问:
Netezza Batch Insert is very slow even in Batch execute mode
I am referring to this documentation. http://www-01.ibm.com/support/docview.wss?uid=swg21981328. As per the article if we use executeBatch method then inserts will be faster (The Netezza JDBC driver may detect a batch insert, and under the covers convert this to an external table load and external table load will be faster). I had to execute millions of insert statements  and i am getting only a speed of 500 records per minute per connection max. Is there any better way to load data faster to netezza via jdbc connection? I am using spark and jdbc connection to insert the records.Why external table via loading is not happening even when i am executing in batches. Given below is the spark code i am using,</p>

```<code>Dataset<String> insertQueryDataSet.foreachPartition( partition -> {
    Connection conn = NetezzaConnector.getSingletonConnection(url, userName, pwd);
    conn.setAutoCommit(false);
    int commitBatchCount = 0;
    int insertBatchCount = 0;
    Statement statement = conn.createStatement();
    //PreparedStatement preparedStmt  = null;
    while(partition.hasNext()){
        insertBatchCount++;
        //preparedStmt = conn.prepareStatement(partition.next());
        statement.addBatch(partition.next());
        //statement.addBatch(partition.next());
        commitBatchCount++;
        if(insertBatchCount % 10000 == 0){
            LOGGER.info("Before executeBatch.");
            int[] execCount = statement.executeBatch();
            LOGGER.info("After execCount." + execCount.length);
            LOGGER.info("Before commit.");
            conn.commit();
            LOGGER.info("After commit.");
        }
    }
    //execute remaining statements
    statement.executeBatch();
    int[] execCount = statement.executeBatch();
    LOGGER.info("After execCount." + execCount.length);
    conn.commit();
    conn.close();

});
</code>```

答:
I tried this approach(batch insert) but found very slow,
So I put all data in CSV & do external table load for each csv.

```<code>InsertReq="Insert into "+ tablename + " select * from external '"+ filepath + "' using (maxerrors 0, delimiter ',' unase 2000 encoding 'internal' remotesource 'jdbc' escapechar '\' )";
Jdbctemplate.execute(InsertReq);
</code>```

Since I was using java so JDBC as source & note that csv file path is in single quotes .
Hope this helps.
If you find better than this approach, don't forget to post. :)

Body:
I am referring to this documentation. http://www-01.ibm.com/support/docview.wss?uid=swg21981328. As per the article if we use executeBatch method then inserts will be faster (The Netezza JDBC driver may detect a batch insert, and under the covers convert this to an external table load and external table load will be faster). I had to execute millions of insert statements  and i am getting only a speed of 500 records per minute per connection max. Is there any better way to load data faster to netezza via jdbc connection? I am using spark and jdbc connection to insert the records.Why external table via loading is not happening even when i am executing in batches. Given below is the spark code i am using,

Dataset<String> insertQueryDataSet.foreachPartition( partition -> {
    Connection conn = NetezzaConnector.getSingletonConnection(url, userName, pwd);
    conn.setAutoCommit(false);
    int commitBatchCount = 0;
    int insertBatchCount = 0;
    Statement statement = conn.createStatement();
    //PreparedStatement preparedStmt  = null;
    while(partition.hasNext()){
        insertBatchCount++;
        //preparedStmt = conn.prepareStatement(partition.next());
        statement.addBatch(partition.next());
        //statement.addBatch(partition.next());
        commitBatchCount++;
        if(insertBatchCount % 10000 == 0){
            LOGGER.info("Before executeBatch.");
            int[] execCount = statement.executeBatch();
            LOGGER.info("After execCount." + execCount.length);
            LOGGER.info("Before commit.");
            conn.commit();
            LOGGER.info("After commit.");
        }
    }
    //execute remaining statements
    statement.executeBatch();
    int[] execCount = statement.executeBatch();
    LOGGER.info("After execCount." + execCount.length);
    conn.commit();
    conn.close();

});

Body:
I tried this approach(batch insert) but found very slow,
So I put all data in CSV & do external table load for each csv.

InsertReq="Insert into "+ tablename + " select * from external '"+ filepath + "' using (maxerrors 0, delimiter ',' unase 2000 encoding 'internal' remotesource 'jdbc' escapechar '\' )";
Jdbctemplate.execute(InsertReq);

Since I was using java so JDBC as source & note that csv file path is in single quotes .
Hope this helps.
If you find better than this approach, don't forget to post. :)


来源: stackexchange

问:
Postgresql create function error
What am I doing wrong in the following function?

```<code>CREATE OR REPLACE FUNCTION extended_sales(area_type varchar, area_code varchar, dpci varchar) RETURNS TABLE(task_id bigint, location_id int)as

$BODY$

BEGIN
    IF area_type = 1 THEN
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where T.task_payload->>'str_area_type_i'='3';
    ELSE IF area_type = 2 THEN
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where T.due_date < '2017-10-06';
    ELSE
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where task_payload->>'str_area_type_i'='1' and task_payload->>'str_area_c'='7'  and due_date < '2016-11-07';
    END IF;

END

$BODY$ language plpgsql;
</code>```

When I run the above function it gives the following error

```<code>ERROR:  syntax error at end of input
LINE 17: $BODY$ language plpgsql;
</code>```

Any help is appreciated. Thanks.

答:
You have two IF statements and one END IF. Use ELSIF if you want to have a single IF statement.</p>

```<code>    IF area_type = 1 THEN
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where T.task_payload->>'str_area_type_i'='3';
    ELSIF area_type = 2 THEN
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where T.due_date < '2017-10-06';
    ELSE
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where task_payload->>'str_area_type_i'='1' and task_payload->>'str_area_c'='7'  and due_date < '2016-11-07';
    END IF;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Postgresql create function error

Body:
What am I doing wrong in the following function?

CREATE OR REPLACE FUNCTION extended_sales(area_type varchar, area_code varchar, dpci varchar) RETURNS TABLE(task_id bigint, location_id int)as

$BODY$

BEGIN
    IF area_type = 1 THEN
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where T.task_payload->>'str_area_type_i'='3';
    ELSE IF area_type = 2 THEN
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where T.due_date < '2017-10-06';
    ELSE
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where task_payload->>'str_area_type_i'='1' and task_payload->>'str_area_c'='7'  and due_date < '2016-11-07';
    END IF;

END

$BODY$ language plpgsql;

When I run the above function it gives the following error

ERROR:  syntax error at end of input
LINE 17: $BODY$ language plpgsql;

Any help is appreciated. Thanks.

Body:
You have two IF statements and one END IF. Use ELSIF if you want to have a single IF statement.

    IF area_type = 1 THEN
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where T.task_payload->>'str_area_type_i'='3';
    ELSIF area_type = 2 THEN
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where T.due_date < '2017-10-06';
    ELSE
        RETURN QUERY select T.task_id, T.location_id from store_price.task T where task_payload->>'str_area_type_i'='1' and task_payload->>'str_area_c'='7'  and due_date < '2016-11-07';
    END IF;


问:
Add noexcept on otherwise-non-throwing inline functions calling C functions?
I've implemented C++ bindings for some C library. The library API calls can fail, but obviously can't throw anything; and my bindings are, for the purposes of this question, all inline.

Now, the compiler can figure out, for most of my inlined functions/methods, that an exception can't be thrown; for example, suppose I have:

```<code>bool foo() {
    auto result = wrapped_lib_foo();
    return some_constexpr_nothrow_cond(result);
}
</code>```

should I mark such functions/methods with noexcept?

Notes:

Not a dupe of Should I use noexcept for simple functions that obviously cannot throw?, as in that case the compiler doesn't know whether the function can throw or not; for C functions - it does know.

The more general question When should I really use noexcept? has potentially conflicting answers, plus, the accepted answer is from 5 years ago and says "it's too early to say".

答:
I think this is good practice to add "noexcept", when you know a function doesn't throw. It is because a C function can throw, if it calls back into C++.

Whether this calling back to C++ and throw is allowed, seems to be compiler dependent. I've checked two compilers:

MSVC: has an option, /EHs, which:

The exception-handling model that catches C++ exceptions only and
  tells the compiler to assume that functions declared as extern "C" may
  throw an exception.

So, if this option is specified, then the compiler assumes that a C function can throw.

GCC: here's the documentation of -fexceptions:

Enable exception handling. Generates extra code needed to propagate
  exceptions. For some targets, this implies GCC generates frame unwind
  information for all functions, which can produce significant data size
  overhead, although it does not affect execution. If you do not specify
  this option, GCC enables it by default for languages like C++ that
  normally require exception handling, and disables it for languages
  like C that do not normally require it. However, you may need to
  enable this option when compiling C code that needs to interoperate
  properly with exception handlers written in C++. You may also wish to
  disable this option if you are compiling older C++ programs that don’t
  use exception handling.

So, this implies that with -fexceptions, GCC compiles C code which can throw. Note, however: when calling a C function, the compiler doesn't know, whether the C code was compiled with -fexceptions, or not. So it has to assume, that it was. So, it seems that GCC must assume, that a C code can throw (the other possible way could be that -fexception would need to be specified for C++ code for telling the compiler that a called C code can throw, but doc of -fexceptions doesn't say anything like this).

Note: for GCC, throwing from a call stack, where a C function is involved, works even without the C code compiled with -fexceptions currently.

Body:
I've implemented C++ bindings for some C library. The library API calls can fail, but obviously can't throw anything; and my bindings are, for the purposes of this question, all inline.

Now, the compiler can figure out, for most of my inlined functions/methods, that an exception can't be thrown; for example, suppose I have:

bool foo() {
    auto result = wrapped_lib_foo();
    return some_constexpr_nothrow_cond(result);
}

should I mark such functions/methods with noexcept?

Notes:

Not a dupe of Should I use noexcept for simple functions that obviously cannot throw?, as in that case the compiler doesn't know whether the function can throw or not; for C functions - it does know.

The more general question When should I really use noexcept? has potentially conflicting answers, plus, the accepted answer is from 5 years ago and says "it's too early to say".


问:
Error ITMS-90717: "Invalid App Store Icon"
When I tried to submit an App to Itunes Connect I got the following error.

```<code>iTunes Store Operation Failed

Error ITMS-90717: "Invalid App Store Icon. The App Store Icon in the asset catalog in 'YourApp.app' can't be transparent nor contain an alpha channel."
</code>```

I made sure that I submitted a file with no transparency. So the error persisted in submission to iTunes Connect.

答:
I faced the same problem and wasn't able to fix it with the provided solution by Shamsudheen TK. Ionic somehow added transparency to my icons even if the source icon did not have any transparency at all. In the end I was able to resolve it by:

Install imagemagick (MacOS):

brew install imagemagick

Remove alpha channel from all images in resource folder:

find ./resources/ -name "*.png" -exec convert "{}" -alpha off "{}" \;

Body:
When I tried to submit an App to Itunes Connect I got the following error.

iTunes Store Operation Failed

Error ITMS-90717: "Invalid App Store Icon. The App Store Icon in the asset catalog in 'YourApp.app' can't be transparent nor contain an alpha channel."

I made sure that I submitted a file with no transparency. So the error persisted in submission to iTunes Connect.


问:
Selenium Path python
My English is bad because i'm french, sorry.
Hello
I want to get starting with selenium, but when I write

```<code>webdriver = webdriver.chrome()
</code>```

The path isn't good.
I hope you help me, i had search, but i dont find.
My python folder:

```<code>C:\Users\ano\AppData\Local\Programs\Python\Python36-32
</code>```

The chromedriver.exe folder:

```<code>C:\Users\ano\AppData\Local\Programs\Python\Python36-32\selenium\chrome
</code>```

I get the error when i write:

```<code>from selenium import webdriver

chrome_path = r"C:\Users\ano\AppData\Local\Programs\Python\Python36-32\selenium\chrome\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
</code>```

I need to change the folder of the chromedriver?
Thanks for your help.
Have a nice day

Error message:

```<code>    "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\python.exe" "C:/Users/FAMILLE ano/PycharmProjects/Project/WebDriver/MyFirstSelenium.py"
Traceback (most recent call last):
  File "C:/Users/FAMILLE ano/PycharmProjects/Project/WebDriver/MyFirstSelenium.py", line 3, in <module>
    driver = webdriver.Chrome(chrome_path)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 69, in __init__
    desired_capabilities=desired_capabilities)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 151, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 240, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Process finished with exit code 1
</code>```

答:
As you are seeing the error as WebDriverException: Message: unknown error: cannot find Chrome binary which means the chromedriver.exe binary is unable to find the chrome.exe binary.

Solution :

Uninstall Google Chrome from your system through Revo Uninstaller.

Confirm there is no trace of Google Chrome in your System and User variables as well as Windows Registry.

Run CCleaner to wipe out all the **OS** chores.

Take a System Reboot

Install the latest version of Google Chrome.

Download the latest version of chromedriver.exe from this link and place it anywhere within your system.

While mentioning the absolute path of chromedriver.exe, either use the single front slash (/) along with the raw (r) switch or the escaped back slash (\\).

Here is your own code with some simple tweaks :

```<code>from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\your_system_path\chromedriver.exe')
</code>```

Title: Selenium Path python

Body:
My English is bad because i'm french, sorry.
Hello
I want to get starting with selenium, but when I write

webdriver = webdriver.chrome()

The path isn't good.
I hope you help me, i had search, but i dont find.
My python folder:

C:\Users\ano\AppData\Local\Programs\Python\Python36-32

The chromedriver.exe folder:

C:\Users\ano\AppData\Local\Programs\Python\Python36-32\selenium\chrome

I get the error when i write:

from selenium import webdriver

chrome_path = r"C:\Users\ano\AppData\Local\Programs\Python\Python36-32\selenium\chrome\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)

I need to change the folder of the chromedriver?
Thanks for your help.
Have a nice day

Error message:

    "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\python.exe" "C:/Users/FAMILLE ano/PycharmProjects/Project/WebDriver/MyFirstSelenium.py"
Traceback (most recent call last):
  File "C:/Users/FAMILLE ano/PycharmProjects/Project/WebDriver/MyFirstSelenium.py", line 3, in <module>
    driver = webdriver.Chrome(chrome_path)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 69, in __init__
    desired_capabilities=desired_capabilities)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 151, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 240, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Users\FAMILLE ano\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Process finished with exit code 1

Body:
As you are seeing the error as WebDriverException: Message: unknown error: cannot find Chrome binary which means the chromedriver.exe binary is unable to find the chrome.exe binary.

Solution :

Uninstall Google Chrome from your system through Revo Uninstaller.

Confirm there is no trace of Google Chrome in your System and User variables as well as Windows Registry.

Run CCleaner to wipe out all the **OS** chores.

Take a System Reboot

Install the latest version of Google Chrome.

Download the latest version of chromedriver.exe from this link and place it anywhere within your system.

While mentioning the absolute path of chromedriver.exe, either use the single front slash (/) along with the raw (r) switch or the escaped back slash (\\).

Here is your own code with some simple tweaks :

from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\your_system_path\chromedriver.exe')


问:
load JS function before PHP validation
I'm trying to (echo) call a javascript function from PHP when the form is submitted. I have an error that function is not defined. I do understand that PHP is loaded before Javascript, therefore, the function is not defined in PHP call.

I could create onclick even in the HTML section but the example below is part of a bigger program and PHP script is in a separate file which is included at the top of the HTML page, the function will also receive different parameters and perform different operations when called and it will be an AJAX function. Also, I have some variables loaded as page renders and I only want to call the JS function at a certain point in the program. Moving PHP to the bottom is not elegant as I would have to add some PHP at the top some at the bottom to have all variables included.

Is there a way to include the PHP part at the top and still call an AJAX function whenever required with a range of parameters? Or even better what is the best way of doing this sort of thing? I believe echo'ing javascript through PHP is not the best practice.

```<code><?php

if (isset($_POST['a'])) {
  echo "<script type='text/javascript'>example('hello');</script>";
  echo "<script type='text/javascript'>printSome(0,0);</script>";
}

?>

<!DOCTYPE html>
<html>
<body>

<form method="post">
  <input type="text">
  <input type="submit" name="a">
</form>

</body>

<script type='text/javascript'>
  function example(variable)
  {
    window.alert(variable);
  }

  function printSome(type, quantity)
  {
   return $.ajax({
   url                   : 'http://localhost/printDoc.php',
   type                  : 'POST',
   dataType              : 'json',
   data                  : {
                              DTStype      : type,
                              DTSquantity  : quantity
                           },
   cache                 : false
});
}

</script>
</html>
</code>```

答:
This happens just because when it tries to execute the example function, it was not yet defined.
You can overcome this by using an event listener:

```<code>document.addEventListener("DOMContentLoaded", function(event) {
  example('hello');
});
</code>```

More than that, having script tags outside body is not valid, although probably most browser would still run it. Therefore, I suggest you to move the entire php section of the page somewhere inside the body../body tag.

Title: load JS function before PHP validation

Body:
I'm trying to (echo) call a javascript function from PHP when the form is submitted. I have an error that function is not defined. I do understand that PHP is loaded before Javascript, therefore, the function is not defined in PHP call.

I could create onclick even in the HTML section but the example below is part of a bigger program and PHP script is in a separate file which is included at the top of the HTML page, the function will also receive different parameters and perform different operations when called and it will be an AJAX function. Also, I have some variables loaded as page renders and I only want to call the JS function at a certain point in the program. Moving PHP to the bottom is not elegant as I would have to add some PHP at the top some at the bottom to have all variables included.

Is there a way to include the PHP part at the top and still call an AJAX function whenever required with a range of parameters? Or even better what is the best way of doing this sort of thing? I believe echo'ing javascript through PHP is not the best practice.

<?php

if (isset($_POST['a'])) {
  echo "";
  echo "";
}

?>

<!DOCTYPE html>

<form method="post">
  <input type="text">
  <input type="submit" name="a">
</form>

Body:
This happens just because when it tries to execute the example function, it was not yet defined.
You can overcome this by using an event listener:

document.addEventListener("DOMContentLoaded", function(event) {
  example('hello');
});

More than that, having script tags outside body is not valid, although probably most browser would still run it. Therefore, I suggest you to move the entire php section of the page somewhere inside the body../body tag.


问:
In search bar when i am searching key , its still making total no page either there is matches in table or not
When i am searching in search bar , its not making total no page based on search key element here is code

```<code><?php
                 $total_num_page=2;
               if (isset($_GET['page']))
                    {
                        $page_id = $_GET['page'];
                    }
               else
                    {
                        $page_id = 1;
                    }
                    $search = '' ;
                    if( isset($_POST['search']) )
                    {
                        $search = urldecode($_POST['search']);
                    }
                    else if( isset($_GET['search']) )
                    {
                        $search = urldecode($_GET['search']);
                    }
              if ( $search )
              {
                        $all_post_query = "select * from files where recieved_by like '%" . $search . "%' or processed_by like  '%" . $search . "%' or   purpose like  '%" . $search . "%' or file_name like  '%" . $_SESSION["search"] . "%' order by date desc";
                        $all_post_run = mysqli_query($con, $all_post_query);
                        $all_post = mysqli_num_rows($all_post_run);
                        $total_page = ceil($all_post / $total_num_page);
                        $page_start_from = ($page_id - 1) * $total_num_page;
              }
               else {
                    $all_post_query = "select * from files order by date desc";
                    $all_post_run = mysqli_query($con, $all_post_query);
                    $all_post = mysqli_num_rows($all_post_run);
                    $total_page = ceil($all_post / $total_num_page);
                    $page_start_from = ($page_id - 1) * $total_num_page;
                    }

               ?>
</code>```

and this is place where table is fetching data

```<code> <?php
                            if ( $search )
                            {
                                $p_query = "select * from files where recieved_by like '%$search%' or processed_by like  '%$search%' or   purpose like  '%$search%' or file_name like '%$search%' order by date desc limit $page_start_from, $total_num_page";
                            }
                            else
                            {

                                $p_query = "select * from files order by date desc limit $page_start_from, $total_num_page";
                            }
                          $p_run=mysqli_query($con,$p_query);
                            if(mysqli_num_rows($p_run)){
                             while($row=mysqli_fetch_array($p_run))
                             {
                                $c_id=$row['id'];
                                $file=$row['file_name'];
                                $purpose=$row['purpose'];
                                $recieve=$row['recieved_by'];
                                $processed=$row['processed_by'];
                                $address=$row['address'];
                                $contact=$row['contact_no'];
                                $date=$row['date'];

                            ?>
</code>```

and this is pagination code

```<code><ul class="pagination">
        <?php
        $search_str = '';
        if ($search) {
            $search_str = "&search=" . urlencode($search);
        }
        for ($i = 1; $i <= $total_page; $i++)
            echo "<li class='" . ($page_id == $i ? 'active' : '') . "'><a href='index.php?page=" . $i . $search_str . "'>$i</a></li>";
        ?>

    </ul>
</code>```

and this is the problem in picture in which when i am searching key in search bar its making total no page and showing total number of pages , which is wrong , some one help me please

答:
This Uses search string from POST when posted, uses GET when you click on a page link. If not uses null string.

```<code>    if (isset($_GET['page'])) {
        $page_id = $_GET['page'];
    } else {
        $page_id = 1;
    }
    $search = '' ;
    if( isset($_POST['search']) ) {
        $search = urldecode($_POST['search']);
    }
    else if( isset($_GET['search']) ) {
        $search = urldecode($_GET['search']);
    }
</code>```

Here we uses that keyword in query.

Suggestion : Change query to use COUNT(*) to find the total records instead of using num_rows.

```<code>    if ( $search ) {

        $all_post_query = "select * from files where recieved_by like '%" . $search . "%' or processed_by like  '%" . $search . "%' or   purpose like  '%" . $search . "%' or file_name like  '%" . $search . "%' order by date desc";
        $all_post_run = mysqli_query($con, $all_post_query);
        $all_post = mysqli_num_rows($all_post_run);
        $total_page = ceil($all_post / $total_num_page);
        $page_start_from = ($page_id - 1) * $total_num_page;
    } else {
        $all_post_query = "select * from files order by date desc";
        $all_post_run = mysqli_query($con, $all_post_query);
        $all_post = mysqli_num_rows($all_post_run);
        $total_page = ceil($all_post / $total_num_page);
        $page_start_from = ($page_id - 1) * $total_num_page;
    }
</code>```

Also here

```<code><?php
if ( $search ) {
    $p_query = "select * from files where recieved_by like '%$search%' or processed_by like  '%$search%' or   purpose like  '%$search%' or file_name like '%$search%' order by date desc limit $page_start_from, $total_num_page";
} else {

    $p_query = "select * from files order by date desc limit $page_start_from, $total_num_page";
}
</code>```

Finaly in your pagination append search keyword. With this you loose seach keyword when you click a link other than pagination.

```<code><ul class="pagination">
            <?php
            $search_str = '';
            if ($search) {
                $search_str = "&search=" . urlencode($search);
            }
            for ($i = 1; $i <= $total_page; $i++)
                echo "<li class='" . ($page_id == $i ? 'active' : '') . "'><a href='index.php?page=" . $i . $search_str . "'>$i</a></li>";
            ?>

</ul>
</code>```

Body:
When i am searching in search bar , its not making total no page based on search key element here is code

<?php
                 $total_num_page=2;
               if (isset($_GET['page']))
                    {
                        $page_id = $_GET['page'];
                    }
               else
                    {
                        $page_id = 1;
                    }
                    $search = '' ;
                    if( isset($_POST['search']) )
                    {
                        $search = urldecode($_POST['search']);
                    }
                    else if( isset($_GET['search']) )
                    {
                        $search = urldecode($_GET['search']);
                    }
              if ( $search )
              {
                        $all_post_query = "select * from files where recieved_by like '%" . $search . "%' or processed_by like  '%" . $search . "%' or   purpose like  '%" . $search . "%' or file_name like  '%" . $_SESSION["search"] . "%' order by date desc";
                        $all_post_run = mysqli_query($con, $all_post_query);
                        $all_post = mysqli_num_rows($all_post_run);
                        $total_page = ceil($all_post / $total_num_page);
                        $page_start_from = ($page_id - 1) * $total_num_page;
              }
               else {
                    $all_post_query = "select * from files order by date desc";
                    $all_post_run = mysqli_query($con, $all_post_query);
                    $all_post = mysqli_num_rows($all_post_run);
                    $total_page = ceil($all_post / $total_num_page);
                    $page_start_from = ($page_id - 1) * $total_num_page;
                    }

               ?>

and this is place where table is fetching data

 <?php
                            if ( $search )
                            {
                                $p_query = "select * from files where recieved_by like '%$search%' or processed_by like  '%$search%' or   purpose like  '%$search%' or file_name like '%$search%' order by date desc limit $page_start_from, $total_num_page";
                            }
                            else
                            {

                                $p_query = "select * from files order by date desc limit $page_start_from, $total_num_page";
                            }
                          $p_run=mysqli_query($con,$p_query);
                            if(mysqli_num_rows($p_run)){
                             while($row=mysqli_fetch_array($p_run))
                             {
                                $c_id=$row['id'];
                                $file=$row['file_name'];
                                $purpose=$row['purpose'];
                                $recieve=$row['recieved_by'];
                                $processed=$row['processed_by'];
                                $address=$row['address'];
                                $contact=$row['contact_no'];
                                $date=$row['date'];

                            ?>

and this is pagination code

        <?php
        $search_str = '';
        if ($search) {
            $search_str = "&search=" . urlencode($search);
        }
        for ($i = 1; $i <= $total_page; $i++)
            echo "
$i
";
        ?>

and this is the problem in picture in which when i am searching key in search bar its making total no page and showing total number of pages , which is wrong , some one help me please

Body:
This Uses search string from POST when posted, uses GET when you click on a page link. If not uses null string.

    if (isset($_GET['page'])) {
        $page_id = $_GET['page'];
    } else {
        $page_id = 1;
    }
    $search = '' ;
    if( isset($_POST['search']) ) {
        $search = urldecode($_POST['search']);
    }
    else if( isset($_GET['search']) ) {
        $search = urldecode($_GET['search']);
    }

Here we uses that keyword in query.

Suggestion : Change query to use COUNT(*) to find the total records instead of using num_rows.

    if ( $search ) {

        $all_post_query = "select * from files where recieved_by like '%" . $search . "%' or processed_by like  '%" . $search . "%' or   purpose like  '%" . $search . "%' or file_name like  '%" . $search . "%' order by date desc";
        $all_post_run = mysqli_query($con, $all_post_query);
        $all_post = mysqli_num_rows($all_post_run);
        $total_page = ceil($all_post / $total_num_page);
        $page_start_from = ($page_id - 1) * $total_num_page;
    } else {
        $all_post_query = "select * from files order by date desc";
        $all_post_run = mysqli_query($con, $all_post_query);
        $all_post = mysqli_num_rows($all_post_run);
        $total_page = ceil($all_post / $total_num_page);
        $page_start_from = ($page_id - 1) * $total_num_page;
    }

Also here

<?php
if ( $search ) {
    $p_query = "select * from files where recieved_by like '%$search%' or processed_by like  '%$search%' or   purpose like  '%$search%' or file_name like '%$search%' order by date desc limit $page_start_from, $total_num_page";
} else {

    $p_query = "select * from files order by date desc limit $page_start_from, $total_num_page";
}

Finaly in your pagination append search keyword. With this you loose seach keyword when you click a link other than pagination.

<ul class="pagination">
            <?php
            $search_str = '';
            if ($search) {
                $search_str = "&search=" . urlencode($search);
            }
            for ($i = 1; $i <= $total_page; $i++)
                echo "<li class='" . ($page_id == $i ? 'active' : '') . "'><a href='index.php?page=" . $i . $search_str . "'>$i</a></li>";
            ?>

</ul>


问:
Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]
I am new to spring mvc and facing this issue with session factory
"Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]"

I added all required jars to class path but it still exists

here is my  spring-mvc-crud-demo-servlet.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"

    xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx.xsd">

<context:component-scan base-package="com.luv2code.springdemo" />
<mvc:annotation-driven/>

<!-- Configuration defining views files -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/view/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
</bean>

<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/customer_db?useSSL=false"/>
        <property name="user" value="newuser"/>
        <property name="password" value="newuser"/>

        <property name="minPoolSize" value="5"/>
        <property name="maxPoolSize" value="20"/>
        <property name="maxIdleTime" value="3000"/>

    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="packagesToScan" value="com.luv2code.springdemo.entity"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.mySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="myTransactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="myTransactionManager" />

</beans>
</code>```

and this is my web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app>
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
```

答:
```<code><prop key="hibernate.dialect">org.hibernate.dialect.mySQLDialect</prop>
</code>```

must be

```<code><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</code>```

Here you reference a class and this is case sensitiv. So my must be My with uppercase M

Body:
I am new to spring mvc and facing this issue with session factory
"Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]"

I added all required jars to class path but it still exists

here is my  spring-mvc-crud-demo-servlet.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"

    xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx.xsd">

<context:component-scan base-package="com.luv2code.springdemo" />
<mvc:annotation-driven/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/view/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
</bean>

<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/customer_db?useSSL=false"/>
        <property name="user" value="newuser"/>
        <property name="password" value="newuser"/>

        <property name="minPoolSize" value="5"/>
        <property name="maxPoolSize" value="20"/>
        <property name="maxIdleTime" value="3000"/>

    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="packagesToScan" value="com.luv2code.springdemo.entity"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.mySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="myTransactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="myTransactionManager" />

</beans>

and this is my web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app>
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Body:
<prop key="hibernate.dialect">org.hibernate.dialect.mySQLDialect</prop>

must be

<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

Here you reference a class and this is case sensitiv. So my must be My with uppercase M


问:
Only display one paragraph of text
You can set what the Facebook Share preview says. I would like it to be the first paragraph of my movable type entry. The people who make entries sometimes use

```<code><p>
</code>```

tags or they use the rich editor which puts in two

```<code><br /><br />
</code>```

tags to separate paragraphs.

Is there a way I can have movable type detect when the first paragraph end and only display the first paragraph? I would like to add that to my entry template so it will add some information to my head.

答:
EntryBody has a lot of attributes to help format the output of the tag. You can use those to change the content so it shows up correctly in HTML, JavaScript, PHP, XML or other forms of output.

If you understand how to use regular expressions, you can use that and an additional language, say PHP, to break the body up into an array and only output the first paragraph or element of the array.

The simplest thing, though, I would think, would be to do something like

```<code><mt:EntryBody words=100>
</code>```

That will cut off the entry body after the first 100 words. You could also require users to upload an excerpt with the entry and use the entry excerpt for Facebook, instead.

ContentLicense: CC BY-SA 2.5

Title: Only display one paragraph of text

Body:
You can set what the Facebook Share preview says. I would like it to be the first paragraph of my movable type entry. The people who make entries sometimes use

tags or they use the rich editor which puts in two

tags to separate paragraphs.

Is there a way I can have movable type detect when the first paragraph end and only display the first paragraph? I would like to add that to my entry template so it will add some information to my head.

Body:
EntryBody has a lot of attributes to help format the output of the tag. You can use those to change the content so it shows up correctly in HTML, JavaScript, PHP, XML or other forms of output.

If you understand how to use regular expressions, you can use that and an additional language, say PHP, to break the body up into an array and only output the first paragraph or element of the array.

The simplest thing, though, I would think, would be to do something like

<mt:EntryBody words=100>

That will cut off the entry body after the first 100 words. You could also require users to upload an excerpt with the entry and use the entry excerpt for Facebook, instead.


问:
Composite Primary Keys in Rails still being ignored
I've set up a database that has composite primary keys for Ruby on Rails. Creating the migration works, but when I start to seed the database, I still get a warning that "Active Record does not support primary keys." and that the "Composite primary key is ignored." even after I've installed the composite_primary_keys gem, and included require 'composite_primary_keys' into the environments.rb file.

Any thoughts as to why the composite primary key is still ignored?

答: Well, I found the work-around to this. For every model that I had that has composite primary keys, I included require 'composite_primary_keys' on the start of the class. Seems to work for me.

ContentLicense: CC BY-SA 4.0


问:
Scikit-Learn Decision Tree: Probability of prediction being a or b?
I have a basic decision tree classifier with Scikit-Learn:

```<code>#Used to determine men from women based on height and shoe size

from sklearn import tree

#height and shoe size
X = [[65,9],[67,7],[70,11],[62,6],[60,7],[72,13],[66,10],[67,7.5]]

Y=["male","female","male","female","female","male","male","female"]

#creating a decision tree
clf = tree.DecisionTreeClassifier()

#fitting the data to the tree
clf.fit(X, Y)

#predicting the gender based on a prediction
prediction = clf.predict([68,9])

#print the predicted gender
print(prediction)
</code>```

When I run the program, it always outputs either "male" or "female", but how would I be able to see the probability of the prediction being male or female? For example, the prediction above returns "male", but how would I get it to print the probability of the prediction being male?

Thanks!

答:
You can do something like the following:

```<code>from sklearn import tree

#load data
X = [[65,9],[67,7],[70,11],[62,6],[60,7],[72,13],[66,10],[67,7.5]]
Y=["male","female","male","female","female","male","male","female"]

#build model
clf = tree.DecisionTreeClassifier()

#fit
clf.fit(X, Y)

#predict
prediction = clf.predict([[68,9],[66,9]])

#probabilities
probs = clf.predict_proba([[68,9],[66,9]])

#print the predicted gender
print(prediction)
print(probs)
</code>```

Theory

The result of clf.predict_proba(X) is: The predicted class probability which is the fraction of samples of the same class in a leaf.

Interpretation of the results:

The first print returns ['male' 'male'] so the data [[68,9],[66,9]] are predicted as males.

The second print returns:

[[ 0.  1.]
  [ 0.  1.]]

This means that the data were predicted as males and this is reported by the ones in the second column.

To see the order of the classes use: clf.classes_

This returns: ['female', 'male']

Body:
I have a basic decision tree classifier with Scikit-Learn:

#Used to determine men from women based on height and shoe size

from sklearn import tree

#height and shoe size
X = [[65,9],[67,7],[70,11],[62,6],[60,7],[72,13],[66,10],[67,7.5]]

Y=["male","female","male","female","female","male","male","female"]

#creating a decision tree
clf = tree.DecisionTreeClassifier()

#fitting the data to the tree
clf.fit(X, Y)

#predicting the gender based on a prediction
prediction = clf.predict([68,9])

#print the predicted gender
print(prediction)

When I run the program, it always outputs either "male" or "female", but how would I be able to see the probability of the prediction being male or female? For example, the prediction above returns "male", but how would I get it to print the probability of the prediction being male?

Thanks!

Body:
You can do something like the following:

from sklearn import tree

#load data
X = [[65,9],[67,7],[70,11],[62,6],[60,7],[72,13],[66,10],[67,7.5]]
Y=["male","female","male","female","female","male","male","female"]

#build model
clf = tree.DecisionTreeClassifier()

#fit
clf.fit(X, Y)

#predict
prediction = clf.predict([[68,9],[66,9]])

#probabilities
probs = clf.predict_proba([[68,9],[66,9]])

#print the predicted gender
print(prediction)
print(probs)

Theory

The result of clf.predict_proba(X) is: The predicted class probability which is the fraction of samples of the same class in a leaf.

Interpretation of the results:

The first print returns ['male' 'male'] so the data [[68,9],[66,9]] are predicted as males.

The second print returns:

[[ 0.  1.]
  [ 0.  1.]]

This means that the data were predicted as males and this is reported by the ones in the second column.

To see the order of the classes use: clf.classes_

This returns: ['female', 'male']


问:
SWIG python binding for c does not find _EXFUN for standard headers
I am trying to use SWIG python binding for a c file. The c file compiles fine. The SWIG generated _wrap.c file does not compile because the compiler canot find the definitions for the _EXFUN coming from wchar.h getting included somehow.

```<code>int _EXFUN(wcsncmp, (const wchar_t *, const wchar_t *, size_t));
</code>```

The environment is :
msys with arm-none-eabi.
Anaconda2-5.0.1-Windows-x86 32bit

I am in a deadend trying to find the cause. Any help is very much appreciated.
Thanks.

答:
The above problem occured while I tried to compile with gcc arm-none-eabi tool chain. And I could not solve the problem.

Then I changed the tool chain to TDM-GCC-32 and reorder the headers and the above issue disappeared. Still no idea why it is occuring with the arm-none-eabi option.

Body:
I am trying to use SWIG python binding for a c file. The c file compiles fine. The SWIG generated _wrap.c file does not compile because the compiler canot find the definitions for the _EXFUN coming from wchar.h getting included somehow.

int _EXFUN(wcsncmp, (const wchar_t *, const wchar_t *, size_t));

The environment is :
msys with arm-none-eabi.
Anaconda2-5.0.1-Windows-x86 32bit

I am in a deadend trying to find the cause. Any help is very much appreciated.
Thanks.


问:
Determine major Java version across all Java releases
When determining the major Java version on Java 8 and before it was common to use the system property java.specification.version, drop 1., and parse the second digit:

on Java 8 this would yield "1.8" ~> "8" ~> 8

on Java 9 the same calls leads to NumberFormatException because the system property is "9"

What is a future-proof way to determine the major Java version? The goal is to get an int that can be if-ed or switch-ed over to decide which code path to take (e.g. in a library to activate a feature).

答:
Of course, it depends on the goal of the operation. If you want to report it to the user in a Java marketing compatible way, you have to face the fact that the marketing itself never used a consistent labeling and may retroactively relabel old versions.

If the check is only intended to ensure the presence of certain features or bug fixes, just assigning an ascending number to every release would be sufficient. Then, you may assign 0 to Java 1.0, which is significantly different from Java 1.1 (assign 1 to it) and get a consistent numbering up to nine using

```<code>public static int getMajorVersion() {
    String version = System.getProperty("java.class.version");
    int p = version.indexOf('.');
    if(p>0) version = version.substring(0, p);
    return Integer.parseInt(version)-44;
}
</code>```

The good thing about the class file version is that it is bound to a more formal definition, as it has to fit into the two fields of a class file, so it can’t be subject to scheme changes nor retroactive redefinition. Also, there is no room for prose like “beta”, “final”, or “please interpret differently” in these two version numbers. The only thing, the code above protects against, is the potential omission of the .0 minor number which has not been used since Java 1.1, as the major class file version has been incremented for every release.

Of course, there is no guaranty that the number will be incremented again in each of the next releases, however, this is not an issue for compatibility checks, as it will always have at least the number of the previous release, being interpreted as “compatible with the previous release”. To start using newer features, you have to touch the source code anyway. In that case, you may add the Runtime.version() based operation for these future releases…

But note that you get this for free when compiling with -target or --release, as the required minimum version is written into the class file anyway and older JVM versions will refuse to execute your code. When you want to optionally support features of a version newer than the minimum release, you have to access them dynamically anyway, so in this case, you can simply make a reflective attempt to use the feature, going to the fallback code if failed, and don’t need to do an additional version number check. That’s exactly what you are doing when trying to implement getMajorVersion() doing a reflective Runtime.version().major(), without a preceding version based check for the presence of that feature.

Body:
Of course, it depends on the goal of the operation. If you want to report it to the user in a Java marketing compatible way, you have to face the fact that the marketing itself never used a consistent labeling and may retroactively relabel old versions.

If the check is only intended to ensure the presence of certain features or bug fixes, just assigning an ascending number to every release would be sufficient. Then, you may assign 0 to Java 1.0, which is significantly different from Java 1.1 (assign 1 to it) and get a consistent numbering up to nine using

public static int getMajorVersion() {
    String version = System.getProperty("java.class.version");
    int p = version.indexOf('.');
    if(p>0) version = version.substring(0, p);
    return Integer.parseInt(version)-44;
}

The good thing about the class file version is that it is bound to a more formal definition, as it has to fit into the two fields of a class file, so it can’t be subject to scheme changes nor retroactive redefinition. Also, there is no room for prose like “beta”, “final”, or “please interpret differently” in these two version numbers. The only thing, the code above protects against, is the potential omission of the .0 minor number which has not been used since Java 1.1, as the major class file version has been incremented for every release.

Of course, there is no guaranty that the number will be incremented again in each of the next releases, however, this is not an issue for compatibility checks, as it will always have at least the number of the previous release, being interpreted as “compatible with the previous release”. To start using newer features, you have to touch the source code anyway. In that case, you may add the Runtime.version() based operation for these future releases…

But note that you get this for free when compiling with -target or --release, as the required minimum version is written into the class file anyway and older JVM versions will refuse to execute your code. When you want to optionally support features of a version newer than the minimum release, you have to access them dynamically anyway, so in this case, you can simply make a reflective attempt to use the feature, going to the fallback code if failed, and don’t need to do an additional version number check. That’s exactly what you are doing when trying to implement getMajorVersion() doing a reflective Runtime.version().major(), without a preceding version based check for the presence of that feature.


问:
Sigabrt on Main function
I've just began to learn iOS development and now I have a sigabrt on my main function. The error is triggered by calling:

```<code>    int retVal = UIApplicationMain(argc, argv, nil, nil);
</code>```

As I am very new to iOS programming I have no idea on what could by causing this error. One thing that I have found on my callstack is the following exception being raised: dyld_stub_objc_exception_throw
What could be causing this error?

答:
UIApplicationMain basically kicks off the rest of your application, so the actual cause of the crash could be anywhere in your application. You may need to look further down the call stack.

However, I note that you're passing nil as the final two parameters. The first nil is the principalClassName argument, which can legally be nil if you want UIApplication to be the principal class. The second nil is the application delegate name; you should pass nil if you load the delegate from the main nib. Do you? If you don't, that might be the problem (I can't say I've ever called this function with both of those arguments nil).

Title: Sigabrt on Main function

Body:
I've just began to learn iOS development and now I have a sigabrt on my main function. The error is triggered by calling:

    int retVal = UIApplicationMain(argc, argv, nil, nil);

As I am very new to iOS programming I have no idea on what could by causing this error. One thing that I have found on my callstack is the following exception being raised: dyld_stub_objc_exception_throw
What could be causing this error?


问:
How to make a Contact Form 7 responsive
I need to make my Contact form 7 responsive. It is aligned right of an image but covers the image when screen size is reduced.

Image css

```<code>#ImageDiv{
margin-right: auto;
max-width:800px;
top: -30px;
position: relative;
left: -25px;
</code>```

}

```<code><div id="ImageDiv"><img alt="" src="https://image.png" height="auto" />
</code>```

Contact Form 7

```<code><div style="background-color:green;padding:5px 5px 5px 5px">
<div style="text-align: center;color:white;padding-bottom:5px">HEADER</div>

<div style="margin-bottom:5px"><div style="color:white; display:inline-block;padding-right:10px;width:30%">Name:</div>
<div style=" display:inline-block;width:65%">[text* your-name]</div></div>

<div style="margin-bottom:5px"><div style="color:white; display:inline-block;padding-right:10px;width:30%">Surname:</div>
<div style="display:inline-block;width:65%">[text* your-name]</div></div>

<div style="margin-bottom:5px"><div style="color:white; display:inline-block;padding-right:10px;width:30%">Email:</div>
<div style="display:inline-block;width:65%">[text* your-name]</div></div>

<div style="margin-bottom:5px;text-align:center">[submit "SUBMIT"]</div>
</div>
</code>```

答: You can now use the Smart Grid-layout design for cf7 plugin which has a grid form editor as well as giving you many other features to make responsive and complex forms.</p>

Title: How to make a Contact Form 7 responsive

Body:
I need to make my Contact form 7 responsive. It is aligned right of an image but covers the image when screen size is reduced.

Image css

#ImageDiv{
margin-right: auto;
max-width:800px;
top: -30px;
position: relative;
left: -25px;

}

Contact Form 7

HEADER

Name:

[text* your-name]

Surname:

[text* your-name]

Email:

[text* your-name]

[submit "SUBMIT"]


问:
Stacked chart with data array
I try to create stacked bar chart like https://bl.ocks.org/mbostock/1134768. But I don't want to use .tsv file

How can I create the stacked bar chart with an array like below?

```<code>var data=[
    {date:'Jan',total:100, disease:20, wounds: 5,  other: 10},
    {date:'Feb',total:200, disease:25, wounds: 10, other: 20}
];
</code>```

Any suggestion should be appreciated.

答:
These are the steps for the bl.ocks you linked (have in mind that, since you didn't provide your code, I'll write the answer to that bl.ocks specifically):

Hardcode your data:

```<code>var crimea = [{
    date: "4/1854",
    total: "8571",
    disease: "1",
    wounds: "0",
    other: "5"
}, {
    date: "5/1854",
    total: "23333",
    disease: "12",
    wounds: "0",
    other: "9"
},
etc...
]
</code>```

Move the row function to a forEach loop:

```<code>crimea.forEach(function(d) {
    d.date = parseDate(d.date);
    causes.forEach(function(c) {
        d[c] = +d[c];
    });
})
</code>```

Get rid of the TSV.

This is the code with those changes:

  ```

Title: Stacked chart with data array

Body:
I try to create stacked bar chart like https://bl.ocks.org/mbostock/1134768. But I don't want to use .tsv file

How can I create the stacked bar chart with an array like below?

var data=[
    {date:'Jan',total:100, disease:20, wounds: 5,  other: 10},
    {date:'Feb',total:200, disease:25, wounds: 10, other: 20}
];

Any suggestion should be appreciated.

Body:
These are the steps for the bl.ocks you linked (have in mind that, since you didn't provide your code, I'll write the answer to that bl.ocks specifically):

Hardcode your data:

var crimea = [{
    date: "4/1854",
    total: "8571",
    disease: "1",
    wounds: "0",
    other: "5"
}, {
    date: "5/1854",
    total: "23333",
    disease: "12",
    wounds: "0",
    other: "9"
},
etc...
]

Move the row function to a forEach loop:

crimea.forEach(function(d) {
    d.date = parseDate(d.date);
    causes.forEach(function(c) {
        d[c] = +d[c];
    });
})

Get rid of the TSV.

This is the code with those changes:

<style>
  .axis text {
    font: 10px sans-serif;
  }

  .axis line,
  .axis path {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }

  .axis--x path {
    display: none;
  }
</style>

<body>
  <script src="//d3js.org/d3.v3.min.js"></script>
  <script>
    var causes = ["wounds", "other", "disease"];

    var parseDate = d3.time.format("%m/%Y").parse;

    var margin = {
        top: 20,
        right: 50,
        bottom: 30,
        left: 20
      },
      width = 960 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;

    var x = d3.scale.ordinal()
      .rangeRoundBands([0, width]);

    var y = d3.scale.linear()
      .rangeRound([height, 0]);

    var z = d3.scale.category10();

    var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom")
      .tickFormat(d3.time.format("%b"));

    var yAxis = d3.svg.axis()
      .scale(y)
      .orient("right");

    var svg = d3.select("body").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var crimea = [{
        date: "4/1854",
        total: "8571",
        disease: "1",
        wounds: "0",
        other: "5"
      },
      {
        date: "5/1854",
        total: "23333",
        disease: "12",
        wounds: "0",
        other: "9"
      },
      {
        date: "6/1854",
        total: "28333",
        disease: "11",
        wounds: "0",
        other: "6"
      },
      {
        date: "7/1854",
        total: "28772",
        disease: "359",
        wounds: "0",
        other: "23"
      },
      {
        date: "8/1854",
        total: "30246",
        disease: "828",
        wounds: "1",
        other: "30"
      },
      {
        date: "9/1854",
        total: "30290",
        disease: "788",
        wounds: "81",
        other: "70"
      },
      {
        date: "10/1854",
        total: "30643",
        disease: "503",
        wounds: "132",
        other: "128"
      },
      {
        date: "11/1854",
        total: "29736",
        disease: "844",
        wounds: "287",
        other: "106"
      },
      {
        date: "12/1854",
        total: "32779",
        disease: "1725",
        wounds: "114",
        other: "131"
      },
      {
        date: "1/1855",
        total: "32393",
        disease: "2761",
        wounds: "83",
        other: "324"
      },
      {
        date: "2/1855",
        total: "30919",
        disease: "2120",
        wounds: "42",
        other: "361"
      },
      {
        date: "3/1855",
        total: "30107",
        disease: "1205",
        wounds: "32",
        other: "172"
      },
      {
        date: "4/1855",
        total: "32252",
        disease: "477",
        wounds: "48",
        other: "57"
      },
      {
        date: "5/1855",
        total: "35473",
        disease: "508",
        wounds: "49",
        other: "37"
      },
      {
        date: "6/1855",
        total: "38863",
        disease: "802",
        wounds: "209",
        other: "31"
      },
      {
        date: "7/1855",
        total: "42647",
        disease: "382",
        wounds: "134",
        other: "33"
      },
      {
        date: "8/1855",
        total: "44614",
        disease: "483",
        wounds: "164",
        other: "25"
      },
      {
        date: "9/1855",
        total: "47751",
        disease: "189",
        wounds: "276",
        other: "20"
      },
      {
        date: "10/1855",
        total: "46852",
        disease: "128",
        wounds: "53",
        other: "18"
      },
      {
        date: "11/1855",
        total: "37853",
        disease: "178",
        wounds: "33",
        other: "32"
      },
      {
        date: "12/1855",
        total: "43217",
        disease: "91",
        wounds: "18",
        other: "28"
      },
      {
        date: "1/1856",
        total: "44212",
        disease: "42",
        wounds: "2",
        other: "48"
      },
      {
        date: "2/1856",
        total: "43485",
        disease: "24",
        wounds: "0",
        other: "19"
      },
      {
        date: "3/1856",
        total: "46140",
        disease: "15",
        wounds: "0",
        other: "35"
      }
    ];

    crimea.forEach(function(d) {
      d.date = parseDate(d.date);
      causes.forEach(function(c) {
        d[c] = +d[c];
      });
    })

    var layers = d3.layout.stack()(causes.map(function(c) {
      return crimea.map(function(d) {
        return {
          x: d.date,
          y: d[c]
        };
      });
    }));

    x.domain(layers[0].map(function(d) {
      return d.x;
    }));
    y.domain([0, d3.max(layers[layers.length - 1], function(d) {
      return d.y0 + d.y;
    })]).nice();

    var layer = svg.selectAll(".layer")
      .data(layers)
      .enter().append("g")
      .attr("class", "layer")
      .style("fill", function(d, i) {
        return z(i);
      });

    layer.selectAll("rect")
      .data(function(d) {
        return d;
      })
      .enter().append("rect")
      .attr("x", function(d) {
        return x(d.x);
      })
      .attr("y", function(d) {
        return y(d.y + d.y0);
      })
      .attr("height", function(d) {
        return y(d.y0) - y(d.y + d.y0);
      })
      .attr("width", x.rangeBand() - 1);

    svg.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    svg.append("g")
      .attr("class", "axis axis--y")
      .attr("transform", "translate(" + width + ",0)")
      .call(yAxis);
  </script>


问:
Start solution build from VSIX command
I'm creating a Visual Studio Extension and want to create a command to build the current solution and start debugging afterwards, so that I have to press one button and wait instead of starting build, waiting and then run.

How can I call Visual Studio's default commands from my command?

答: Call ExecuteCommand like DTE.ExecuteCommand("Debug.Start");

Title: Start solution build from VSIX command


问:
What stages would be involved in compiling Assembly language to Machine Code
I'm trying to write a compiler to take an assembler file which will output raw machine code instructions.

I've found lots of tutorials on how to write a compiler, but I'm wondering if all the stages are relevant to assembler mnemonics. For instance, is lexical analysis necessary at all given the simplified stage-by-stage format of assembler, or will it still be necessary but in a simpler format?

答:
At first I would check if there aren't invalid instructions/operands, then if all variables used are declared. Once you are sure that the file is a valid program delete the comments and replace variables and procedures with addresses (you have to assign addresses to labels "on the fly" during the translation because you can't know the address right now.). Last do the actual conversion in binary code.  </p>

<p>If you assume that every instruction has its own line it will be much easier: if the current line is a label then replace all further references to that with current address, else delete all spaces, leaving one between the two "words" (instruction and operands). Now process the instruction is a joke. ;) </p>

Body:
At first I would check if there aren't invalid instructions/operands, then if all variables used are declared. Once you are sure that the file is a valid program delete the comments and replace variables and procedures with addresses (you have to assign addresses to labels "on the fly" during the translation because you can't know the address right now.). Last do the actual conversion in binary code.

If you assume that every instruction has its own line it will be much easier: if the current line is a label then replace all further references to that with current address, else delete all spaces, leaving one between the two "words" (instruction and operands). Now process the instruction is a joke. ;)


问:
Custom view RatingBar has setOnTouchListener called on it but does not override performClick
I have used RatingBar in my layout as 1 star like below -

```<code><RatingBar
            android:id="@+id/ratingBar"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_below="@id/textViewReleaseDate"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_toRightOf="@id/imageViewPoster"
            android:numStars="1"
            android:stepSize="1.0" />
</code>```

And have setOnTouchListener in my activity like below -

```<code>ratingBar.setOnTouchListener(new View.OnTouchListener() {

        int ratingAtActionDown;

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN)
                ratingAtActionDown = (int) ratingBar.getRating();
            else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                ratingBar.setRating(ratingAtActionDown == 0 ? 1 : 0);
            }

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

For above snippet I am getting this warning -

Custom view 'RatingBar' has setOnTouchListener called on it but does not override performClick

On Android Studio 2.3.3 ratingBar.setOnTouchListener wasn't generating warning but after uprading to Android Studio 3.0 stable it started warning.

What should be done to get rid of the warning?

答:
Lint seems to wrongly think that any view not implementing the performClick() method is a custom view. Knowing this, we can guess that the views affected by this warning are, in fact, missing that implementation.

Now to answer your question, you may need to extend the View you want to set a onTouchListener if you want the warning to disappear:

```<code>class TouchableRatingBar extends android.support.v7.widget.AppCompatRatingBar{

    public TouchableRatingBar(Context context) {
        super(context);
    }
    @Override
    public boolean performClick() {
        return true;
    }
}
</code>```

Override the performClick() method and you should be good to go.

Note that i used the AppCompatRatingBar as Lint seems to dislike doing otherwise.

You also may need to either double cast the Rating Bar or change it's type in the layout.

Double Cast:

```<code>TouchableRatingBar ratingBar = (TouchableRatingBar)(RatingBar)findViewById(R.id.ratingBar);
</code>```

I wouldn't use the double cast personally, but if you need to have an alternative to simply changing the type in the layout it might do the job.

Type Change:

```<code><yourcompany.yourproject.TouchableRatingBar
            android:id="@+id/ratingBar"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_below="@id/textViewReleaseDate"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_toRightOf="@id/imageViewPoster"
            android:numStars="1"
            android:stepSize="1.0" />
</code>```

Body:
I have used RatingBar in my layout as 1 star like below -

<RatingBar
            android:id="@+id/ratingBar"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_below="@id/textViewReleaseDate"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_toRightOf="@id/imageViewPoster"
            android:numStars="1"
            android:stepSize="1.0" />

And have setOnTouchListener in my activity like below -

ratingBar.setOnTouchListener(new View.OnTouchListener() {

        int ratingAtActionDown;

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN)
                ratingAtActionDown = (int) ratingBar.getRating();
            else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                ratingBar.setRating(ratingAtActionDown == 0 ? 1 : 0);
            }

            return true;
        }
    });

For above snippet I am getting this warning -

Custom view 'RatingBar' has setOnTouchListener called on it but does not override performClick

On Android Studio 2.3.3 ratingBar.setOnTouchListener wasn't generating warning but after uprading to Android Studio 3.0 stable it started warning.

What should be done to get rid of the warning?

Body:
Lint seems to wrongly think that any view not implementing the performClick() method is a custom view. Knowing this, we can guess that the views affected by this warning are, in fact, missing that implementation.

Now to answer your question, you may need to extend the View you want to set a onTouchListener if you want the warning to disappear:

class TouchableRatingBar extends android.support.v7.widget.AppCompatRatingBar{

    public TouchableRatingBar(Context context) {
        super(context);
    }
    @Override
    public boolean performClick() {
        return true;
    }
}

Override the performClick() method and you should be good to go.

Note that i used the AppCompatRatingBar as Lint seems to dislike doing otherwise.

You also may need to either double cast the Rating Bar or change it's type in the layout.

Double Cast:

TouchableRatingBar ratingBar = (TouchableRatingBar)(RatingBar)findViewById(R.id.ratingBar);

I wouldn't use the double cast personally, but if you need to have an alternative to simply changing the type in the layout it might do the job.

Type Change:

<yourcompany.yourproject.TouchableRatingBar
            android:id="@+id/ratingBar"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_below="@id/textViewReleaseDate"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_toRightOf="@id/imageViewPoster"
            android:numStars="1"
            android:stepSize="1.0" />


问:
Making form elements on the same line
I am currently make an app and I am trying to make 3 form element align (25/25/50) whoever, it seems like it has not been going smoothly. I will attach a picture at the end to show how it is looking right now. Also, if possible, is there anyway I can make the 3 form element have a space between them so that it is easier to be read and interpreted?

```<code>Between
<div class="ui-grid-e">
  <div class=ui-block-a><input type="text" name="between1" id="between1" required /></div>
  <div class=ui-block-b><input type="text" name="between2" id="between2" required /></div>
  Comment
  <div class=ui-block-c><input type="text" name="betweencomment" id="betweencomment" required /></div>
</div>
</code>```

https://imgur.com/a/vlpbi/

答:
just update your markup

.ui-grid-e {
position: relative;
width: 400px;
}

.ui-block-a,
.ui-block-b,
.ui-block-c {
box-sizing: border-box;
padding: 0 5px;
}

.ui-block-a{
padding-left: 0;
}

.title-c {
padding-left: 5px;
}

.ui-block-title{
box-sizing: border-box;
float: left;
width: 50%;
}

.ui-block-a,
.ui-block-b {
float: left;
width: 25%;
}

.ui-block-c{
float: left;
width: 50%;
}

input {
width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ui-grid-e">
                     <div class="ui-block-title title-a-b">Between</div>
                     <div class="ui-block-title title-c">Comment</div>
                        <div class=ui-block-a><input type="text" name="between1" id="between1" required /></div>
                        <div class=ui-block-b><input type="text" name="between2" id="between2" required /></div>

                        <div class=ui-block-c><input type="text" name="betweencomment" id="betweencomment" required /></div>
                    </div></code>```

Title: Making form elements on the same line

Body:
I am currently make an app and I am trying to make 3 form element align (25/25/50) whoever, it seems like it has not been going smoothly. I will attach a picture at the end to show how it is looking right now. Also, if possible, is there anyway I can make the 3 form element have a space between them so that it is easier to be read and interpreted?

Between

<input type="text" name="between1" id="between1" required />

<input type="text" name="between2" id="between2" required />

  Comment

<input type="text" name="betweencomment" id="betweencomment" required />

https://imgur.com/a/vlpbi/

Body:
just update your markup

.ui-grid-e {
position: relative;
width: 400px;
}

.ui-block-a,
.ui-block-b,
.ui-block-c {
box-sizing: border-box;
padding: 0 5px;
}

.ui-block-a{
padding-left: 0;
}

.title-c {
padding-left: 5px;
}

.ui-block-title{
box-sizing: border-box;
float: left;
width: 50%;
}

.ui-block-a,
.ui-block-b {
float: left;
width: 25%;
}

.ui-block-c{
float: left;
width: 50%;
}

input {
width: 100%;
}

<div class="ui-grid-e">
                     <div class="ui-block-title title-a-b">Between</div>
                     <div class="ui-block-title title-c">Comment</div>
                        <div class=ui-block-a><input type="text" name="between1" id="between1" required /></div>
                        <div class=ui-block-b><input type="text" name="between2" id="between2" required /></div>

                        <div class=ui-block-c><input type="text" name="betweencomment" id="betweencomment" required /></div>
                    </div>


问:
Call a concrete method on an concrete object which current type is an abstract object
I have the following abstract class which ensures that all subclasses contain the method eval().

```<code>public abstract class ExpressionTreeNode {
        abstract double eval();
}
</code>```

I would like to create several concrete classes which inherit from ExpressionTreeNode, like the class Addition. Theses concrete classes contain two other concrete classes (right and left), which inherit from ExpressionTreeNode. Since there might be different concrete classes I defined the variable type as ExpressionTreeNode.

Furthermore I would like to call the eval() method from these concrete classes. But Eclipse says at this point (e.g. double arg1 = right.eval();):

The method eval() is undefined for the type ExpressionTreeNode

Why is it undefined? There can't be a object which is only of the type ExpressionTreeNode and therefore it will contain the eval() method.

```<code>public class Addition extends ExpressionTreeNode {

    ExpressionTreeNode left;
    ExpressionTreeNode right;

    public double eval() {
        double arg1 = left.eval();
        double arg2 = right.eval();

        return arg1+arg2;
    }
}
</code>```

How can I solve this problem (without using an interface instead of the abstract class)?

答:
As @daniu notes in the comments, this is likely due to not making your method public.

Here's a working example that shows your basic architecture is valid:

```<code>public class TreeClasses {
    public static abstract class ExpressionTreeNode {
        public abstract double eval();
    }

    public static class Addition extends ExpressionTreeNode {

        ExpressionTreeNode left;
        ExpressionTreeNode right;

        public Addition(ExpressionTreeNode left, ExpressionTreeNode right) {
            this.left = left;
            this.right = right;
        }

        public double eval() {
            double arg1 = left.eval();
            double arg2 = right.eval();

            return arg1+arg2;
        }
    }

    public static class Constant extends ExpressionTreeNode {
        double val;

        public Constant(double val) {
            this.val = val;
        }

        @Override
        public double eval() {
            return val;
        }

    }

    public static void main(String[] args) {
        ExpressionTreeNode tree = new Addition(new Constant(1),new Constant(2));
        System.out.println(tree.eval());
    }
}
</code>```

Body:
I have the following abstract class which ensures that all subclasses contain the method eval().

public abstract class ExpressionTreeNode {
        abstract double eval();
}

I would like to create several concrete classes which inherit from ExpressionTreeNode, like the class Addition. Theses concrete classes contain two other concrete classes (right and left), which inherit from ExpressionTreeNode. Since there might be different concrete classes I defined the variable type as ExpressionTreeNode.

Furthermore I would like to call the eval() method from these concrete classes. But Eclipse says at this point (e.g. double arg1 = right.eval();):

The method eval() is undefined for the type ExpressionTreeNode

Why is it undefined? There can't be a object which is only of the type ExpressionTreeNode and therefore it will contain the eval() method.

public class Addition extends ExpressionTreeNode {

    ExpressionTreeNode left;
    ExpressionTreeNode right;

    public double eval() {
        double arg1 = left.eval();
        double arg2 = right.eval();

        return arg1+arg2;
    }
}

How can I solve this problem (without using an interface instead of the abstract class)?

Body:
As @daniu notes in the comments, this is likely due to not making your method public.

Here's a working example that shows your basic architecture is valid:

public class TreeClasses {
    public static abstract class ExpressionTreeNode {
        public abstract double eval();
    }

    public static class Addition extends ExpressionTreeNode {

        ExpressionTreeNode left;
        ExpressionTreeNode right;

        public Addition(ExpressionTreeNode left, ExpressionTreeNode right) {
            this.left = left;
            this.right = right;
        }

        public double eval() {
            double arg1 = left.eval();
            double arg2 = right.eval();

            return arg1+arg2;
        }
    }

    public static class Constant extends ExpressionTreeNode {
        double val;

        public Constant(double val) {
            this.val = val;
        }

        @Override
        public double eval() {
            return val;
        }

    }

    public static void main(String[] args) {
        ExpressionTreeNode tree = new Addition(new Constant(1),new Constant(2));
        System.out.println(tree.eval());
    }
}


问:
Boost array Initialization in C++
I need to declare a boost::array. I did it as boost::array<char, 116> buf;
is there a possibility that I can declare with the size stored as a constant that is initialized from property file. something like boost::array<char, BUFFER_SIZE> buf;

Any Help?

答:
No. If you want a dynamically sizable array, use a std::vector

Reason for No is that the template parameter cannot be provided at run time (caveat: current standard)

Title: Boost array Initialization in C++


问:
Release APK crash on start - React Native
I have an issue with react native release APK.

The app run on debug mode but it crash immediately on release mode

Got these message from the logcat which is probably causing this problem

```<code>Module AppRegistry is not a registered callable module (calling unmountApplicationComponentAtRootTag)
11-01 08:28:24.531  6644  6662 E ReactNativeJS: undefined is not an object (evaluating 'd.View.propTypes.style')
11-01 08:28:24.534  6644  6662 E ReactNativeJS: Module AppRegistry is not a registered callable module (calling runApplication)
</code>```

Here is my packages :

```<code>  {
  "name": "jbw",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "color": "^2.0.0",
    "intl": "^1.2.5",
    "native-base": "^2.3.3",
    "prop-types": "^15.6.0",
    "react": "16.0.0-beta.5",
    "react-native": "0.49.3",
    "react-native-fontawesome": "^5.7.0",
    "react-native-keyboard-aware-scroll-view": "^0.4.1",
    "react-native-linear-gradient": "^2.3.0",
    "react-native-loading-spinner-overlay": "^0.5.2",
    "react-native-masked-text": "^1.6.2",
    "react-native-modal": "^4.1.1",
    "react-native-popup-dialog": "^0.9.38",
    "react-native-super-grid": "^1.0.4",
    "react-native-vector-icons": "^4.4.2",
    "react-navigation": "^1.0.0-beta.15"
  },
  "devDependencies": {
    "babel-jest": "21.2.0",
    "babel-preset-react-native": "4.0.0",
    "jest": "21.2.1",
    "react-test-renderer": "16.0.0-beta.5"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

答:
just make sure that you have:

```<code>"react-native": "0.50.3",
"react": "^16.0.0"
</code>```

then do:

```<code>watchman watch-del-all
cd android
./gradlew clean
./gradlew assembleDebug
</code>```

and everything will work well

credit to: @mobdim  https://github.com/facebook/react-native/issues/16745#issuecomment-343443988

i should mention that i had to fix also the problem mentioned here by Ganesh Cauda

Body:
I have an issue with react native release APK.

The app run on debug mode but it crash immediately on release mode

Got these message from the logcat which is probably causing this problem

Module AppRegistry is not a registered callable module (calling unmountApplicationComponentAtRootTag)
11-01 08:28:24.531  6644  6662 E ReactNativeJS: undefined is not an object (evaluating 'd.View.propTypes.style')
11-01 08:28:24.534  6644  6662 E ReactNativeJS: Module AppRegistry is not a registered callable module (calling runApplication)

Here is my packages :

  {
  "name": "jbw",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "color": "^2.0.0",
    "intl": "^1.2.5",
    "native-base": "^2.3.3",
    "prop-types": "^15.6.0",
    "react": "16.0.0-beta.5",
    "react-native": "0.49.3",
    "react-native-fontawesome": "^5.7.0",
    "react-native-keyboard-aware-scroll-view": "^0.4.1",
    "react-native-linear-gradient": "^2.3.0",
    "react-native-loading-spinner-overlay": "^0.5.2",
    "react-native-masked-text": "^1.6.2",
    "react-native-modal": "^4.1.1",
    "react-native-popup-dialog": "^0.9.38",
    "react-native-super-grid": "^1.0.4",
    "react-native-vector-icons": "^4.4.2",
    "react-navigation": "^1.0.0-beta.15"
  },
  "devDependencies": {
    "babel-jest": "21.2.0",
    "babel-preset-react-native": "4.0.0",
    "jest": "21.2.1",
    "react-test-renderer": "16.0.0-beta.5"
  },
  "jest": {
    "preset": "react-native"
  }
}

Body:
just make sure that you have:

"react-native": "0.50.3",
"react": "^16.0.0"

then do:

watchman watch-del-all
cd android
./gradlew clean
./gradlew assembleDebug

and everything will work well

credit to: @mobdim  https://github.com/facebook/react-native/issues/16745#issuecomment-343443988

i should mention that i had to fix also the problem mentioned here by Ganesh Cauda


问:
Apache Solr suggestion suggest only if search term have missing last char
I'm having very strange issue with Broadleaf solr search please see following screen-shot

here is i search with wrong spelled term "mesur" then solr search provide spell correction result but see result all results seems to have last char missing.

now see following second screen-shot

now i have appended "e" to search terms and its "mesure" now then it is not providing any results can any one having good solr experience help me out with this especially why solr have missing last character in suggestion?.

答:
I have resolved my issue by changing schema.xml, i'm having issue with field type, previously it was as follow

```<code><fieldType name="text_general_partial" class="solr.TextField">
        <analyzer type="index">
            <tokenizer class="solr.StandardTokenizerFactory" />

            <!-- Partial Word matcher -->
            <filter class="solr.NGramFilterFactory" minGramSize="3"
                maxGramSize="1000" />
            <filter class="solr.ReverseStringFilterFactory" />

            <filter class="solr.NGramFilterFactory" minGramSize="3"
                maxGramSize="1000" />
            <filter class="solr.ReverseStringFilterFactory" />
            <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>

            <filter class="solr.LowerCaseFilterFactory" />
            <filter class="solr.TrimFilterFactory" />
            <filter class="solr.SnowballPorterFilterFactory" language="English" />
        </analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory" />
            <filter class="solr.WordDelimiterFilterFactory"
                generateWordParts="1" generateNumberParts="1" catenateWords="0"
                catenateNumbers="0" catenateAll="0" splitOnCaseChange="0" />

            <filter class="solr.LowerCaseFilterFactory" />
            <filter class="solr.TrimFilterFactory" />
            <filter class="solr.SnowballPorterFilterFactory" language="English" />
        </analyzer>
    </fieldType>
</code>```

but i have changed to as follows and it's working fine now

```<code><fieldType name="text_general_partial" class="solr.TextField">
        <analyzer type="index">
            <tokenizer class="solr.StandardTokenizerFactory" />

            <!-- Partial Word matcher -->
            <filter class="solr.NGramFilterFactory" minGramSize="3"
                maxGramSize="1000" />
            <filter class="solr.ReverseStringFilterFactory" />

            <filter class="solr.NGramFilterFactory" minGramSize="3"
                maxGramSize="1000" />
            <filter class="solr.ReverseStringFilterFactory" />
            <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
             language="English" />
        </analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory" />
            <filter class="solr.WordDelimiterFilterFactory"
                generateWordParts="1" generateNumberParts="1" catenateWords="0"
                catenateNumbers="0" catenateAll="0" splitOnCaseChange="0" />language="English" />
        </analyzer>
    </fieldType>
</code>```

removed filters as per xml schema and its working fine now

Body:
I have resolved my issue by changing schema.xml, i'm having issue with field type, previously it was as follow

<fieldType name="text_general_partial" class="solr.TextField">
        <analyzer type="index">
            <tokenizer class="solr.StandardTokenizerFactory" />

            <!-- Partial Word matcher -->
            <filter class="solr.NGramFilterFactory" minGramSize="3"
                maxGramSize="1000" />
            <filter class="solr.ReverseStringFilterFactory" />

            <filter class="solr.NGramFilterFactory" minGramSize="3"
                maxGramSize="1000" />
            <filter class="solr.ReverseStringFilterFactory" />
            <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>

            <filter class="solr.LowerCaseFilterFactory" />
            <filter class="solr.TrimFilterFactory" />
            <filter class="solr.SnowballPorterFilterFactory" language="English" />
        </analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory" />
            <filter class="solr.WordDelimiterFilterFactory"
                generateWordParts="1" generateNumberParts="1" catenateWords="0"
                catenateNumbers="0" catenateAll="0" splitOnCaseChange="0" />

            <filter class="solr.LowerCaseFilterFactory" />
            <filter class="solr.TrimFilterFactory" />
            <filter class="solr.SnowballPorterFilterFactory" language="English" />
        </analyzer>
    </fieldType>

but i have changed to as follows and it's working fine now

<fieldType name="text_general_partial" class="solr.TextField">
        <analyzer type="index">
            <tokenizer class="solr.StandardTokenizerFactory" />

            <!-- Partial Word matcher -->
            <filter class="solr.NGramFilterFactory" minGramSize="3"
                maxGramSize="1000" />
            <filter class="solr.ReverseStringFilterFactory" />

            <filter class="solr.NGramFilterFactory" minGramSize="3"
                maxGramSize="1000" />
            <filter class="solr.ReverseStringFilterFactory" />
            <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
             language="English" />
        </analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory" />
            <filter class="solr.WordDelimiterFilterFactory"
                generateWordParts="1" generateNumberParts="1" catenateWords="0"
                catenateNumbers="0" catenateAll="0" splitOnCaseChange="0" />language="English" />
        </analyzer>
    </fieldType>

removed filters as per xml schema and its working fine now


问:
Avoiding comma separator for the last value
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

```<code>Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");
</code>```

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

答: In your loop, simply use insert a "break" when the count reaches the last digit and that has been processed?</p>

Body:
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)


问:
GVim Command / Script to delete lines from a set of 4
This post could count as duplicate , but i have not found any relevant answer in previous threads. I have a large (6 GB) text file and i wish to remove every 3rd and 4th line in a set of 4 lines . For example , the following

```<code>line1
line2
line3
line4
line5
line6
line7
line8
</code>```

needs to be converted to this

```<code>line1
line2
line5
line6
</code>```

Is there any vim script / command to remove those lines ? It could be also in multiple passes . 1 pass to delete the 3rd lines (in a set of 4 (line1,line2,line3,line4)) and another pass to delete again the 3rd lines (previously 4th ones , in a set of 3 (line1,line2,line3)) .

The commands :g/^/+1 d3 is close to what i want but it also removes the second lines .

答:
UPDATE: It is a bad approach for large files, it needs ~3 sec for a 6MB file to perform a substitution.

This approach works in vim. Using regular expression, you find 4 lines and substitute them with first two lines of these 4. Works for a long file as well. Doesn't work for last 1–3 lines if there is a remainder of division of total lines number by 4.

:%s#\(^.*\n^.*\)\n^.*\n^.*\n#\1\r#g

Explanation:

:%s — substitute in the whole file, # used as a delimiter

\(^.*\n^.*\) — \(\) select two lines that will be used later as \1; \n stands for linebreak; ^ for the beginning of the line; .* for any symbol repeated as much times as possible before the linebreak

\n —  linebreak after the second line

^.*\n^.*\n — next two lines to be deleted

\1\r — substitute for lines with first two lines and add a linebreak \r

g — apply to the whole file

Body:
This post could count as duplicate , but i have not found any relevant answer in previous threads. I have a large (6 GB) text file and i wish to remove every 3rd and 4th line in a set of 4 lines . For example , the following

line1
line2
line3
line4
line5
line6
line7
line8

needs to be converted to this

line1
line2
line5
line6

Is there any vim script / command to remove those lines ? It could be also in multiple passes . 1 pass to delete the 3rd lines (in a set of 4 (line1,line2,line3,line4)) and another pass to delete again the 3rd lines (previously 4th ones , in a set of 3 (line1,line2,line3)) .

The commands :g/^/+1 d3 is close to what i want but it also removes the second lines .