问:
Menu being cropped
I have a MFC project. It supports over 40 languages.

On my PC I have two monitors. They are both different size monitors and different resolutions.

If I move my application onto the smaller monitor the complete language menu does not display. I understood it would show scroll bars. Why isn't it?

My menu is a standard menu. Nothing fancy.

My main monitor has higher resolution and I can see full menu.

Please advise.

Thanks.

答:
There are different ways to set DPI awareness. It depends how you have set this value.

Click "Project Properties" -> "Manifest Tools" -> "DPI Awareness"

It might say "High DPI Aware" in your case, that could explain the problem. Change it to "Per Monitor High DPI Aware"

Or you can set this value in manifest file, in dpiAware section, in this manifest file the value should be "True/PM" instead of "True". The manifest file will be names "myapp.exe.manifest" it should be in resource directory.

```<code><dpiAware>True/PM</dpiAware>
</code>```

In your case the value might be "True", that could explain the problem.

Or you might be using SetProcessDpiAwareness. In that case it should use the value PROCESS_PER_MONITOR_DPI_AWARE.

It's also possible that you are using SetProcessDPIAware! This function is deprecated.

See also

Creating a DPI-Aware Application

High DPI Reference

Title: Menu being cropped

Body:
There are different ways to set DPI awareness. It depends how you have set this value.

Click "Project Properties" -> "Manifest Tools" -> "DPI Awareness"

It might say "High DPI Aware" in your case, that could explain the problem. Change it to "Per Monitor High DPI Aware"

Or you can set this value in manifest file, in dpiAware section, in this manifest file the value should be "True/PM" instead of "True". The manifest file will be names "myapp.exe.manifest" it should be in resource directory.

<dpiAware>True/PM</dpiAware>

In your case the value might be "True", that could explain the problem.

Or you might be using SetProcessDpiAwareness. In that case it should use the value PROCESS_PER_MONITOR_DPI_AWARE.

It's also possible that you are using SetProcessDPIAware! This function is deprecated.

See also

Creating a DPI-Aware Application

High DPI Reference


来源: stackexchange

问:
How to add category option to shortcode
I'm new to creating wordpress shortcodes and have one just about working the way I want. Missing something specific. Currently I am able to put the following on any page - [children] and it pulls a query of all posts from the custom post type "children" I would like to add the option to add the category id within the shortcode - something like [children category="8"] Here is the code I have so far:

```<code>add_shortcode( 'children', 'display_custom_post_type' );

function display_custom_post_type(){
    $args = array(
'post_type' => 'children',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
    );
    $string = '';
    $query = new WP_Query( $args );
    if( $query->have_posts() ){
        while( $query->have_posts() ){
            $query->the_post();
            $string .= '<div id="childWrapper"><div id="childImage"><a href="' . get_permalink() . '">' . get_the_post_thumbnail() . '</a></div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
        }
    }
    wp_reset_postdata();
    return $string;
}
</code>```

Secondary - is it possible for it to show posts in multiple categories, but only where the posts are in each of the categories. For example showing a list of children, who fall under a category for critical care and surgery needed.

Any help would be greatly appreciated.

答:
You should refer Shortcode function from WordPress Codex. Assuming your taxonomy name is category, I made some changes in your current code it should work as per your requirements.

```<code>/**
 *  [children category="5,7,8"]
 */
add_shortcode( 'children' , 'display_custom_post_type' );

function display_custom_post_type($atts) {

    $atts = shortcode_atts( array(
        'category' => ''
    ), $atts );

  //If category is multiple: 8,9,3
  $categories  = explode(',' , $atts['category']);

    $args = array(
            'post_type'     => 'children',
            'post_status'   => 'publish',
            'orderby'       => 'title',
            'order'         => 'ASC',
            'posts_per_page'=> -1,
            'tax_query'     => array( array(
                                'taxonomy'  => 'category',
                                'field'     => 'term_id',
                                'terms'     => $categories
                            ) )
        );

        $string = '';
        $query = new WP_Query( $args );

        if( ! $query->have_posts() ) {
            return false;
        }

        while( $query->have_posts() ){
            $query->the_post();
            $string .= '<div id="childWrapper"><div id="childImage"><a href="' . get_permalink() . '">' . get_the_post_thumbnail() . '</a></div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
        }
        wp_reset_postdata();

        return $string;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to add category option to shortcode

Body:
I'm new to creating wordpress shortcodes and have one just about working the way I want. Missing something specific. Currently I am able to put the following on any page - [children] and it pulls a query of all posts from the custom post type "children" I would like to add the option to add the category id within the shortcode - something like [children category="8"] Here is the code I have so far:

add_shortcode( 'children', 'display_custom_post_type' );

function display_custom_post_type(){
    $args = array(
'post_type' => 'children',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
    );
    $string = '';
    $query = new WP_Query( $args );
    if( $query->have_posts() ){
        while( $query->have_posts() ){
            $query->the_post();
            $string .= '

' . get_the_post_thumbnail() . '

' . get_the_title() . '

';
        }
    }
    wp_reset_postdata();
    return $string;
}

Secondary - is it possible for it to show posts in multiple categories, but only where the posts are in each of the categories. For example showing a list of children, who fall under a category for critical care and surgery needed.

Any help would be greatly appreciated.

Body:
You should refer Shortcode function from WordPress Codex. Assuming your taxonomy name is category, I made some changes in your current code it should work as per your requirements.

/**
 *  [children category="5,7,8"]
 */
add_shortcode( 'children' , 'display_custom_post_type' );

function display_custom_post_type($atts) {

    $atts = shortcode_atts( array(
        'category' => ''
    ), $atts );

  //If category is multiple: 8,9,3
  $categories  = explode(',' , $atts['category']);

    $args = array(
            'post_type'     => 'children',
            'post_status'   => 'publish',
            'orderby'       => 'title',
            'order'         => 'ASC',
            'posts_per_page'=> -1,
            'tax_query'     => array( array(
                                'taxonomy'  => 'category',
                                'field'     => 'term_id',
                                'terms'     => $categories
                            ) )
        );

        $string = '';
        $query = new WP_Query( $args );

        if( ! $query->have_posts() ) {
            return false;
        }

        while( $query->have_posts() ){
            $query->the_post();
            $string .= '<div id="childWrapper"><div id="childImage"><a href="' . get_permalink() . '">' . get_the_post_thumbnail() . '</a></div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
        }
        wp_reset_postdata();

        return $string;
}


问:
While updating database with php i'm experiencing some issue
I'm working on library management system. and in update field. if user didn't pass data the i want to keep my data as it is, instead of changing it into blank

```<code><?php
if( isset($_POST['update']) )
{
    $conn = mysql_connect('localhost', 'root', '');
    if( !$conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    $db_selected = mysql_select_db('library', $conn);
    $Book_ID     = $_POST['Book_ID'];
    $Book_Name   = $_POST['Book_Name'];
    $Author      = $_POST['Author'];
    $Quantity    = $_POST['Quantity'];

    $sql    = "update books set Book_Name='$Book_Name', Author='$Author',
            Quantity='$Quantity' where Book_ID='$Book_ID'";
    mysql_select_db('test_db');
    $retval = mysql_query($sql, $conn);

    if( !$retval )
    {
        die('Could not update data: ' . mysql_error());
    }
    echo "Updated data successfully\n";
    header("refresh:2; url=updatebook.php");
    mysql_close($conn);
}
else
{
    ?>
    <form method = "post" action = "<?php $_PHP_SELF ?>">
        <table width = "400" border =" 0" cellspacing = "1" cellpadding = "2">
            <tr>
                <td width = "100">Book ID</td>
                <td><input name = "Book_ID" type = "number" id = "Book_ID"></td>
            </tr>
            <tr>
                <td width = "100">Book Name</td>
                <td><input name = "Book_Name" type = "text" id = "Book_Name"></td>
            </tr>
            <tr>
                <td width = "100">Author</td>
                <td><input name = "Author" type = "text" id = "Author"></td>
            </tr>
            <tr>
                <td width = "100">Quantity</td>
                <td><input name = "Quantity" type = "text" id = "Quantity"></td>
            </tr>

            <tr>
                <td width = "100"> </td>
                <td> </td>
            </tr>

            <tr>
                <td width = "100"> </td>
                <td>
            <tr>
                <td width = "100"> </td>
                <td> </td>
            </tr>

            <tr>
                <td width = "100"> </td>
                <td>
                    <input name = "update" type = "submit" id = "update" value = "Update">
                </td>
            </tr>
        </table>
    </form>
    <?php
}
?>
</code>```

If user didn't want to change value of some field and keep it blank. i don't want to update that field with blank. I want to keep the data of that field, as it is.

from this code if i enter Book ID and kept Book Name, blank then this code passes the value

答:
You need to fetch the original values first then use IF ELSE to use that old value instead of the new one if the variable is empty. Refer to the code below which i've modified:

`

```<code>    $conn = mysql_connect('localhost', 'root', '');

    if(!$conn ) {
       die('Could not connect: ' . mysql_error());
    }
    $db_selected = mysql_select_db('library', $conn);
    $old_data = mysql_fetch_array(mysql_query("select * from books where Book_ID='".$_POST['Book_ID']."'"));

    $Book_ID = $_POST['Book_ID'];
    $Book_Name = ($_POST['Book_Name'] == '' ? $old_data['Book_Name'] : $_POST['Book_Name']);
    $Author = ($_POST['Author'] == '' ? $old_data['Author'] : $_POST['Author']);
    $Quantity = ($_POST['Quantity'] == '' ? $old_data['Quantity'] : $_POST['Quantity']);

    $sql = "update books set  Book_Name='$Book_Name', Author='$Author',
    Quantity='$Quantity' where Book_ID='$Book_ID'";
    mysql_select_db('test_db');
    $retval = mysql_query( $sql, $conn );

    if(! $retval ) {
       die('Could not update data: ' . mysql_error());
    }
    echo "Updated data successfully\n";
    header("refresh:2; url=updatebook.php");

    mysql_close($conn);
 }else {
    ?>
       <form method = "post" action = "<?php $_PHP_SELF ?>">
          <table width = "400" border =" 0" cellspacing = "1"
             cellpadding = "2">

             <tr>
                <td width = "100">Book ID</td>
                <td><input name = "Book_ID" type = "number"
                   id = "Book_ID"></td>
             </tr>

             <tr>
                <td width = "100">Book Name</td>
                <td><input name = "Book_Name" type = "text"
                   id = "Book_Name"></td>
             </tr>
             <tr>
                <td width = "100">Author</td>
                <td><input name = "Author" type = "text"
                   id = "Author"></td>
             </tr>

             <tr>
                <td width = "100">Quantity</td>
                <td><input name = "Quantity" type = "text"
                   id = "Quantity"></td>
             </tr>

             <tr>
                <td width = "100"> </td>
                <td> </td>
             </tr>

             <tr>
                <td width = "100"> </td>
                <td>
                <tr>
                <td width = "100"> </td>
                <td> </td>
             </tr>

             <tr>
                <td width = "100"> </td>
                <td>
                   <input name = "update" type = "submit"
                      id = "update" value = "Update">
                </td>
             </tr>

          </table>
       </form>

    <?php
 }
</code>```

?>
`

Body:
I'm working on library management system. and in update field. if user didn't pass data the i want to keep my data as it is, instead of changing it into blank

<?php
if( isset($_POST['update']) )
{
    $conn = mysql_connect('localhost', 'root', '');
    if( !$conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    $db_selected = mysql_select_db('library', $conn);
    $Book_ID     = $_POST['Book_ID'];
    $Book_Name   = $_POST['Book_Name'];
    $Author      = $_POST['Author'];
    $Quantity    = $_POST['Quantity'];

    $sql    = "update books set Book_Name='$Book_Name', Author='$Author',
            Quantity='$Quantity' where Book_ID='$Book_ID'";
    mysql_select_db('test_db');
    $retval = mysql_query($sql, $conn);

    if( !$retval )
    {
        die('Could not update data: ' . mysql_error());
    }
    echo "Updated data successfully\n";
    header("refresh:2; url=updatebook.php");
    mysql_close($conn);
}
else
{
    ?>
    <form method = "post" action = "<?php $_PHP_SELF ?>">

                Book ID
                <input name = "Book_ID" type = "number" id = "Book_ID">

                Book Name
                <input name = "Book_Name" type = "text" id = "Book_Name">

                Author
                <input name = "Author" type = "text" id = "Author">

                Quantity
                <input name = "Quantity" type = "text" id = "Quantity">

                    <input name = "update" type = "submit" id = "update" value = "Update">

    </form>
    <?php
}
?>

If user didn't want to change value of some field and keep it blank. i don't want to update that field with blank. I want to keep the data of that field, as it is.

from this code if i enter Book ID and kept Book Name, blank then this code passes the value

Body:
You need to fetch the original values first then use IF ELSE to use that old value instead of the new one if the variable is empty. Refer to the code below which i've modified:

`

    $conn = mysql_connect('localhost', 'root', '');

    if(!$conn ) {
       die('Could not connect: ' . mysql_error());
    }
    $db_selected = mysql_select_db('library', $conn);
    $old_data = mysql_fetch_array(mysql_query("select * from books where Book_ID='".$_POST['Book_ID']."'"));

    $Book_ID = $_POST['Book_ID'];
    $Book_Name = ($_POST['Book_Name'] == '' ? $old_data['Book_Name'] : $_POST['Book_Name']);
    $Author = ($_POST['Author'] == '' ? $old_data['Author'] : $_POST['Author']);
    $Quantity = ($_POST['Quantity'] == '' ? $old_data['Quantity'] : $_POST['Quantity']);

    $sql = "update books set  Book_Name='$Book_Name', Author='$Author',
    Quantity='$Quantity' where Book_ID='$Book_ID'";
    mysql_select_db('test_db');
    $retval = mysql_query( $sql, $conn );

    if(! $retval ) {
       die('Could not update data: ' . mysql_error());
    }
    echo "Updated data successfully\n";
    header("refresh:2; url=updatebook.php");

    mysql_close($conn);
 }else {
    ?>
       <form method = "post" action = "<?php $_PHP_SELF ?>">
          <table width = "400" border =" 0" cellspacing = "1"
             cellpadding = "2">

             <tr>
                <td width = "100">Book ID</td>
                <td><input name = "Book_ID" type = "number"
                   id = "Book_ID"></td>
             </tr>

             <tr>
                <td width = "100">Book Name</td>
                <td><input name = "Book_Name" type = "text"
                   id = "Book_Name"></td>
             </tr>
             <tr>
                <td width = "100">Author</td>
                <td><input name = "Author" type = "text"
                   id = "Author"></td>
             </tr>

             <tr>
                <td width = "100">Quantity</td>
                <td><input name = "Quantity" type = "text"
                   id = "Quantity"></td>
             </tr>

             <tr>
                <td width = "100"> </td>
                <td> </td>
             </tr>

             <tr>
                <td width = "100"> </td>
                <td>
                <tr>
                <td width = "100"> </td>
                <td> </td>
             </tr>

             <tr>
                <td width = "100"> </td>
                <td>
                   <input name = "update" type = "submit"
                      id = "update" value = "Update">
                </td>
             </tr>

          </table>
       </form>

    <?php
 }

?>
`


问:
get error while file upload in laravel
I am trying to upload image in laravel. But when i upload it gives error.

Call to a member function getClientOriginalExtension() on null

Here is my Blade file form

```<code>{{Form::open(array('url' => '/AddNewBlog','id'=>'blogadd' ,
   'method' => 'post','class'=>'form-row','files'=>true,
   "enctype"=>"multipart/form-data"))}}
</code>```

And here is controller

```<code> $imagename_bg = time() . '.' . $photo->getClientOriginalExtension();
 $destinationPath = public_path('/uploads/blog');
 $thumb_img = Image::make($photo->getRealPath())->resize(750, 450);
 $thumb_img->save($destinationPath . '/' . $imagename_bg, 80);
 $photo->move($destinationPath, $imagename_bg);
</code>```

Please help me how to resolve this problem.

答:
I am not able to understand your code. if you are looking for uploading image and resize using intervention package try this:-

```<code>if($request->hasFile('blogimage')){
if (Input::file('blogimage')->isValid()) {
    $file = Input::file('image');
    $img = Image::make($file);
    $img->resize(400,270);
    $name = pathinfo($_FILES['image']['name']);
    $destination = public_path('/uploads/blog');
    $ext = $name['extension'];
    $rand= time().str_random(6).date('h-i-s').'.'.$ext;
    $img->save($destination.$rand);
}
}
</code>```

Or Without intervention pacakge:-

```<code>if($request->hasFile('blogimage')){
if (Input::file('blogimage')->isValid()) {
    $file = Input::file('blogimage');
    $destination = public_path('/uploads/blog');
    $ext= Input::file('blogimage')->getClientOriginalExtension();
    $mainFilename =time().str_random(5).date('h-i-s');
    $file->move($destination, $mainFilename.".".$ext);
}
}
</code>```

Hope it helps!

Title: get error while file upload in laravel

Body:
I am trying to upload image in laravel. But when i upload it gives error.

Call to a member function getClientOriginalExtension() on null

Here is my Blade file form

{{Form::open(array('url' => '/AddNewBlog','id'=>'blogadd' ,
   'method' => 'post','class'=>'form-row','files'=>true,
   "enctype"=>"multipart/form-data"))}}

And here is controller

 $imagename_bg = time() . '.' . $photo->getClientOriginalExtension();
 $destinationPath = public_path('/uploads/blog');
 $thumb_img = Image::make($photo->getRealPath())->resize(750, 450);
 $thumb_img->save($destinationPath . '/' . $imagename_bg, 80);
 $photo->move($destinationPath, $imagename_bg);

Please help me how to resolve this problem.

Body:
I am not able to understand your code. if you are looking for uploading image and resize using intervention package try this:-

if($request->hasFile('blogimage')){
if (Input::file('blogimage')->isValid()) {
    $file = Input::file('image');
    $img = Image::make($file);
    $img->resize(400,270);
    $name = pathinfo($_FILES['image']['name']);
    $destination = public_path('/uploads/blog');
    $ext = $name['extension'];
    $rand= time().str_random(6).date('h-i-s').'.'.$ext;
    $img->save($destination.$rand);
}
}

Or Without intervention pacakge:-

if($request->hasFile('blogimage')){
if (Input::file('blogimage')->isValid()) {
    $file = Input::file('blogimage');
    $destination = public_path('/uploads/blog');
    $ext= Input::file('blogimage')->getClientOriginalExtension();
    $mainFilename =time().str_random(5).date('h-i-s');
    $file->move($destination, $mainFilename.".".$ext);
}
}

Hope it helps!


问:
Extension Modules disappeared
I don't have any error logs or other info that I can figure out what's the issue, is not the first time that it happens. In my case is when I installed an extension, basically I do what is recommended after uploading the extension, clean cache and login again on admin, and everything is ok when I installed, the only problem is that sometimes the module disappeares has nothing was installed, and only shows again if a go and "clean Cache" on the admin panel.</p>

答:
If you use multiple web-nodes, separate admin nodes then it can be possible that the new codes might have not deployed to one of your servers and the old xmls are cached.

And I understand that you are using redis as your caching layer, so sometimes flushing the cache from magento admin panel doesnt flush the entire redis cache.

So you would need to try to connect to the redis server using redis-cli command then issue 'flushall' there.

Title: Extension Modules disappeared


问:
How to clear datagridview using timer?
I want to update datagridview every 10 seconds. So far after update, new rows are added and I want to clean the datagridview before update.

The problem is that, when I call inside of OnCallBack() dataGridView2.Rows.Clear(); and dataGridView2.Refresh();, I get an exception:

Cross-thread operation not valid

I have tried to Invoke it, but it doesn't help.

```<code> if(dataGridView2.InvokeRequired){
        dataGridView2.Invoke(new MethodInvoker(delegate{
        dataGridView2.Rows.Clear();
        dataGridView2.Refresh();
 }));
</code>```

My code:

```<code>    private void Live(){
        timer = new System.Threading.Timer (_ => OnCallBack(), null, 1000,Timeout.Infinite);
    }

    private void OnCallBack()
    {
        timer.Dispose();
        counter--;

        label8.Text = counter.ToString();
        if (counter == 0){
                string[] pr = {"124"};
                search.SearchLive(pr, dataGridView2, label10);
                counter = 10;
        }
        timer = new System.Threading.Timer (_ => OnCallBack(), null, 1000,Timeout.Infinite);
     }
</code>```

答:
You can use System.Timers class to create a new timer along with its interval

```<code> System.Timers.Timer timer1 = new System.Timers.Timer();
 timer1.Interval = 1000; //time after which you want to clear datagrid
 timer1.Start();
 timer1.Elapsed += TimerTick;
</code>```

Then create an event handler for TimerTick

```<code>private void TimerTick(object sender, ElapsedEventArgs e)
{
   if (dataGridView1.rows.count>0)
   {
     dataGridView1.Rows.Clear();
     dataGridView1.Refresh();
   }
}
</code>```

Add this check if you want to prevent further crossthreading exceptions

```<code>CheckForIllegalCrossThreadCalls = false;
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to clear datagridview using timer?

Body:
I want to update datagridview every 10 seconds. So far after update, new rows are added and I want to clean the datagridview before update.

The problem is that, when I call inside of OnCallBack() dataGridView2.Rows.Clear(); and dataGridView2.Refresh();, I get an exception:

Cross-thread operation not valid

I have tried to Invoke it, but it doesn't help.

 if(dataGridView2.InvokeRequired){
        dataGridView2.Invoke(new MethodInvoker(delegate{
        dataGridView2.Rows.Clear();
        dataGridView2.Refresh();
 }));

My code:

    private void Live(){
        timer = new System.Threading.Timer (_ => OnCallBack(), null, 1000,Timeout.Infinite);
    }

    private void OnCallBack()
    {
        timer.Dispose();
        counter--;

        label8.Text = counter.ToString();
        if (counter == 0){
                string[] pr = {"124"};
                search.SearchLive(pr, dataGridView2, label10);
                counter = 10;
        }
        timer = new System.Threading.Timer (_ => OnCallBack(), null, 1000,Timeout.Infinite);
     }

Body:
You can use System.Timers class to create a new timer along with its interval

 System.Timers.Timer timer1 = new System.Timers.Timer();
 timer1.Interval = 1000; //time after which you want to clear datagrid
 timer1.Start();
 timer1.Elapsed += TimerTick;

Then create an event handler for TimerTick

private void TimerTick(object sender, ElapsedEventArgs e)
{
   if (dataGridView1.rows.count>0)
   {
     dataGridView1.Rows.Clear();
     dataGridView1.Refresh();
   }
}

Add this check if you want to prevent further crossthreading exceptions

CheckForIllegalCrossThreadCalls = false;


问:
Apache MyFaces Trinidad 1.2 throws NullPointerException with Tomcat 8.5
I created a JSF 1.2 project in eclipse and deployed on Tomcat 8.5 but it throws NullPointerException when I open the jsp page in a browser.

The application works fine in Tomcat 6.
I am using JSF 1.2 and Apache MyFaces Trinidad 1.2

The following is jsp page

```<code>        <?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:trh="http://myfaces.apache.org/trinidad/html"
    xmlns:tr="http://myfaces.apache.org/trinidad"
     version="1.2">
    <jsp:directive.page language="java"
        contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />
    <jsp:text>
        <![CDATA[ <?xml version="1.0" encoding="UTF-8" ?> ]]>
    </jsp:text>
    <jsp:text>
        <![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ]]>
    </jsp:text>
    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
</head>
<body>
    <f:view>
    <tr:outputText value="test jsf"></tr:outputText>
    </f:view>
</body>
    </html>
</jsp:root>
</code>```

The following is the exception in console of eclipse

```<code>SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.NullPointerException
    at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:113)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.setProperty(UIXComponentELTag.java:135)
    at org.apache.myfaces.trinidadinternal.taglib.UIXValueTag.setProperties(UIXValueTag.java:77)
    at org.apache.myfaces.trinidadinternal.taglib.core.output.CoreOutputTextTag.setProperties(CoreOutputTextTag.java:158)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.setProperties(UIXComponentELTag.java:122)
    at javax.faces.webapp.UIComponentELTag.createComponent(UIComponentELTag.java:230)
    at javax.faces.webapp.UIComponentClassicTagBase.createChild(UIComponentClassicTagBase.java:486)
    at javax.faces.webapp.UIComponentClassicTagBase.findComponent(UIComponentClassicTagBase.java:670)
    at javax.faces.webapp.UIComponentClassicTagBase.doStartTag(UIComponentClassicTagBase.java:1142)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.doStartTag(UIXComponentELTag.java:71)
    at org.apache.jsp.NewFile1_jsp._jspx_meth_tr_005foutputText_005f0(NewFile1_jsp.java:211)
    at org.apache.jsp.NewFile1_jsp._jspx_meth_f_005fview_005f0(NewFile1_jsp.java:179)
    at org.apache.jsp.NewFile1_jsp._jspService(NewFile1_jsp.java:139)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:467)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:392)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311)
    at com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:410)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidadinternal.context.FacesContextFactoryImpl$OverrideDispatch.dispatch(FacesContextFactoryImpl.java:267)
    at com.sun.faces.application.ViewHandlerImpl.executePageToBuildView(ViewHandlerImpl.java:473)
    at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:141)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:189)
    at org.apache.myfaces.trinidadinternal.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:193)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:109)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:266)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Nov 28, 2017 4:48:59 AM com.sun.faces.lifecycle.Phase doPhase
SEVERE: JSF1054: (Phase ID: RENDER_RESPONSE 6, View ID: /NewFile1.jsp) Exception thrown during phase execution: javax.faces.event.PhaseEvent[source=com.sun.faces.lifecycle.LifecycleImpl@19c4105c]
Nov 28, 2017 4:48:59 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/testJSF] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:113)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.setProperty(UIXComponentELTag.java:135)
    at org.apache.myfaces.trinidadinternal.taglib.UIXValueTag.setProperties(UIXValueTag.java:77)
    at org.apache.myfaces.trinidadinternal.taglib.core.output.CoreOutputTextTag.setProperties(CoreOutputTextTag.java:158)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.setProperties(UIXComponentELTag.java:122)
    at javax.faces.webapp.UIComponentELTag.createComponent(UIComponentELTag.java:230)
    at javax.faces.webapp.UIComponentClassicTagBase.createChild(UIComponentClassicTagBase.java:486)
    at javax.faces.webapp.UIComponentClassicTagBase.findComponent(UIComponentClassicTagBase.java:670)
    at javax.faces.webapp.UIComponentClassicTagBase.doStartTag(UIComponentClassicTagBase.java:1142)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.doStartTag(UIXComponentELTag.java:71)
    at org.apache.jsp.NewFile1_jsp._jspx_meth_tr_005foutputText_005f0(NewFile1_jsp.java:211)
    at org.apache.jsp.NewFile1_jsp._jspx_meth_f_005fview_005f0(NewFile1_jsp.java:179)
    at org.apache.jsp.NewFile1_jsp._jspService(NewFile1_jsp.java:139)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:467)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:392)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311)
    at com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:410)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidadinternal.context.FacesContextFactoryImpl$OverrideDispatch.dispatch(FacesContextFactoryImpl.java:267)
    at com.sun.faces.application.ViewHandlerImpl.executePageToBuildView(ViewHandlerImpl.java:473)
    at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:141)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:189)
    at org.apache.myfaces.trinidadinternal.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:193)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:109)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:266)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

How to fix this for Apache MyFaces Trinidad 1.2?

答:
I had the same problem at about 2 years ago. The productive Webserver has been changed from Tomcat7 to Tomcat8 and Trinidad was no longer working.
I moved the whole Project to jsf 2.2 and trinidad 2.1.1, of which a user solved the Tomcat 8 Problem. It is two years ago, but as far as I know the trinidad community is dead somehow...</p>

Body:
I created a JSF 1.2 project in eclipse and deployed on Tomcat 8.5 but it throws NullPointerException when I open the jsp page in a browser.

The application works fine in Tomcat 6.
I am using JSF 1.2 and Apache MyFaces Trinidad 1.2

The following is jsp page

        <?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:trh="http://myfaces.apache.org/trinidad/html"
    xmlns:tr="http://myfaces.apache.org/trinidad"
     version="1.2">
    <jsp:directive.page language="java"
        contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />
    <jsp:text>
        <![CDATA[ <?xml version="1.0" encoding="UTF-8" ?> ]]>
    </jsp:text>
    <jsp:text>
        <![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ]]>
    </jsp:text>

<title>Test</title>

    <f:view>

    </f:view>

</jsp:root>

The following is the exception in console of eclipse

SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.NullPointerException
    at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:113)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.setProperty(UIXComponentELTag.java:135)
    at org.apache.myfaces.trinidadinternal.taglib.UIXValueTag.setProperties(UIXValueTag.java:77)
    at org.apache.myfaces.trinidadinternal.taglib.core.output.CoreOutputTextTag.setProperties(CoreOutputTextTag.java:158)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.setProperties(UIXComponentELTag.java:122)
    at javax.faces.webapp.UIComponentELTag.createComponent(UIComponentELTag.java:230)
    at javax.faces.webapp.UIComponentClassicTagBase.createChild(UIComponentClassicTagBase.java:486)
    at javax.faces.webapp.UIComponentClassicTagBase.findComponent(UIComponentClassicTagBase.java:670)
    at javax.faces.webapp.UIComponentClassicTagBase.doStartTag(UIComponentClassicTagBase.java:1142)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.doStartTag(UIXComponentELTag.java:71)
    at org.apache.jsp.NewFile1_jsp._jspx_meth_tr_005foutputText_005f0(NewFile1_jsp.java:211)
    at org.apache.jsp.NewFile1_jsp._jspx_meth_f_005fview_005f0(NewFile1_jsp.java:179)
    at org.apache.jsp.NewFile1_jsp._jspService(NewFile1_jsp.java:139)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:467)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:392)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311)
    at com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:410)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidadinternal.context.FacesContextFactoryImpl$OverrideDispatch.dispatch(FacesContextFactoryImpl.java:267)
    at com.sun.faces.application.ViewHandlerImpl.executePageToBuildView(ViewHandlerImpl.java:473)
    at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:141)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:189)
    at org.apache.myfaces.trinidadinternal.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:193)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:109)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:266)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Nov 28, 2017 4:48:59 AM com.sun.faces.lifecycle.Phase doPhase
SEVERE: JSF1054: (Phase ID: RENDER_RESPONSE 6, View ID: /NewFile1.jsp) Exception thrown during phase execution: javax.faces.event.PhaseEvent[source=com.sun.faces.lifecycle.LifecycleImpl@19c4105c]
Nov 28, 2017 4:48:59 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/testJSF] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:113)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.setProperty(UIXComponentELTag.java:135)
    at org.apache.myfaces.trinidadinternal.taglib.UIXValueTag.setProperties(UIXValueTag.java:77)
    at org.apache.myfaces.trinidadinternal.taglib.core.output.CoreOutputTextTag.setProperties(CoreOutputTextTag.java:158)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.setProperties(UIXComponentELTag.java:122)
    at javax.faces.webapp.UIComponentELTag.createComponent(UIComponentELTag.java:230)
    at javax.faces.webapp.UIComponentClassicTagBase.createChild(UIComponentClassicTagBase.java:486)
    at javax.faces.webapp.UIComponentClassicTagBase.findComponent(UIComponentClassicTagBase.java:670)
    at javax.faces.webapp.UIComponentClassicTagBase.doStartTag(UIComponentClassicTagBase.java:1142)
    at org.apache.myfaces.trinidad.webapp.UIXComponentELTag.doStartTag(UIXComponentELTag.java:71)
    at org.apache.jsp.NewFile1_jsp._jspx_meth_tr_005foutputText_005f0(NewFile1_jsp.java:211)
    at org.apache.jsp.NewFile1_jsp._jspx_meth_f_005fview_005f0(NewFile1_jsp.java:179)
    at org.apache.jsp.NewFile1_jsp._jspService(NewFile1_jsp.java:139)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:467)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:392)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311)
    at com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:410)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidad.context.ExternalContextDecorator.dispatch(ExternalContextDecorator.java:44)
    at org.apache.myfaces.trinidadinternal.context.FacesContextFactoryImpl$OverrideDispatch.dispatch(FacesContextFactoryImpl.java:267)
    at com.sun.faces.application.ViewHandlerImpl.executePageToBuildView(ViewHandlerImpl.java:473)
    at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:141)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:189)
    at org.apache.myfaces.trinidadinternal.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:193)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:109)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:266)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

How to fix this for Apache MyFaces Trinidad 1.2?


问:
Append a New Line onto each concatenated row from SQL Server
The following sql query correctly concatenates each row of the table for a given foreign key PlanId. However, The CHAR(10) + CHAR(13) appear to be ignored.

```<code>SELECT PlanID,
   STUFF(
            (
                SELECT CONVERT(NVARCHAR, CONVERT(DATE, CreateTimestamp)) + ' ' + CreateUserID + ': ' + Notes
                       + CHAR(13) + CHAR(10)
                FROM PlanNotes
                WHERE PlanID = OuterNotes.PlanId
                ORDER BY UpdateTimestamp DESC
                FOR XML PATH(''), TYPE
            ).value('.', 'nvarchar(max)'),
            1,
            0,
            ''
        ) AS Notes
FROM PlanNotes OuterNotes;
</code>```

The resulting output looks like:

2017-12-04 nickh: Nick's Test Notes v2  2017-11-27 bobj: Original date was 6/1/2016.

When I want:

2017-12-04 nickh: Nick's Test Notes v2

  2017-11-27 bobj: Original date was

答: My guess is that the CHAR(10) and CHAR(13) characters did in fact make it into your output, but that for whatever reason SSMS or your particular tool is not rendering them as you would expect.  A workaround here might be to output your query to a text file and then open in a bona-fide text editor (e.g. Notepad++).

Body:
The following sql query correctly concatenates each row of the table for a given foreign key PlanId. However, The CHAR(10) + CHAR(13) appear to be ignored.

SELECT PlanID,
   STUFF(
            (
                SELECT CONVERT(NVARCHAR, CONVERT(DATE, CreateTimestamp)) + ' ' + CreateUserID + ': ' + Notes
                       + CHAR(13) + CHAR(10)
                FROM PlanNotes
                WHERE PlanID = OuterNotes.PlanId
                ORDER BY UpdateTimestamp DESC
                FOR XML PATH(''), TYPE
            ).value('.', 'nvarchar(max)'),
            1,
            0,
            ''
        ) AS Notes
FROM PlanNotes OuterNotes;

The resulting output looks like:

2017-12-04 nickh: Nick's Test Notes v2  2017-11-27 bobj: Original date was 6/1/2016.

When I want:

2017-12-04 nickh: Nick's Test Notes v2

  2017-11-27 bobj: Original date was


问:
What is the difference between (for example) p.post {color: #336;} and .post p {color: #336;}?
I've always used this structure in the style sheet:

```<code>.post {padding: 10px;}
.post h1 {color: #336;}
.post p {font-size: 1em;}
</code>```

with this html:

```<code><div class="post">
<h1>title</h1>
<p>content</p>
</div>
</code>```

However, I frequently see this structure in style sheets:

```<code>h1.post {color:#336;}
p.post {font-size: 1em;}
</code>```

with this html:

```<code><h1 class="post">title</h1>
<p class="post">content</p>
</code>```

I'm working on a theme that I will be giving to others, therefore, it's not enough that it works--I want it to reflect "best practices" (and keep me from appearing to be a total newbie).

My attempts to find an answer haven't been successful--perhaps because the search terms (element, selector, css, etc) are too broad.

Thank you in advance for any assistance.

(Also, an overdue thanks for past assistance.  This is my first question, but not my first visit to the site.)

答:
They specify slightly different things.

p.post matches a p element (and only a p element) that also has a class of post.

.post p matches a p element that is a descendent of another element that has a class of post.

The general term for the operators that combine or refine the elements to form a CSS rule is selectors or combinators. In CSS3 they're defined by this document. p.post is an example of the class selector, while .post p illustrates the descendant combinator.

ContentLicense: CC BY-SA 2.5

Body:
I've always used this structure in the style sheet:

.post {padding: 10px;}
.post h1 {color: #336;}
.post p {font-size: 1em;}

with this html:

title

content

However, I frequently see this structure in style sheets:

h1.post {color:#336;}
p.post {font-size: 1em;}

with this html:

title

content

I'm working on a theme that I will be giving to others, therefore, it's not enough that it works--I want it to reflect "best practices" (and keep me from appearing to be a total newbie).

My attempts to find an answer haven't been successful--perhaps because the search terms (element, selector, css, etc) are too broad.

Thank you in advance for any assistance.

(Also, an overdue thanks for past assistance.  This is my first question, but not my first visit to the site.)


问:
How to get the select value into the controller
I'm trying to create a simple calculator using Angularjs,in my code I can't get the operator value.How can I fix that?

Home html contains get the two numbers and the operator.User have to select the operator..

my Code -

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    //$scope.cdata={};

    console.log("calcCtrl works!");
    var opp;
    ans = 0;
    opp = $scope.singleSelect;

    console.log("opp ==> "+opp);

    $scope.calculateNums = function(nu1, nu2) {
        console.log("function works!");
        console.log("nu1 ==> "+nu1);
        console.log("opp in calculateNums ==> "+opp);
        if (opp == "+") {
            ans = (parseInt(nu1) + parseInt(nu2));
            console.log("ans ==> "+ans);
        } else if (opp == "-") {
            ans = (parseInt(nu1) - parseInt(nu2));
        }
        console.log("ans ==> "+ans);
        return ans;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<h3>Hello</h3>
<div ng-controller='calcCtrl' >
Number 1::<input Type="text" name="number1" ng-model="n1"/ required> <br/>
Number 2::<input Type="text" name="number2" ng-model="n2"/ required> <br/>
operator::<select ng-model="singleSelect">
        <option value="+">+</option>
        <option >*</option>
        <option>-</option>
        <option>/</option>
     </select></p> <br/>

<button ng-click="calculateNums(n1,n2)">Calculate Now</button>
</div>
  </body>
</html></code>```

So, The output I get is -

```<code>calcCtrl works!
opp ==> undefined
function works!
nu1 ==> 1
opp in calculateNums ==> undefined
ans ==> 0
</code>```

the operator values are undefined here..

答:
add the value attr to the other options

```<code><select ng-model="singleSelect">
        <option value="+">+</option>
        <option value="*">*</option>
        <option value="-">-</option>
        <option value="/">/</option>
</select></p> <br/>
</code>```

Body:
I'm trying to create a simple calculator using Angularjs,in my code I can't get the operator value.How can I fix that?

Home html contains get the two numbers and the operator.User have to select the operator..

my Code -

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    //$scope.cdata={};

    console.log("calcCtrl works!");
    var opp;
    ans = 0;
    opp = $scope.singleSelect;

    console.log("opp ==> "+opp);

    $scope.calculateNums = function(nu1, nu2) {
        console.log("function works!");
        console.log("nu1 ==> "+nu1);
        console.log("opp in calculateNums ==> "+opp);
        if (opp == "+") {
            ans = (parseInt(nu1) + parseInt(nu2));
            console.log("ans ==> "+ans);
        } else if (opp == "-") {
            ans = (parseInt(nu1) - parseInt(nu2));
        }
        console.log("ans ==> "+ans);
        return ans;
    }
});

Hello

Number 1::<input Type="text" name="number1" ng-model="n1"/ required>

Number 2::<input Type="text" name="number2" ng-model="n2"/ required>

operator::<select ng-model="singleSelect">
        <option value="+">+</option>
        <option >*</option>
        <option>-</option>
        <option>/</option>
     </select>

<button ng-click="calculateNums(n1,n2)">Calculate Now</button>

So, The output I get is -

calcCtrl works!
opp ==> undefined
function works!
nu1 ==> 1
opp in calculateNums ==> undefined
ans ==> 0

the operator values are undefined here..

Body:
add the value attr to the other options

<select ng-model="singleSelect">
        <option value="+">+</option>
        <option value="*">*</option>
        <option value="-">-</option>
        <option value="/">/</option>
</select></p> <br/>


问:
Function is working in OnClick but not in OnCreate()
I am trying to show  a countdown timer for the user. A Function(myfunc) is working perfect with a button click. But I want to run it as soon as the activity is created. In the Oncreate method. But myfunc not working in the OnCreate method.

Here is the code of MainActivity

```<code>public class MainActivity extends AppCompatActivity {
private enum TimerState {
    STOPPED,
    RUNNING
}

private static final long TIMER_LENGHT = 60; // Sixty seconds
private long mTimeToGo;
private CountDownTimer mCountDownTimer;
private TimerState mState;

@BindView(R.id.main_timer)
TextView mTimerText;

@BindView(R.id.main_timer_button)
Button mTimerButton;

PrefUtils mPreferences;
long startTime;
Calendar rightNow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    mState=TimerState.STOPPED;
    mPreferences = new PrefUtils(this);
    startTime = mPreferences.getStartedTime();
    rightNow = Calendar.getInstance();

            myfunc();

}

@Override
protected void onResume()
{
    super.onResume();
    initTimer();
    removeAlarm();
}
@Override
protected void onPause() {
    super.onPause();
    if (mState == TimerState.RUNNING) {
        mCountDownTimer.cancel();
        setAlarm();
    }
}
private long getNow()
{

    return rightNow.getTimeInMillis() / 1000;
}

private void initTimer()
{

    if (startTime >= 0)
    {
        mTimeToGo = (TIMER_LENGHT - (getNow() - startTime));
        if (mTimeToGo <= 0)
        { // TIMER EXPIRED
            mTimeToGo = TIMER_LENGHT;
            mState = TimerState.STOPPED;
            onTimerFinish();
        }
        else
        {
            startTimer();
            mState = TimerState.RUNNING;
        }
    }
    else
    {
        mTimeToGo = TIMER_LENGHT;
        mState = TimerState.STOPPED;
    }
    updateTimeUi();
}

private void onTimerFinish()
{

    Toast.makeText(getApplicationContext(),R.string.timer_finished,Toast.LENGTH_LONG).show();
    mTimerText.setText(R.string.timer_finished);
    mPreferences.setStartedTime(0);
    mTimeToGo=TIMER_LENGHT ;
    updateTimeUi();
}

private void updateTimeUi()
{
    mTimerText.setText(String.valueOf(mTimeToGo));
}

private void startTimer()
{
    mCountDownTimer = new CountDownTimer(mTimeToGo*1000 , 1000) {
        public void onTick(long millisUntilFinished)
        {
            mTimeToGo -= 1;
            updateTimeUi();
        }
        public void onFinish()
        {
            mState = TimerState.STOPPED;
            onTimerFinish();
            updateTimeUi();
        }
    }.start();
}

public void myfunc()
{
    if  (mState == TimerState.STOPPED) {
        mPreferences.setStartedTime(getNow());
        startTimer();
        mState = TimerState.RUNNING;
    }
}

public void setAlarm() {
    long wakeUpTime = (mPreferences.getStartedTime() + TIMER_LENGHT) * 1000;
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, TimerExpiredReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        am.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeUpTime, sender), sender);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, sender);
    }
}

public void removeAlarm() {
    Intent intent = new Intent(this, TimerExpiredReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.cancel(sender);
}
</code>```

}

And one utils code is here

```<code>class PrefUtils {
private static final String STARTED_TIME_ID = "com.whiterabbit.time";
private SharedPreferences mPreferences;

PrefUtils(Context c)
{
    mPreferences = PreferenceManager.getDefaultSharedPreferences(c);
}

long getStartedTime()
{
    return mPreferences.getLong(STARTED_TIME_ID, 0);
}

void setStartedTime(long started) {
    SharedPreferences.Editor editor = mPreferences.edit();
    editor.putLong(STARTED_TIME_ID, started);
    editor.apply();
}
</code>```

}

And The Broadcast Receiver is here too

```<code> @Override
public void onReceive(Context context, Intent intent)
{
    Intent i = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, i, 0);

    NotificationCompat.Builder b = new NotificationCompat.Builder(context);
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    b.setSound(notification)
            .setContentTitle(context.getString(R.string.timer_finished))
            .setAutoCancel(true)
            .setContentText(context.getString(R.string.timer_finished))
            .setSmallIcon(android.R.drawable.ic_notification_clear_all)
            .setContentIntent(pIntent);

    Notification n = b.build();
    NotificationManager mNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, n);
}
</code>```

答:
Before Call  myfunc call  initTimer once.Because onResume will be call after onCreate or delay some seconds in oncreate</p>

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mState=TimerState.STOPPED;
mPreferences = new PrefUtils(this);
startTime = mPreferences.getStartedTime();
rightNow = Calendar.getInstance();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
myfunc();
}
}, 100);//Delay 100ms

}
</code>```

Body:
I am trying to show  a countdown timer for the user. A Function(myfunc) is working perfect with a button click. But I want to run it as soon as the activity is created. In the Oncreate method. But myfunc not working in the OnCreate method.

Here is the code of MainActivity

public class MainActivity extends AppCompatActivity {
private enum TimerState {
    STOPPED,
    RUNNING
}

private static final long TIMER_LENGHT = 60; // Sixty seconds
private long mTimeToGo;
private CountDownTimer mCountDownTimer;
private TimerState mState;

@BindView(R.id.main_timer)
TextView mTimerText;

@BindView(R.id.main_timer_button)
Button mTimerButton;

PrefUtils mPreferences;
long startTime;
Calendar rightNow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    mState=TimerState.STOPPED;
    mPreferences = new PrefUtils(this);
    startTime = mPreferences.getStartedTime();
    rightNow = Calendar.getInstance();

            myfunc();

}

@Override
protected void onResume()
{
    super.onResume();
    initTimer();
    removeAlarm();
}
@Override
protected void onPause() {
    super.onPause();
    if (mState == TimerState.RUNNING) {
        mCountDownTimer.cancel();
        setAlarm();
    }
}
private long getNow()
{

    return rightNow.getTimeInMillis() / 1000;
}

private void initTimer()
{

    if (startTime >= 0)
    {
        mTimeToGo = (TIMER_LENGHT - (getNow() - startTime));
        if (mTimeToGo <= 0)
        { // TIMER EXPIRED
            mTimeToGo = TIMER_LENGHT;
            mState = TimerState.STOPPED;
            onTimerFinish();
        }
        else
        {
            startTimer();
            mState = TimerState.RUNNING;
        }
    }
    else
    {
        mTimeToGo = TIMER_LENGHT;
        mState = TimerState.STOPPED;
    }
    updateTimeUi();
}

private void onTimerFinish()
{

    Toast.makeText(getApplicationContext(),R.string.timer_finished,Toast.LENGTH_LONG).show();
    mTimerText.setText(R.string.timer_finished);
    mPreferences.setStartedTime(0);
    mTimeToGo=TIMER_LENGHT ;
    updateTimeUi();
}

private void updateTimeUi()
{
    mTimerText.setText(String.valueOf(mTimeToGo));
}

private void startTimer()
{
    mCountDownTimer = new CountDownTimer(mTimeToGo*1000 , 1000) {
        public void onTick(long millisUntilFinished)
        {
            mTimeToGo -= 1;
            updateTimeUi();
        }
        public void onFinish()
        {
            mState = TimerState.STOPPED;
            onTimerFinish();
            updateTimeUi();
        }
    }.start();
}

public void myfunc()
{
    if  (mState == TimerState.STOPPED) {
        mPreferences.setStartedTime(getNow());
        startTimer();
        mState = TimerState.RUNNING;
    }
}

public void setAlarm() {
    long wakeUpTime = (mPreferences.getStartedTime() + TIMER_LENGHT) * 1000;
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, TimerExpiredReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        am.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeUpTime, sender), sender);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, sender);
    }
}

public void removeAlarm() {
    Intent intent = new Intent(this, TimerExpiredReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.cancel(sender);
}

}

And one utils code is here

class PrefUtils {
private static final String STARTED_TIME_ID = "com.whiterabbit.time";
private SharedPreferences mPreferences;

PrefUtils(Context c)
{
    mPreferences = PreferenceManager.getDefaultSharedPreferences(c);
}

long getStartedTime()
{
    return mPreferences.getLong(STARTED_TIME_ID, 0);
}

void setStartedTime(long started) {
    SharedPreferences.Editor editor = mPreferences.edit();
    editor.putLong(STARTED_TIME_ID, started);
    editor.apply();
}

}

And The Broadcast Receiver is here too

 @Override
public void onReceive(Context context, Intent intent)
{
    Intent i = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, i, 0);

    NotificationCompat.Builder b = new NotificationCompat.Builder(context);
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    b.setSound(notification)
            .setContentTitle(context.getString(R.string.timer_finished))
            .setAutoCancel(true)
            .setContentText(context.getString(R.string.timer_finished))
            .setSmallIcon(android.R.drawable.ic_notification_clear_all)
            .setContentIntent(pIntent);

    Notification n = b.build();
    NotificationManager mNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, n);
}

Body:
Before Call  myfunc call  initTimer once.Because onResume will be call after onCreate or delay some seconds in oncreate

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mState=TimerState.STOPPED;
mPreferences = new PrefUtils(this);
startTime = mPreferences.getStartedTime();
rightNow = Calendar.getInstance();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
myfunc();
}
}, 100);//Delay 100ms

}


问:
Break CSS into rules
I have the content of a CSS file as a string I got with an AJAX request.

I need to break it into rules that I can feed into styleSheet.insertRule

What is the best way to achieve this correctly and efficiently ? I do not want to include/write a full CSS parser just for that if possible ...

I considered simply splitting on '}' but this will not work if there are @media clauses which created nested curly brackets, and I am not sure it is correct otherwise ...

Thanks!

答:
The solution from Nisarg Shah probably does the job, but here's an alternative. It uses the css.js library to parse the CSS string into a JS array, which can then be inserted using stylesheet.insertRule().

The two advantages this method has:

It breaks the CSS into rules as stated in the question

It would allow styles to be filtered or altered before insertion

Also, this is a simplified solution that will not work with more complicated CSS containing media queries or similar rules. For a more robust solution, the function would need to handle those types of style rules, and more info on how to do that can be found in the MDN docs.

Here's the approach:

Get the CSS from your API

Parse the CSS into a JS array of objects

Loop through the CSS rules and create the CSS style string

Add the style string to the stylesheet with insertRule()

var cssString = `
div {
  color: green;
  font-size: 24px;
}`;

setTimeout(function() {
  var parsedStyles = addStylesAndReturnParsedStyles(cssString);
  console.log(parsedStyles)
}, 1000);

var addStylesAndReturnParsedStyles = function(cssString) {
  var parser = new cssjs();
  var parsed = parser.parseCSS(cssString);
  var styleEl = document.createElement('style'),
      styleSheet;

  // Append style element to head
  document.head.appendChild(styleEl);

  // Grab style sheet
  styleSheet = styleEl.sheet;

  parsed.forEach(style => {
    var selector = style.selector;
    var rules = style.rules;
    var propStr = '';

    for (var i = 0; i < rules.length; i++) {
      var prop = rules[i];
      propStr += prop.directive + ':' + prop.value + ';\n';
    }

    // Insert CSS Rules
    styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);
  });

  return parsed;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.rawgit.com/jotform/css.js/master/css.min.js"></script>
<div>Here's some content</div></code>```

Title: Break CSS into rules

Body:
The solution from Nisarg Shah probably does the job, but here's an alternative. It uses the css.js library to parse the CSS string into a JS array, which can then be inserted using stylesheet.insertRule().

The two advantages this method has:

It breaks the CSS into rules as stated in the question

It would allow styles to be filtered or altered before insertion

Also, this is a simplified solution that will not work with more complicated CSS containing media queries or similar rules. For a more robust solution, the function would need to handle those types of style rules, and more info on how to do that can be found in the MDN docs.

Here's the approach:

Get the CSS from your API

Parse the CSS into a JS array of objects

Loop through the CSS rules and create the CSS style string

Add the style string to the stylesheet with insertRule()

var cssString = `
div {
  color: green;
  font-size: 24px;
}`;

setTimeout(function() {
  var parsedStyles = addStylesAndReturnParsedStyles(cssString);
  console.log(parsedStyles)
}, 1000);

var addStylesAndReturnParsedStyles = function(cssString) {
  var parser = new cssjs();
  var parsed = parser.parseCSS(cssString);
  var styleEl = document.createElement('style'),
      styleSheet;

  // Append style element to head
  document.head.appendChild(styleEl);

  // Grab style sheet
  styleSheet = styleEl.sheet;

  parsed.forEach(style => {
    var selector = style.selector;
    var rules = style.rules;
    var propStr = '';

    for (var i = 0; i < rules.length; i++) {
      var prop = rules[i];
      propStr += prop.directive + ':' + prop.value + ';\n';
    }

    // Insert CSS Rules
    styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);
  });

  return parsed;
};

<script src="https://cdn.rawgit.com/jotform/css.js/master/css.min.js"></script>
<div>Here's some content</div>