问:
assign template to other pages
I am trying to assign my other templates to menus that I have created in the backend of my joomla project.

Should I create another templateDetails.xml for my other templates to display in the template manager?

Or am I missing any code to activate my other template to the template manager?

Here is my main page:

<?php

    defined( '_JEXEC' ) or die( 'Restricted Access' );

    echo '<?xml version="1.0" encoding="utf-8"?'.'>';

    $doc = JFactory::getDocument();

    /* Let's tell Joomla! to use HTML5 */
    $doc->setHtml5(true);

?>

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i" rel="stylesheet">

    <jdoc:include type="head" />

    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/normalize.min.css" type="text/css" />
    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/main.css" type="text/css" />
    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/cognitif.css" type="text/css">

                                <jdoc:include type="modules" name="redbox-menu" style="xhtml"/>

<input type="text" class="search-box" placeholder="SEARCH"/>

(02) 621 0631

h1.title

                  <jdoc:include type="modules" name="main-menu" style="xhtml"/>

                <header style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/mainpage-banner.png)">

Let’s collaborate on Making Possibilities

                                I am an
                                    <select class="red-selection">
                                        <option>Owner</option>
                                        <option>Option2</option>
                                        <option>Option3</option>
                                        <option>Option4</option>
                                    </select>

                                <input type="text" class="input-standard" placeholder="Looking for..." />

                                Organization Size

                                <input type="text" class="input-standard" placeholder="1-5" />

                                Department

                                <input type="text" class="input-standard" placeholder="Sales" />

                                <button class="button large-btn">Collaborate Now</button>

                <div style="background: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/bg-emblem.png) center 200px no-repeat;">

                                <img src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/cognitif-emblem.png">

Our promise, already a given

                                <jdoc:include type="modules" name="our-promise" style="xhtml"/>

                                    <jdoc:include type="modules" name="business-care" style="xhtml"/>

                                    <jdoc:include type="modules" name="reliable-service" style="xhtml"/>

                                    <jdoc:include type="modules" name="realized-gains" style="xhtml"/>

                                    <jdoc:include type="modules" name="perfect-solutions" style="xhtml"/>

                                <img src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/array-ico.png">

Wide array of businesses

                                <jdoc:include type="modules" name="our-business" style="xhtml"/>

                                    <jdoc:include type="modules" name="business-consulting" style="xhtml"/>

                                    <jdoc:include type="modules" name="knowledge-process" style="xhtml"/>

                                    <jdoc:include type="modules" name="executed-search" style="xhtml"/>

                                    <jdoc:include type="modules" name="integrated-business" style="xhtml"/>

                            <div class="image-box cols-31" style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/people.png)">

Solutions to an ever changing market

                                    <jdoc:include type="modules" name="featured-content" style="xhtml"/>

Join our Referral Program

                                <jdoc:include type="modules" name="referral-box" style="xhtml"/>

News

Lorem ipsum dolor sit amet

2days ago by Cognitif

Pellentesque quis massa ultricies, varius velit sodales, consectetur sem. Praesent at

Read More

News

Sed cursus blandit rhoncus

2days ago by Cognitif

Pellentesque quis massa ultricies, varius velit sodales, consectetur sem. Praesent at

Read More

                                <div class="thumbnail" style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/woman.png)">

Featured

Etiam et molestie turpis

2days ago by Cognitif

Pellentesque quis massa ultricies, varius velit sodales, consectetur sem. Praesent at

Read More

Strong business relationships

Nullam accumsan scelerisque leo, sed ultricies orci tristique non. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Maecenas eget velit id leo scelerisque molestie.

                        <footer class="contact-form clearfix" style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/contact-bg.png)">

Together, we’ll do great.

 Cras venenatis feugiat nibh quis tempus. Quisque libero nibh, consequat posuere, tempus pulvinar purus.

                                <form class="rounded-input">
                                    <input type="text" class="rounded-input cols-4" placeholder="Your Name" />
                                    <input type="text" class="rounded-input cols-4" placeholder="Position" />
                                    <input type="text" class="rounded-input cols-4" placeholder="Company Name" />
                                    <input type="text" class="rounded-input cols-4" placeholder="Email Name" />

                                        <input type="checkbox" class="rounded-input"/> I’m looking for the best solution with fantastic local support.

                                    <button class="button">Get a Solution</button>

*Your privacy is very important to us. To learn more about our information processesing procedures, please visit our Privacy Policy.

                                </form>

                    <img src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/cognitif-white-transparent.png">

Unit 3010, One Corporate Center, Julia Vargas Street, corner Meralco Avenue, Ortigas Center, Pasig City, Metro Manila

(02) 621 0631

Get in touch

                        <jdoc:include type="modules" name="getintouch-menu" style="xhtml"/>

Our company in a glance

                        <jdoc:include type="modules" name="ourcompany-menu" style="xhtml"/>

Area of Expertise

                        <jdoc:include type="modules" name="aoe-menu" style="xhtml"/>

Area of Expertise

                        <jdoc:include type="modules" name="aoe-menu" style="xhtml"/>

Copyright © 2017 Cognitif. All rights reserved.

X

                <input type="text" class="search-box" placeholder="Search for..." />

                <jdoc:include type="modules" name="mobile-menu" style="xhtml"/>

                <jdoc:include type="modules" name="sub-menu" style="xhtml"/>

```
</div>
</div>
</p>
<p>And here is my code for my other page:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php

    defined( '_JEXEC' ) or die( 'Restricted Access' );

    echo '<?xml version="1.0" encoding="utf-8"?'.'>';

    $doc = JFactory::getDocument();

    /* Let's tell Joomla! to use HTML5 */
    $doc->setHtml5(true);

?>

<!doctype html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]-->
<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i" rel="stylesheet">

    <jdoc:include type="head" />

    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/normalize.min.css" type="text/css" />
    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/main.css" type="text/css" />
    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/cognitif.css" type="text/css">

    <script src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>

</head>
    <body>
        <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
        <![endif]-->

        <div class="header-container">
            <div class="red-box">
                <div class="wrapper clearfix">
                    <div class="cols-2">
                        <jdoc:include type="modules" name="redbox-menu" style="xhtml"/>
                    </div>
                    <div class="cols-2 nav-align-right">
                        <ul>
                            <li><input type="text" class="search-box" placeholder="SEARCH"/></li>
                            <li>(02) 621 0631</li>
                        </ul>
                    </div>
                </div>
            </div>
            <header class="wrapper clearfix">
                <div class="title"><div id="open-menu"></div><span class="hidden">h1.title</span></div>
                <nav>
                                    <jdoc:include type="modules" name="main-menu" style="xhtml"/>
                </nav>
            </header>
        </div>

        <div class="main-container page">

            <article>
                <header style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/about-header.jpg)">
                    <div class="wrapper">
                        <h1>About Us</h1>
                    </div>
                </header>
            </article>

            <article>
                <div class="page-content wrapper clearfix">
                    <section class="clearfix">
                        <div id="breadcrumb">
                            <?php JFactory::getApplication()->getPathWay(); ?>
                        </div>

                        <h2>Lorem ipsum dolor sit amet</h2>
                        <p>Vivamus vel varius velit, at sodales tortor. Suspendisse dignissim ac nisi in auctor. Mauris leo mauris, ultrices a purus id, sagittis rutrum felis. Vestibulum pretium, tellus vitae mattis mollis, nisi mauris ornare metus, vitae tempor nibh massa ac tellus. Nunc eu massa interdum, semper felis placerat, vestibulum diam. Mauris ut pulvinar nibh.</p>
                        <p>Maecenas molestie enim ut mollis tincidunt. Donec iaculis cursus malesuada. Suspendisse vitae tellus iaculis, rutrum ipsum molestie, auctor nunc. Fusce leo metus, dapibus ut enim quis, sodales luctus urna. Donec ultricies ac ex ac venenatis. Suspendisse eleifend finibus porttitor. Maecenas dictum dolor aliquet lorem elementum ultrices.</p>
                        <p>Integer iaculis auctor orci, ut faucibus augue. Nulla sagittis viverra scelerisque. Suspendisse lobortis metus sed mi vestibulum faucibus. Pellentesque congue elit ligula, vel pretium tortor rhoncus vitae. Aliquam quis orci nec ipsum commodo auctor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis </p>
                        <p>Praesent eget ipsum ac dui commodo ornare. Aliquam gravida ipsum nec ultrices fermentum. Aliquam in turpis sollicitudin, blandit turpis at, vestibulum lacus. Maecenas finibus ac neque sit amet luctus. Curabitur quis ipsum eget velit auctor fringilla.</p>

                        <h3>Aenean molestie lacus a blandit</h3>
                        <p>Nunc ipsum tellus, viverra molestie leo ut Integer iaculis auctor orci, ut faucibus augue. Nulla sagittis viverra scelerisque. Suspendisse lobortis metus sed mi vestibulum faucibus. Pellentesque congue elit ligula, vel pretium tortor rhoncus vitae. Aliquam quis orci nec ipsum commodo auctor. Aliquam gravida ipsum nec ultrices fermentum. Aliquam in turpis sollicitudin, blandit turpis at, vestibulum lacus. </p>
                        <p>Maecenas finibus ac neque sit amet luctus. Curabitur quis ipsum eget velit auctor fringilla. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam vel vulputate sem. Aenean justo diam, feugiat sit amet dolor eget, maximus mollis velit.</p>

                        <h3>Nunc accumsan varius ipsum, eu maximus</h3>
                        <div class="clearfix">
                            <div class="cols-2">
                                <img src="img/thumb-01.jpg">
                                <h4>Vivamus dictum augue arcu</h4>
                                <h5>Maecenas Etiam</h5>
                                <p>Integer iaculis auctor orci, ut faucibus augue. Nulla sagittis viverra scelerisque. Suspendisse lobortis metus sed mi vestibulum faucibus. Pellentesque congue elit ligula, vel pretium tortor rhoncus vitae. Aliquam quis orci nec ipsum commodo auctor. Aliquam gravida ipsum nec ultrices fermentum. Aliquam in turpis sollicitudin.</p>
                            </div>
                            <div class="cols-2">
                                <img src="img/thumb-02.jpg">
                                <h4>Quisque ac velit congue</h4>
                                <h5>Aliquam Fusce</h5>
                                <p>Integer iaculis auctor orci, ut faucibus augue. Nulla sagittis viverra scelerisque. Suspendisse lobortis metus sed mi vestibulum faucibus. Pellentesque congue elit ligula, vel pretium tortor rhoncus vitae. Aliquam quis orci nec ipsum commodo auctor. Aliquam gravida ipsum nec ultrices fermentum. Aliquam in turpis sollicitudin.</p>
                            </div>
                        </div>
                    </section>

                    <aside>
                        <input type="text" class="aside-search" placeholder="Search Topics..." />
                        <ul>
                            <li class="active">About Us</li>
                            <li>News and Media</li>
                            <li>Knowledge and Insights</li>
                            <li>Awards and Recognition</li>
                            <li>History</li>
                            <li>Corporate Governance</li>
                            <li>Sponsorship</li>
                            <li>Notifications</li>
                            <li class="last">Contact Us</li>
                        </ul>
                    </aside>
                </div>
            </article>

        </div> <!-- #main-container -->

        <div class="footer-container">
            <footer class="black-bg wrapper clearfix">
                <div class="cols-33">
                    <img src="img/cognitif-white-transparent.png">
                    <p>Unit 3010, One Corporate Center, Julia Vargas Street, corner Meralco Avenue, Ortigas Center, Pasig City, Metro Manila</p>
                    <p>(02) 621 0631</p>
                </div>

                <div class="cols-31 footer-navs clearfix">
                    <div class="cols-4">
                        <h4>Get in touch</h4>
                        <jdoc:include type="modules" name="getintouch-menu" style="xhtml"/>
                    </div>
                    <div class="cols-4">
                        <h4>Our company in a glance</h4>
                        <jdoc:include type="modules" name="ourcompany-menu" style="xhtml"/>
                    </div>
                    <div class="cols-4">
                        <h4>Area of Expertise</h4>
                        <jdoc:include type="modules" name="aoe-menu" style="xhtml"/>
                    </div>
                    <div class="cols-4">
                        <h4>Area of Expertise</h4>
                        <jdoc:include type="modules" name="aoe-menu" style="xhtml"/>
                    </div>
                </div>
            </footer>

            <div class="center-content baseline">Copyright © 2017 Cognitif. All rights reserved.</div>

        </div>

        <div id="mobile-menu">
            <div style="position: relative">
                <div id="close-menu">X</div>
                <input type="text" class="search-box" placeholder="Search for..." />

                <jdoc:include type="modules" name="mobile-menu" style="xhtml"/>

                <jdoc:include type="modules" name="sub-menu" style="xhtml"/>

            </div>
        </div>
        <div id="mobile-menu-closer"></div>

        <!--script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script-->
      <script>window.jQuery || document.write('<script src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/js/vendor/jquery-1.11.2.min.js"><\/script>')</script>

      <script src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/js/main.js"></script>
    </body>
</html></code>```

I am suspecting that I have missing code that I need to put on my second page in order for the template manager to read my second template.

答:
From what you describe it sounds like your second template may not be correctly installed. If you don't see it under Extensions > Templates > Templates then you need to fix that first.

I am wondering if should I create another templateDetails.xml ...

Yes, your second template would need this. The typical template has its own folder which would have at minimum index.php, templateDetails.xml, and usually css, js and image files.

If you think this is already in place, try Extensions > Manage > Discover then Discover. This may find a template which hasn't been correctly installed.

Once your second template is showing in the Extensions > Templates > Templates (formerly the Template Manager), you can assign menu items to the second template from Extensions > Templates > Styles.  From this screen select your second template then go to the Menu Assignment tab.

Good luck

Title: assign template to other pages

Body:
I am trying to assign my other templates to menus that I have created in the backend of my joomla project.

Should I create another templateDetails.xml for my other templates to display in the template manager?

Or am I missing any code to activate my other template to the template manager?

Here is my main page:

<?php

    defined( '_JEXEC' ) or die( 'Restricted Access' );

    echo '<?xml version="1.0" encoding="utf-8"?'.'>';

    $doc = JFactory::getDocument();

    /* Let's tell Joomla! to use HTML5 */
    $doc->setHtml5(true);

?>

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i" rel="stylesheet">

    <jdoc:include type="head" />

    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/normalize.min.css" type="text/css" />
    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/main.css" type="text/css" />
    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/cognitif.css" type="text/css">

                                <jdoc:include type="modules" name="redbox-menu" style="xhtml"/>

<input type="text" class="search-box" placeholder="SEARCH"/>

(02) 621 0631

h1.title

                  <jdoc:include type="modules" name="main-menu" style="xhtml"/>

                <header style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/mainpage-banner.png)">

Let’s collaborate on Making Possibilities

                                I am an
                                    <select class="red-selection">
                                        <option>Owner</option>
                                        <option>Option2</option>
                                        <option>Option3</option>
                                        <option>Option4</option>
                                    </select>

                                <input type="text" class="input-standard" placeholder="Looking for..." />

                                Organization Size

                                <input type="text" class="input-standard" placeholder="1-5" />

                                Department

                                <input type="text" class="input-standard" placeholder="Sales" />

                                <button class="button large-btn">Collaborate Now</button>

                <div style="background: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/bg-emblem.png) center 200px no-repeat;">

                                <img src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/cognitif-emblem.png">

Our promise, already a given

                                <jdoc:include type="modules" name="our-promise" style="xhtml"/>

                                    <jdoc:include type="modules" name="business-care" style="xhtml"/>

                                    <jdoc:include type="modules" name="reliable-service" style="xhtml"/>

                                    <jdoc:include type="modules" name="realized-gains" style="xhtml"/>

                                    <jdoc:include type="modules" name="perfect-solutions" style="xhtml"/>

                                <img src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/array-ico.png">

Wide array of businesses

                                <jdoc:include type="modules" name="our-business" style="xhtml"/>

                                    <jdoc:include type="modules" name="business-consulting" style="xhtml"/>

                                    <jdoc:include type="modules" name="knowledge-process" style="xhtml"/>

                                    <jdoc:include type="modules" name="executed-search" style="xhtml"/>

                                    <jdoc:include type="modules" name="integrated-business" style="xhtml"/>

                            <div class="image-box cols-31" style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/people.png)">

Solutions to an ever changing market

                                    <jdoc:include type="modules" name="featured-content" style="xhtml"/>

Join our Referral Program

                                <jdoc:include type="modules" name="referral-box" style="xhtml"/>

News

Lorem ipsum dolor sit amet

2days ago by Cognitif

Pellentesque quis massa ultricies, varius velit sodales, consectetur sem. Praesent at

Read More

News

Sed cursus blandit rhoncus

2days ago by Cognitif

Pellentesque quis massa ultricies, varius velit sodales, consectetur sem. Praesent at

Read More

                                <div class="thumbnail" style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/woman.png)">

Featured

Etiam et molestie turpis

2days ago by Cognitif

Pellentesque quis massa ultricies, varius velit sodales, consectetur sem. Praesent at

Read More

Strong business relationships

Nullam accumsan scelerisque leo, sed ultricies orci tristique non. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Maecenas eget velit id leo scelerisque molestie.

                        <footer class="contact-form clearfix" style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/contact-bg.png)">

Together, we’ll do great.

 Cras venenatis feugiat nibh quis tempus. Quisque libero nibh, consequat posuere, tempus pulvinar purus.

                                <form class="rounded-input">
                                    <input type="text" class="rounded-input cols-4" placeholder="Your Name" />
                                    <input type="text" class="rounded-input cols-4" placeholder="Position" />
                                    <input type="text" class="rounded-input cols-4" placeholder="Company Name" />
                                    <input type="text" class="rounded-input cols-4" placeholder="Email Name" />

                                        <input type="checkbox" class="rounded-input"/> I’m looking for the best solution with fantastic local support.

                                    <button class="button">Get a Solution</button>

*Your privacy is very important to us. To learn more about our information processesing procedures, please visit our Privacy Policy.

                                </form>

                    <img src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/cognitif-white-transparent.png">

Unit 3010, One Corporate Center, Julia Vargas Street, corner Meralco Avenue, Ortigas Center, Pasig City, Metro Manila

(02) 621 0631

Get in touch

                        <jdoc:include type="modules" name="getintouch-menu" style="xhtml"/>

Our company in a glance

                        <jdoc:include type="modules" name="ourcompany-menu" style="xhtml"/>

Area of Expertise

                        <jdoc:include type="modules" name="aoe-menu" style="xhtml"/>

Area of Expertise

                        <jdoc:include type="modules" name="aoe-menu" style="xhtml"/>

Copyright © 2017 Cognitif. All rights reserved.

X

                <input type="text" class="search-box" placeholder="Search for..." />

                <jdoc:include type="modules" name="mobile-menu" style="xhtml"/>

                <jdoc:include type="modules" name="sub-menu" style="xhtml"/>

And here is my code for my other page:

<?php

    defined( '_JEXEC' ) or die( 'Restricted Access' );

    echo '<?xml version="1.0" encoding="utf-8"?'.'>';

    $doc = JFactory::getDocument();

    /* Let's tell Joomla! to use HTML5 */
    $doc->setHtml5(true);

?>

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i" rel="stylesheet">

    <jdoc:include type="head" />

    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/normalize.min.css" type="text/css" />
    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/main.css" type="text/css" />
    <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/cognitif.css" type="text/css">

                        <jdoc:include type="modules" name="redbox-menu" style="xhtml"/>

<input type="text" class="search-box" placeholder="SEARCH"/>

(02) 621 0631

h1.title

                                    <jdoc:include type="modules" name="main-menu" style="xhtml"/>

                <header style="background-image: url(<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/img/about-header.jpg)">

About Us

                            <?php JFactory::getApplication()->getPathWay(); ?>

Lorem ipsum dolor sit amet

Vivamus vel varius velit, at sodales tortor. Suspendisse dignissim ac nisi in auctor. Mauris leo mauris, ultrices a purus id, sagittis rutrum felis. Vestibulum pretium, tellus vitae mattis mollis, nisi mauris ornare metus, vitae tempor nibh massa ac tellus. Nunc eu massa interdum, semper felis placerat, vestibulum diam. Mauris ut pulvinar nibh.

Maecenas molestie enim ut mollis tincidunt. Donec iaculis cursus malesuada. Suspendisse vitae tellus iaculis, rutrum ipsum molestie, auctor nunc. Fusce leo metus, dapibus ut enim quis, sodales luctus urna. Donec ultricies ac ex ac venenatis. Suspendisse eleifend finibus porttitor. Maecenas dictum dolor aliquet lorem elementum ultrices.

Integer iaculis auctor orci, ut faucibus augue. Nulla sagittis viverra scelerisque. Suspendisse lobortis metus sed mi vestibulum faucibus. Pellentesque congue elit ligula, vel pretium tortor rhoncus vitae. Aliquam quis orci nec ipsum commodo auctor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis

Praesent eget ipsum ac dui commodo ornare. Aliquam gravida ipsum nec ultrices fermentum. Aliquam in turpis sollicitudin, blandit turpis at, vestibulum lacus. Maecenas finibus ac neque sit amet luctus. Curabitur quis ipsum eget velit auctor fringilla.

Aenean molestie lacus a blandit

Nunc ipsum tellus, viverra molestie leo ut Integer iaculis auctor orci, ut faucibus augue. Nulla sagittis viverra scelerisque. Suspendisse lobortis metus sed mi vestibulum faucibus. Pellentesque congue elit ligula, vel pretium tortor rhoncus vitae. Aliquam quis orci nec ipsum commodo auctor. Aliquam gravida ipsum nec ultrices fermentum. Aliquam in turpis sollicitudin, blandit turpis at, vestibulum lacus.

Maecenas finibus ac neque sit amet luctus. Curabitur quis ipsum eget velit auctor fringilla. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam vel vulputate sem. Aenean justo diam, feugiat sit amet dolor eget, maximus mollis velit.

Nunc accumsan varius ipsum, eu maximus

Vivamus dictum augue arcu

Maecenas Etiam

Integer iaculis auctor orci, ut faucibus augue. Nulla sagittis viverra scelerisque. Suspendisse lobortis metus sed mi vestibulum faucibus. Pellentesque congue elit ligula, vel pretium tortor rhoncus vitae. Aliquam quis orci nec ipsum commodo auctor. Aliquam gravida ipsum nec ultrices fermentum. Aliquam in turpis sollicitudin.

Quisque ac velit congue

Aliquam Fusce

Integer iaculis auctor orci, ut faucibus augue. Nulla sagittis viverra scelerisque. Suspendisse lobortis metus sed mi vestibulum faucibus. Pellentesque congue elit ligula, vel pretium tortor rhoncus vitae. Aliquam quis orci nec ipsum commodo auctor. Aliquam gravida ipsum nec ultrices fermentum. Aliquam in turpis sollicitudin.

                        <input type="text" class="aside-search" placeholder="Search Topics..." />

About Us

News and Media

Knowledge and Insights

Awards and Recognition

History

Corporate Governance

Sponsorship

Notifications

Contact Us

Unit 3010, One Corporate Center, Julia Vargas Street, corner Meralco Avenue, Ortigas Center, Pasig City, Metro Manila

(02) 621 0631

Get in touch

                        <jdoc:include type="modules" name="getintouch-menu" style="xhtml"/>

Our company in a glance

                        <jdoc:include type="modules" name="ourcompany-menu" style="xhtml"/>

Area of Expertise

                        <jdoc:include type="modules" name="aoe-menu" style="xhtml"/>

Area of Expertise

                        <jdoc:include type="modules" name="aoe-menu" style="xhtml"/>

Copyright © 2017 Cognitif. All rights reserved.

X

                <input type="text" class="search-box" placeholder="Search for..." />

                <jdoc:include type="modules" name="mobile-menu" style="xhtml"/>

                <jdoc:include type="modules" name="sub-menu" style="xhtml"/>

I am suspecting that I have missing code that I need to put on my second page in order for the template manager to read my second template.


来源: stackexchange

问:
Adding overlay buttons to tvOS AVPlayerViewController
I'm trying to build an overlay that appears over an AVPlayer when I press pause. The problem I'm having is that while I can overlay buttons just fine I can't get the focus engine in tvOS to focus on them... I'm pretty sure this is happening as the player frame robs focus (it's fullscreen @ 1080p) and I can't focus on objects that are inside of its frame.

Pseudo code for what I'm doing:

```<code>class MyViewController: UIViewController {
    var playerController = AVPlayerViewController()
    @IBOutlet weak var button: UIButton! // button centred on screen that requires focus

    override func viewDidLoad() {
        super.viewDidLoad()
        self.playerController.player = AVPlayer(url: myURL)
        self.playerController.view.frame = self.view.bounds
        self.view.addSubview(self.playerController.view)
        self.view.bringSubview(toFront: self.button)
    }

    // ... functions that enable listeners and show/hide button when self.playerController.player rate changes
}
</code>```

What I want is to be able to press pause, then swipe up to get focus on the button(s) instead of the seek bar and then swipe back down to the seek bar if needed. Much like the Apple Music application that comes with the tvOS.

Thanks.

答:
My solution is to override preferredFocusEnvironment and add some listeners to the parent VC to change a condition when certain actions are taken...not perfect but good enough.</p>

```<code>override var preferredFocusEnvironment {
    if self.someCondition {
        return [self.button]
    }
    else {
        return [self.playerController.view]
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to build an overlay that appears over an AVPlayer when I press pause. The problem I'm having is that while I can overlay buttons just fine I can't get the focus engine in tvOS to focus on them... I'm pretty sure this is happening as the player frame robs focus (it's fullscreen @ 1080p) and I can't focus on objects that are inside of its frame.

Pseudo code for what I'm doing:

class MyViewController: UIViewController {
    var playerController = AVPlayerViewController()
    @IBOutlet weak var button: UIButton! // button centred on screen that requires focus

    override func viewDidLoad() {
        super.viewDidLoad()
        self.playerController.player = AVPlayer(url: myURL)
        self.playerController.view.frame = self.view.bounds
        self.view.addSubview(self.playerController.view)
        self.view.bringSubview(toFront: self.button)
    }

    // ... functions that enable listeners and show/hide button when self.playerController.player rate changes
}

What I want is to be able to press pause, then swipe up to get focus on the button(s) instead of the seek bar and then swipe back down to the seek bar if needed. Much like the Apple Music application that comes with the tvOS.

Thanks.

Body:
My solution is to override preferredFocusEnvironment and add some listeners to the parent VC to change a condition when certain actions are taken...not perfect but good enough.

override var preferredFocusEnvironment {
    if self.someCondition {
        return [self.button]
    }
    else {
        return [self.playerController.view]
    }
}


问:
React is failing to render simple Hello World in MVC project
I got starting ASP.NET MVC project with the following resources added:

```<code>@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")

<script src="~/Scripts/require.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

@RenderSection("scripts", required: false)
</code>```

Section scripts in Index.cshtml:

```<code><div id="root"></div>

@section scripts
{
    <script src="~/Scripts/ReactJS/Index.js" type="text/babel"></script>
}
</code>```

And the file itself:

```<code>import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('root')
);
</code>```

The result is empty page with no errors.
I do not want to use Node.js, I do not want to use even require.js and babel.js, but it seems I have to.
What are the minimal dependencies of reactjs to work properly?

答:
First, ensure ReactJS core files & Remarkable.js referenced properly as this:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/[version]/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/[version]/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/[version]/remarkable.min.js"></script>
</code>```

(more info: ReactJS MVC / ReactJS Core MVC)

Then, add JSX file in either  tag or Scripts section:

```<code>@section Scripts {
    <script src="~/Scripts/ReactJS/Index.jsx"></script>
}
</code>```

Assume in your  tag has this div container to bind...

```<code><div id="root"></div>
</code>```

Then, in JSX file the React script should be looks like this:

// Index.jsx
var Root = React.createClass({
               render: function () {
                       return (

Hello, world!

                       );
               }
           });

ReactDOM.render(<Root />, document.getElementById('root'));
```

As the tutorial page said, BabelJS required if you want to use ES6 features such as arrow functions & concise methods, or use bundling mechanism (BabelBundle instead of plain ScriptBundle) to load JSX file.

Related issue:

ReactJS.NET MVC tutorial doesn't work?

Body:
I got starting ASP.NET MVC project with the following resources added:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")

@RenderSection("scripts", required: false)

Section scripts in Index.cshtml:

@section scripts
{

}

And the file itself:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(

Hello, world!
,
    document.getElementById('root')
);

The result is empty page with no errors.
I do not want to use Node.js, I do not want to use even require.js and babel.js, but it seems I have to.
What are the minimal dependencies of reactjs to work properly?

Body:
First, ensure ReactJS core files & Remarkable.js referenced properly as this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/[version]/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/[version]/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/[version]/remarkable.min.js"></script>

(more info: ReactJS MVC / ReactJS Core MVC)

Then, add JSX file in either <head> tag or Scripts section:

@section Scripts {
    <script src="~/Scripts/ReactJS/Index.jsx"></script>
}

Assume in your <body> tag has this div container to bind...

<div id="root"></div>

Then, in JSX file the React script should be looks like this:

// Index.jsx
var Root = React.createClass({
               render: function () {
                       return (
                          <h1>Hello, world!</h1>
                       );
               }
           });

ReactDOM.render(<Root />, document.getElementById('root'));

As the tutorial page said, BabelJS required if you want to use ES6 features such as arrow functions & concise methods, or use bundling mechanism (BabelBundle instead of plain ScriptBundle) to load JSX file.

Related issue:

ReactJS.NET MVC tutorial doesn't work?


问:
PHP get value between script tag
how to get value between the script tag using php scrapping.</p>

```<code>$homepage = file_get_contents('http://www.example.com/');

//$homepage
<script type="application/ld+json">
  //FETCH ME
/script>
</code>```

答:
This seems like the answer you need here, Get content between two strings PHP

The second answer seems easiest:

```<code>$out = file_get_contents('http://www.example.com/');
$start = "<script ...>"; // replace ... with exact other text you are maching
$end = "</script>";
$startsAt = strpos($out, $start) + strlen($start);
$endsAt = strpos($out, $end, $startsAt);
$result = substr($out, $startsAt, $endsAt - $startsAt);
</code>```

with $result being the as it says result of the content between $start and $end

For multiple instances, just delete the first occurance from $out and repeat:

```<code>$out = str_replace($start.$result.$end,"",$out);
</code>```

The first occurance is removed, so you can retreive the second occurance. But sure, there may be a more simpler way to get all occurances, not just this.

```<code>$startsAt = strpos($out, $start) + strlen($start);
$endsAt = strpos($out, $end, $startsAt);
$result = substr($out, $startsAt, $endsAt - $startsAt);
</code>```

Title: PHP get value between script tag

Body:
how to get value between the script tag using php scrapping.

$homepage = file_get_contents('http://www.example.com/');

//$homepage

Body:
This seems like the answer you need here, Get content between two strings PHP

The second answer seems easiest:

$out = file_get_contents('http://www.example.com/');
$start = "<script ...>"; // replace ... with exact other text you are maching
$end = "</script>";
$startsAt = strpos($out, $start) + strlen($start);
$endsAt = strpos($out, $end, $startsAt);
$result = substr($out, $startsAt, $endsAt - $startsAt);

with $result being the as it says result of the content between $start and $end

For multiple instances, just delete the first occurance from $out and repeat:

$out = str_replace($start.$result.$end,"",$out);

The first occurance is removed, so you can retreive the second occurance. But sure, there may be a more simpler way to get all occurances, not just this.

$startsAt = strpos($out, $start) + strlen($start);
$endsAt = strpos($out, $end, $startsAt);
$result = substr($out, $startsAt, $endsAt - $startsAt);


问:
How do I run an external javascript function in a web page?
I can run Javascript in-page, thus:

Javascript.html:

```<code><html>
    <body>
        Hello <span id="mySpan"> World! </span>
    </body>
    <script>
        function worldInSpanish() {
            return "Mundo!";
        }
        document.getElementById('mySpan').innerHTML = worldInSpanish();
    </script>
</html>
</code>```

Hello Mundo!

But when I try to run it from an external file, it doesn't work.

javascript.js:

```<code>function worldInSpanish() {
    return "Mundo!";
}
</code>```

External_javascript.html:

```<code><html>
    <body>
        Hello <span id="mySpan"> World! </span>
    </body>
    <script src="javascript.js">
        document.getElementById('mySpan').innerHTML = worldInSpanish();
    </script>
</html>
</code>```

Doesn't change the text:

Hello World!

What am I doing wrong? I'm guessing that I need to do something more to "import" the function into the HTML page or "export" it from the Javascript file.

答:
You need to use separate
        <script>
            document.getElementById('mySpan').innerHTML = worldInSpanish();
        </script>

```

Body:
I can run Javascript in-page, thus:

Javascript.html:

        Hello  World!

Hello Mundo!

But when I try to run it from an external file, it doesn't work.

javascript.js:

function worldInSpanish() {
    return "Mundo!";
}

External_javascript.html:

        Hello  World!

Doesn't change the text:

Hello World!

What am I doing wrong? I'm guessing that I need to do something more to "import" the function into the HTML page or "export" it from the Javascript file.

Body:
You need to use separate <script> tags for your external file and inline JavaScript.

And as @ShammelLee said, within your <head> or <body> tag.

<html>
    <body>
        Hello <span id="mySpan"> World! </span>
        <script src="javascript.js"></script>
        <script>
            document.getElementById('mySpan').innerHTML = worldInSpanish();
        </script>
    </body>
</html>


问:
ORA-03113: end-of-file on communication channel after ~ 2 hours and 10 mins
I have a sql script with a procedure. I run it using
sqlplus -s @script.sql logfile.log myparam1 myparam2

But after ~ 2 hour and 10 mins, my script ends with

```<code>ERROR:
ORA-03114: not connected to ORACLE

DECLARE
*
ERROR at line 1:
ORA-03113: end-of-file on communication channel
Process ID: 12345
Session ID: 33 Serial number: 54321
</code>```

I have following tcp settings

```<code>-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_time (which is two hours)
7200
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_intvl
75
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_probes
9
</code>```

When the script was running, I checked that TCP connection was established at my end , but on the database side (database server machine) there was no such connection.

My theory is that somehow database server is dropping the connection. And when my system sends first keepalive probe after 2 hours (7200 seconds), it finds that connection is no more active and closes the connection and script returns.

I am unable to understand why would a database system drop a connection?
Are there any settings at database end to increase verbosity? Or could this be related to some firewall settings? Also, in 2 hours and 10 mins, we can guess that 2 hours portion is coming from tcp_keepalive_time, what would be 10 mins portion. Any database side retries?

EDIT: DBA and I looked at the issue, I see the TCP connection as ESTABLISHED at my end and he didn't see any connection coming from my side.

答:
First,you should check your alert.log,to find any error during period of
this time.

Then,two way can make your active session disconnect .

(1)SQLNET.EXPIRE_TIME < 120

(2)the init parameter resource_limit is true,and your profile's(dba_users + dba_profiles ) idle_time < 120

Body:
I have a sql script with a procedure. I run it using
sqlplus -s @script.sql logfile.log myparam1 myparam2

But after ~ 2 hour and 10 mins, my script ends with

ERROR:
ORA-03114: not connected to ORACLE

DECLARE
*
ERROR at line 1:
ORA-03113: end-of-file on communication channel
Process ID: 12345
Session ID: 33 Serial number: 54321

I have following tcp settings

-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_time (which is two hours)
7200
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_intvl
75
-bash-4.1$ cat /proc/sys/net/ipv4/tcp_keepalive_probes
9

When the script was running, I checked that TCP connection was established at my end , but on the database side (database server machine) there was no such connection.

My theory is that somehow database server is dropping the connection. And when my system sends first keepalive probe after 2 hours (7200 seconds), it finds that connection is no more active and closes the connection and script returns.

I am unable to understand why would a database system drop a connection?
Are there any settings at database end to increase verbosity? Or could this be related to some firewall settings? Also, in 2 hours and 10 mins, we can guess that 2 hours portion is coming from tcp_keepalive_time, what would be 10 mins portion. Any database side retries?

EDIT: DBA and I looked at the issue, I see the TCP connection as ESTABLISHED at my end and he didn't see any connection coming from my side.


问:
Passing a parameter that could be null to a method
I have the following method call and for some reason the syntax in C# is not working correctly. If the pkg.Library.description is null then set it to a string.."No Folder Selected". Is there another way to do this?</p>

```<code>SendEmail (pkg.libraryfolder.description == null ? "No Folder Selected" :pkg.libraryfolder.description)

public void SendEmail(string folderdescription)
{
////
}
</code>```

答:
```<code>SendEmail(pkg.libraryfolder.description ?? "No Folder Selected")
</code>```

Body:
I have the following method call and for some reason the syntax in C# is not working correctly. If the pkg.Library.description is null then set it to a string.."No Folder Selected". Is there another way to do this?

SendEmail (pkg.libraryfolder.description == null ? "No Folder Selected" :pkg.libraryfolder.description)

public void SendEmail(string folderdescription)
{
////
}


问:
Unable to find typings.d.ts and declare modules in angular 2 typescript app
I am new to Typescript and Angular 2. I need to install an npm dependency and use it in my angular 2 app.

The dependency is https://www.npmjs.com/package/ng2-stomp-service

I have installed the necessary packages, but I need to add the following to my typings.d.ts file

```<code>declare module 'stompjs';
declare module 'sockjs-client';
</code>```

I am unable to find the typings.d.ts file in my project.

I have tried the following so far,

```<code>npm install typings --global
npm install @types/stompjs
npm isntall @types/sockjs-client
typings install dt~stompjs --save
typings install dt~sockjs-client --save
</code>```

I have typings.json file with contents,

```<code>{
  "dependencies": {
    "sockjs-client": "registry:dt/sockjs-client#1.0.3+20160727010356",
    "stompjs": "registry:dt/stompjs#2.3.0+20161111105645"
  }
}
</code>```

When I run my angular 2 app with npm start it throws error as follows

```<code>ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (27,2): Member 'config' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (36,2): Member 'queuePromises' implicitly has an 'any[]' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (83,32): Parameter 'str' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (132,53): Parameter 'response' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (27,2): Member 'config' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (36,2): Member 'queuePromises' implicitly has an 'any[]' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (83,32): Parameter 'str' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (132,53): Parameter 'response' implicitly has an 'any' type.
</code>```

I am not sure what is causing the issue, I am guessing it is because I have not declared the modules in typings.d.ts

Please advise. Thank you.

答:
It seems like your Typescript compiler tries to compile files from node_modules directory.

Please make sure you have this excluding rule in your tsconfig.json file:

```<code>{
  "compilerOptions": {},
  "exclude": [
    "node_modules"
  ]
}
</code>```

Btw. you need just one of @types and typings. The second one is deprecated, all you need is proper @types packages included in your dev dependencies. Hope it helps!

EDIT: I think there shouldn't be any Typescript files in npm package, so I've created a topic with fix on this repository's github: https://github.com/devsullo/ng2-STOMP-Over-WebSocket/issues/5

Body:
I am new to Typescript and Angular 2. I need to install an npm dependency and use it in my angular 2 app.

The dependency is https://www.npmjs.com/package/ng2-stomp-service

I have installed the necessary packages, but I need to add the following to my typings.d.ts file

declare module 'stompjs';
declare module 'sockjs-client';

I am unable to find the typings.d.ts file in my project.

I have tried the following so far,

npm install typings --global
npm install @types/stompjs
npm isntall @types/sockjs-client
typings install dt~stompjs --save
typings install dt~sockjs-client --save

I have typings.json file with contents,

{
  "dependencies": {
    "sockjs-client": "registry:dt/sockjs-client#1.0.3+20160727010356",
    "stompjs": "registry:dt/stompjs#2.3.0+20161111105645"
  }
}

When I run my angular 2 app with npm start it throws error as follows

ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (27,2): Member 'config' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (36,2): Member 'queuePromises' implicitly has an 'any[]' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (83,32): Parameter 'str' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (132,53): Parameter 'response' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (27,2): Member 'config' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (36,2): Member 'queuePromises' implicitly has an 'any[]' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (83,32): Parameter 'str' implicitly has an 'any' type.
ERROR in D:/Userfiles/subramanians/projects/hand-cricket/node_modules/ng2-stomp-service/dist/stomp.service.ts (132,53): Parameter 'response' implicitly has an 'any' type.

I am not sure what is causing the issue, I am guessing it is because I have not declared the modules in typings.d.ts

Please advise. Thank you.

Body:
It seems like your Typescript compiler tries to compile files from node_modules directory.

Please make sure you have this excluding rule in your tsconfig.json file:

{
  "compilerOptions": {},
  "exclude": [
    "node_modules"
  ]
}

Btw. you need just one of @types and typings. The second one is deprecated, all you need is proper @types packages included in your dev dependencies. Hope it helps!

EDIT: I think there shouldn't be any Typescript files in npm package, so I've created a topic with fix on this repository's github: https://github.com/devsullo/ng2-STOMP-Over-WebSocket/issues/5


问:
Instantiate UITabBarViewController with selectedIndex
I am trying to instantiate a UITabBarViewController with preselected Index. However, the code below instantiates the TabBar with incorrect selectedIndex. What am I doing wrong.? Any help is appreciated. Thanks</p>

```<code>        let storyboard = UIStoryboard(name: "Visits", bundle: nil)
        let visitsController = storyboard.instantiateViewController(withIdentifier: "VisitsTabBarViewController") as! VisitsTabBarViewController

        visitsController.selectedIndex = 1
</code>```

答:
I think I got it. The solution is to set a property inside the TabBarViewControllere and not use the selectedIndex when I am instantiating the TabBarViewContoller like shown

```<code>class VisitsTabBarViewController: UITabBarController, UITabBarControllerDelegate {
var index = 0
....

func viewDidLoad() {
      selectedIndex = index
}

let storyboard = UIStoryboard(name: "Visits", bundle: nil)
    let visitsController
storyboard.instantiateViewController(withIdentifier: "VisitsTabBarViewController") as! VisitsTabBarViewController

visitsController.index = 1
</code>```

Then when I instantiate the TabBarViewController, I set this index property as shown above. That seemed to fix it.

Body:
I am trying to instantiate a UITabBarViewController with preselected Index. However, the code below instantiates the TabBar with incorrect selectedIndex. What am I doing wrong.? Any help is appreciated. Thanks

        let storyboard = UIStoryboard(name: "Visits", bundle: nil)
        let visitsController = storyboard.instantiateViewController(withIdentifier: "VisitsTabBarViewController") as! VisitsTabBarViewController

        visitsController.selectedIndex = 1

Body:
I think I got it. The solution is to set a property inside the TabBarViewControllere and not use the selectedIndex when I am instantiating the TabBarViewContoller like shown

class VisitsTabBarViewController: UITabBarController, UITabBarControllerDelegate {
var index = 0
....

func viewDidLoad() {
      selectedIndex = index
}

let storyboard = UIStoryboard(name: "Visits", bundle: nil)
    let visitsController
storyboard.instantiateViewController(withIdentifier: "VisitsTabBarViewController") as! VisitsTabBarViewController

visitsController.index = 1

Then when I instantiate the TabBarViewController, I set this index property as shown above. That seemed to fix it.


问:
What is the difference between a static and const variable?
Can someone explain the difference between a static and const variable?

答: Simple and short answer is memory is allocated for static and const only once. But in const that is for only one value where as in static values may change but the memory area remains the same until the end of the program.</p>

ContentLicense: CC BY-SA 2.5


问:
Reformat a text file to csv using bash script
I have a file (exOut.txt) consisting of several thousand lines of text in the following format:

```<code>[CV] solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482
[CV] solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482
[CV] solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482
[CV] solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405
[CV] solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405
[CV] solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405
[CV]  solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405, score=0.497312, total=11.0min
[CV]  solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405, score=0.499232, total=11.0min
[Parallel(n_jobs=-2)]: Done   2 out of   6 | elapsed: 11.0min remaining: 22.0min
[CV]  solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405, score=0.499762, total=11.1min
[Parallel(n_jobs=-2)]: Done   3 out of   6 | elapsed: 11.1min remaining: 11.1min
[CV]  solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482, score=0.449309, total=19.6min
[Parallel(n_jobs=-2)]: Done   4 out of   6 | elapsed: 19.6min remaining: 9.8min
[CV]  solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482, score=0.449831, total=19.7min
[CV]  solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482, score=0.451609, total=19.7min
[Parallel(n_jobs=-2)]: Done   6 out of   6 | elapsed: 19.7min remaining:    0.0s
[Parallel(n_jobs=-2)]: Done   6 out of   6 | elapsed: 19.7min finished
...
</code>```

I am trying to write a shell script which will take this file and reformat it to create a new file in csv format, only recording the lines with a "score" attribute. This should look something like:

```<code>solver,penalty,multi_class,max_iter,C,score
sag,l2,multinomial,187.638,0.312,0.497
sag,l2,multinomial,187.638,0.312,0.499
sag,l2,multinomial,187.638,0.312,0.500
newton-cg,l2,ovr,187.638,0.779,0.449
newton-cg,l2,ovr,187.638,0.779,0.450
newton-cg,l2,ovr,187.638,0.779,0.450
</code>```

Where all values are rounded to the nearest 1000th place, when possible.

And ultimately I would like to take this csv and make a condensed version by identifying records with all fields equal except "score", and replacing those with one record with an average score given those parameters. For example:

```<code>solver,penalty,multi_class,max_iter,C,avg_score
sag,l2,multinomial,187.638,0.312,0.499
newton-cg,l2,ovr,187.638,0.779,0.450
</code>```

Any help is appreciated! I am not a pro at regular expressions which is mainly why I ask.

EDIT 1 Thanks for the feedback, here's some more info:

Thus far I've tried various scripts using grep, awk and sed including, grep '=.*,' exOut.txt which only recognizes one large occurrence of the pattern rather than multiple fields, and sed 's/^[^\=]*\=//g' exOutput.txt > firstCSV.csv which only cleans up the first part of each line.

答:
1.The question you can reference the parseRawDataFile function.

2.the question you can reference thr parseCsvDataFile  function.

3.In the code had some hard code, please notice.

```<code>import codecs
datausage = r"e:\temp\111.txt"
storagePath = r"e:\temp\222.csv"
storagePath_New = r"e:\temp\222_New.csv"
strStr = "score"

def parseRawDataFile(path):
    sumResult = "solver,penalty,multi_class,max_iter,C,score\r\n"
    # [CV]  solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405, score=0.497312, total=11.0min

    with open(path) as f:

        lines = f.readlines()
        for line in lines:
            if strStr in line:

                tempList = line.replace(",", "=").split("=")
                # print(tempList)
                sumResult += "%s,%s,%s,%.03f,%.03f,%.03f\r\n" % (tempList[1], tempList[3], tempList[5], float(tempList[7]), float(tempList[9]), float(tempList[11]))

    # print(sumResult)
    return sumResult

def parseCsvDataFile(path):
    sumResult = "solver,penalty,multi_class,max_iter,C,score\r\n"
    # sag,l2,multinomial,187.638,0.312,0.497

    nameList = []
    with open(path) as f:
        lines = f.readlines()
        temptSum = 0.0
        tempNum = 0
        for line in lines:
            if "solver" in line:
                continue
            tempList = line.split(",")
            if tempList[0] not in nameList:
                if temptSum != 0:
                    sumResult += "%.03f\r\n" % (temptSum/tempNum)
                sumResult += "%s,%s,%s,%.03f,%.03f," % (tempList[0], tempList[1], tempList[2], float(tempList[3]), float(tempList[4]))

                tempNum = 0
                temptSum = 0.0
                nameList.append(tempList[0])
            if tempList[0] in nameList:
                tempNum += 1
                temptSum += float(tempList[-1])

        sumResult += "%.03f\r\n" % (temptSum / tempNum)
    print(sumResult)
    return sumResult

def writeLog(f, d):
    try:
        f = codecs.open(f, 'w', 'utf-8')
        f.write(d)
        f.close()
    except:
        print("file is not exist.")

result = parseRawDataFile(datausage)
writeLog(storagePath, result)
result = parseCsvDataFile(storagePath)
writeLog(storagePath_New, result)
</code>```

Body:
I have a file (exOut.txt) consisting of several thousand lines of text in the following format:

[CV] solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482
[CV] solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482
[CV] solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482
[CV] solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405
[CV] solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405
[CV] solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405
[CV]  solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405, score=0.497312, total=11.0min
[CV]  solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405, score=0.499232, total=11.0min
[Parallel(n_jobs=-2)]: Done   2 out of   6 | elapsed: 11.0min remaining: 22.0min
[CV]  solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405, score=0.499762, total=11.1min
[Parallel(n_jobs=-2)]: Done   3 out of   6 | elapsed: 11.1min remaining: 11.1min
[CV]  solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482, score=0.449309, total=19.6min
[Parallel(n_jobs=-2)]: Done   4 out of   6 | elapsed: 19.6min remaining: 9.8min
[CV]  solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482, score=0.449831, total=19.7min
[CV]  solver=newton-cg, penalty=l2, multi_class=ovr, max_iter=187.637633813, C=0.778324314482, score=0.451609, total=19.7min
[Parallel(n_jobs=-2)]: Done   6 out of   6 | elapsed: 19.7min remaining:    0.0s
[Parallel(n_jobs=-2)]: Done   6 out of   6 | elapsed: 19.7min finished
...

I am trying to write a shell script which will take this file and reformat it to create a new file in csv format, only recording the lines with a "score" attribute. This should look something like:

solver,penalty,multi_class,max_iter,C,score
sag,l2,multinomial,187.638,0.312,0.497
sag,l2,multinomial,187.638,0.312,0.499
sag,l2,multinomial,187.638,0.312,0.500
newton-cg,l2,ovr,187.638,0.779,0.449
newton-cg,l2,ovr,187.638,0.779,0.450
newton-cg,l2,ovr,187.638,0.779,0.450

Where all values are rounded to the nearest 1000th place, when possible.

And ultimately I would like to take this csv and make a condensed version by identifying records with all fields equal except "score", and replacing those with one record with an average score given those parameters. For example:

solver,penalty,multi_class,max_iter,C,avg_score
sag,l2,multinomial,187.638,0.312,0.499
newton-cg,l2,ovr,187.638,0.779,0.450

Any help is appreciated! I am not a pro at regular expressions which is mainly why I ask.

EDIT 1 Thanks for the feedback, here's some more info:

Thus far I've tried various scripts using grep, awk and sed including, grep '=.*,' exOut.txt which only recognizes one large occurrence of the pattern rather than multiple fields, and sed 's/^[^\=]*\=//g' exOutput.txt > firstCSV.csv which only cleans up the first part of each line.

Body:
1.The question you can reference the parseRawDataFile function.

2.the question you can reference thr parseCsvDataFile  function.

3.In the code had some hard code, please notice.

import codecs
datausage = r"e:\temp\111.txt"
storagePath = r"e:\temp\222.csv"
storagePath_New = r"e:\temp\222_New.csv"
strStr = "score"

def parseRawDataFile(path):
    sumResult = "solver,penalty,multi_class,max_iter,C,score\r\n"
    # [CV]  solver=sag, penalty=l2, multi_class=multinomial, max_iter=187.637633813, C=0.31181629405, score=0.497312, total=11.0min

    with open(path) as f:

        lines = f.readlines()
        for line in lines:
            if strStr in line:

                tempList = line.replace(",", "=").split("=")
                # print(tempList)
                sumResult += "%s,%s,%s,%.03f,%.03f,%.03f\r\n" % (tempList[1], tempList[3], tempList[5], float(tempList[7]), float(tempList[9]), float(tempList[11]))

    # print(sumResult)
    return sumResult

def parseCsvDataFile(path):
    sumResult = "solver,penalty,multi_class,max_iter,C,score\r\n"
    # sag,l2,multinomial,187.638,0.312,0.497

    nameList = []
    with open(path) as f:
        lines = f.readlines()
        temptSum = 0.0
        tempNum = 0
        for line in lines:
            if "solver" in line:
                continue
            tempList = line.split(",")
            if tempList[0] not in nameList:
                if temptSum != 0:
                    sumResult += "%.03f\r\n" % (temptSum/tempNum)
                sumResult += "%s,%s,%s,%.03f,%.03f," % (tempList[0], tempList[1], tempList[2], float(tempList[3]), float(tempList[4]))

                tempNum = 0
                temptSum = 0.0
                nameList.append(tempList[0])
            if tempList[0] in nameList:
                tempNum += 1
                temptSum += float(tempList[-1])

        sumResult += "%.03f\r\n" % (temptSum / tempNum)
    print(sumResult)
    return sumResult

def writeLog(f, d):
    try:
        f = codecs.open(f, 'w', 'utf-8')
        f.write(d)
        f.close()
    except:
        print("file is not exist.")

result = parseRawDataFile(datausage)
writeLog(storagePath, result)
result = parseCsvDataFile(storagePath)
writeLog(storagePath_New, result)


问:
Search query with filtering in oracle database
```<code>SELECT * FROM EMPLOYEES
  WHERE (1 = 1 OR FIRST_NAME = 'renz')
    AND (1 = 1 OR LAST_NAME LIKE '%t%')
    AND (1 = 1 OR EMAIL = 'ASD')
    AND
    (CASE
      WHEN ('06/20/2016'!='' AND '01/23/2017'!='')
        THEN HIRE_DATE BETWEEN TO_DATE('06/20/2016','YYYYMMDD') AND TO_DATE('01/23/2017','YYYYMMDD')
      WHEN ('06/20/2016'!='' AND '01/23/2017'=='')
        THEN HIRE_DATE >=TO_DATE('06/20/2016','YYYYMMDD')
      WHEN ('06/20/2016'=='' AND '01/23/2017'!='')
        THEN HIRE_DATE <=TO_DATE('01/23/2017','YYYYMMDD')
    END)
</code>```

Im trying to create a search query that will search : firstname exactly match, lastname partial match, email exact match, data between from date and to date
 if both from and to are present it will return data between those date
 if from is the only present it will return data with date greater than from
 if to is the only present it will return data with date less than to date
How can i achieve this? The data for my filtering is from my jsp page pass to my DAO class

答:
Try something like this:</p>

```<code>SELECT * FROM EMPLOYEES
  WHERE (1 = 1 OR FIRST_NAME = 'renz')
    AND (1 = 1 OR LAST_NAME LIKE '%t%')
    AND (1 = 1 OR EMAIL = 'ASD')
    AND HIRE_DATE BETWEEN NVL(TO_DATE(:FROM_DT, 'YYYYMMDD'), HIRE_DATE)
                      AND NVL(TO_DATE(:TO_DT,'YYYYMMDD'), HIRE_DATE)
;
</code>```

Body:
SELECT * FROM EMPLOYEES
  WHERE (1 = 1 OR FIRST_NAME = 'renz')
    AND (1 = 1 OR LAST_NAME LIKE '%t%')
    AND (1 = 1 OR EMAIL = 'ASD')
    AND
    (CASE
      WHEN ('06/20/2016'!='' AND '01/23/2017'!='')
        THEN HIRE_DATE BETWEEN TO_DATE('06/20/2016','YYYYMMDD') AND TO_DATE('01/23/2017','YYYYMMDD')
      WHEN ('06/20/2016'!='' AND '01/23/2017'=='')
        THEN HIRE_DATE >=TO_DATE('06/20/2016','YYYYMMDD')
      WHEN ('06/20/2016'=='' AND '01/23/2017'!='')
        THEN HIRE_DATE <=TO_DATE('01/23/2017','YYYYMMDD')
    END)

Im trying to create a search query that will search : firstname exactly match, lastname partial match, email exact match, data between from date and to date
 if both from and to are present it will return data between those date
 if from is the only present it will return data with date greater than from
 if to is the only present it will return data with date less than to date
How can i achieve this? The data for my filtering is from my jsp page pass to my DAO class

Body:
Try something like this:

SELECT * FROM EMPLOYEES
  WHERE (1 = 1 OR FIRST_NAME = 'renz')
    AND (1 = 1 OR LAST_NAME LIKE '%t%')
    AND (1 = 1 OR EMAIL = 'ASD')
    AND HIRE_DATE BETWEEN NVL(TO_DATE(:FROM_DT, 'YYYYMMDD'), HIRE_DATE)
                      AND NVL(TO_DATE(:TO_DT,'YYYYMMDD'), HIRE_DATE)
;


问:
Phonegap yellow highlight
I have a Samsung Captivate. Whenever I click on a button or image a yellow highlight shows up around it. I was wondering is this the phone itself? Or is it something I can turn off via PhoneGap.

Makes the app ugly ;)

Thanks

答:
If you view the page in the browser on the device do you get this same effect?

Do you get this when viewing websites on the device?

If yes to the above then you may be able to control this with CSS.

Title: Phonegap yellow highlight


问:
Need help in JavaScript/JQuery
need some help.. i want the bin to hide on load and i have a draggable div, so when i drag the div the bin should show and when i leave the div the bin should hide again?</p>

```<code><html>
<head>
  <style>
  .box{
    border: 1px solid black;
  }
  </style>

  <script>
  window.onload = function() { document.getElementById('myDIV').style.display = 'none'; };
  function showImg(){
    var x = document.getElementById('myDIV');
    if (x.style.display === 'none') { x.style.display = 'block'; }
    else { x.style.display = 'none'; }
  }
  </script>

</head>

<body>
  <div id="show" onclick="showImg()" class="box">
    when this div is select and drag the bin should be shown
  </div>

  <div id="myDIV">
    <img src="img/upload.png"/>
  </div>

</body>
</html>
</code>```

答:
Using jQuery UI, you can catch drag events easily in this way:</p>

```<code>  $("#myDIV").draggable({
     start: function() {

     },
     drag: function() {

     },
     stop: function() {

     }
  });
</code>```

Title: Need help in JavaScript/JQuery

Body:
need some help.. i want the bin to hide on load and i have a draggable div, so when i drag the div the bin should show and when i leave the div the bin should hide again?

    when this div is select and drag the bin should be shown

Body:
Using jQuery UI, you can catch drag events easily in this way:

  $("#myDIV").draggable({
     start: function() {

     },
     drag: function() {

     },
     stop: function() {

     }
  });


问:
removing .php but now the folder structure doesn't work and trailing slash
I was to remove .php extension by using

```<code>RewriteEngine On
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</code>```

but this introduced a problem which is i can't access to folder directories and their internal files and server is not even accepting trailing slash at the end.

so lets i visit this page

```<code>www.example.com/family
</code>```

url will load fine

if i visit this page with / at the end

```<code>www.example.com/family/
</code>```

note i have trailing slash / at the end, it won't work

now if i have a directory or folder name family

```<code>www.example/family
</code>```

which is directory instead of my page then page will not work nor the directory or folder will be accessible.

答:
It seems like i was able to do it by using this code:

```<code>RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
</code>```

i am pasting here, if someone else searching for the same issue.

Body:
I was to remove .php extension by using

RewriteEngine On
RewriteRule ^([^\.]+)$ $1.php [NC,L]

but this introduced a problem which is i can't access to folder directories and their internal files and server is not even accepting trailing slash at the end.

so lets i visit this page

www.example.com/family

url will load fine

if i visit this page with / at the end

www.example.com/family/

note i have trailing slash / at the end, it won't work

now if i have a directory or folder name family

www.example/family

which is directory instead of my page then page will not work nor the directory or folder will be accessible.

Body:
It seems like i was able to do it by using this code:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

i am pasting here, if someone else searching for the same issue.


问:
I want to play sounds after each other but make them wait until the first one is done. How do I do it?
I am currently doing a simple morse code translator and I want my code to play a long beep on '-' and a short beep on '.', and of course this is to be done after one another. But my program is currently playing it all at once. What am I doing wrong?

I have tried adding an onCompletionListener but Netbeans 8.1 gives an error and cant resolve the problem.

```<code>    //Play the morse code
public void playButton(ActionEvent event){
    String morse = mcTextField.getText();
    char[] charArray = morse.toCharArray();
    for(int x = 0; x<charArray.length; x++){

        if(charArray[x] == '.'){
            playBeep(shortBeep);
        }
        else if(charArray[x] == '-'){
            playBeep(longBeep);
        }
        else{
            sleep(500);
        }
        sleep(1000);
    }
    }

private void playBeep(String name){
    String musicFile = name;

    Media sound = new Media(new File(musicFile).toURI().toString());
    MediaPlayer mediaPlayer = new MediaPlayer(sound);
    mediaPlayer.play();

    sleep(1000);

}

 private void sleep(int duration){
    try{
        Thread.sleep(duration);
    }catch(Exception e){
        System.out.println("Did not work."+e);
    }
}
</code>```

答:
This make use of the Java Sound API, but the basic idea should be feasible for most audio libraries, so long as the provide "end of play back" notification.

All this does is, places the sequence you want to play into a queue, it plays the next tone, wait till it completes and plays the next, until there are no more tones in the queue.

Because AudioClip plays in it's own thread, this uses another Thread to allow the example to "wait for" the sequence to play out fully.  If you're doing this from a UI framework, then you could get away without the additional overhead.

```<code>import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Test {

    public static void main(String[] args) throws InterruptedException {
        try {
            new Test();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
            ex.printStackTrace();
        }
    }

    public Test() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        Sound longBeep = new Sound(new File(...));
        Sound shortBeep = new Sound(new File(...));

        List<Sound> message = new ArrayList<Sound>(9);
        message.add(shortBeep);
        message.add(shortBeep);
        message.add(shortBeep);
        message.add(longBeep);
        message.add(longBeep);
        message.add(longBeep);
        message.add(shortBeep);
        message.add(shortBeep);
        message.add(shortBeep);

        play(message);
    }

    public void play(List<Sound> message) {
        try {
            List<Sound> queue = new ArrayList<>(message);
            Transmit transmit = new Transmit(message);
            Thread thread = new Thread(transmit);
            thread.start();
            transmit.waitFor();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    public class Transmit implements Runnable {

        private List<Sound> queue;
        private ReentrantLock lock;
        private Condition playCondition;

        public Transmit(List<Sound> message) {
            this.queue = new ArrayList<>(message);

            lock = new ReentrantLock();
            playCondition = lock.newCondition();
        }

        @Override
        public void run() {
            playNext();
        }

        public void waitFor() throws InterruptedException {
            lock.lock();
            if (!queue.isEmpty()) {
                try {
                    playCondition.await();
                } finally {
                    lock.unlock();
                }
            } else {
                lock.unlock();
            }
        }

        protected void playNext() {
            if (queue.size() > 0) {
                lock.lock();
                try {
                    System.out.println("Play Next");
                    Sound sound = queue.remove(0);
                    sound.addLineListener(new LineListener() {
                        @Override
                        public void update(LineEvent event) {
                            if (event.getType().equals(LineEvent.Type.STOP)) {
                                sound.removeLineListener(this);
                                System.out.println("Audio Completed");
                                playNext();
                            }
                        }
                    });
                    sound.play();
                } finally {
                    lock.unlock();
                }
            } else {
                lock.lock();
                try {
                    playCondition.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        }

    }

    public class Sound {

        private Clip audio;

        public Sound(AudioInputStream audioInputStream) throws LineUnavailableException, IOException {
            audio = AudioSystem.getClip();
            audio.open(audioInputStream);
        }

        public Sound(File file) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            this(AudioSystem.getAudioInputStream(file));
        }

        public Sound(URL url) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            this(AudioSystem.getAudioInputStream(url));
        }

        public Sound(InputStream stream) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            this(AudioSystem.getAudioInputStream(stream));
        }

        public void close() {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.close();
        }

        public void play() {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.setFramePosition(0);
            audio.start();
        }

        public void addLineListener(LineListener listener) {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.addLineListener(listener);
        }

        public void removeLineListener(LineListener listener) {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.removeLineListener(listener);
        }
    }

}
</code>```

If you want to know when the sequence completes, without going to trouble of using the waitFor method, you wouldn't be a difficult thing to add an observer into for the Transmit class which generate a "completed sequence" event, but I'll leave that up to you to implement

Body:
I am currently doing a simple morse code translator and I want my code to play a long beep on '-' and a short beep on '.', and of course this is to be done after one another. But my program is currently playing it all at once. What am I doing wrong?

I have tried adding an onCompletionListener but Netbeans 8.1 gives an error and cant resolve the problem.

    //Play the morse code
public void playButton(ActionEvent event){
    String morse = mcTextField.getText();
    char[] charArray = morse.toCharArray();
    for(int x = 0; x<charArray.length; x++){

        if(charArray[x] == '.'){
            playBeep(shortBeep);
        }
        else if(charArray[x] == '-'){
            playBeep(longBeep);
        }
        else{
            sleep(500);
        }
        sleep(1000);
    }
    }

private void playBeep(String name){
    String musicFile = name;

    Media sound = new Media(new File(musicFile).toURI().toString());
    MediaPlayer mediaPlayer = new MediaPlayer(sound);
    mediaPlayer.play();

    sleep(1000);

}

 private void sleep(int duration){
    try{
        Thread.sleep(duration);
    }catch(Exception e){
        System.out.println("Did not work."+e);
    }
}

Body:
This make use of the Java Sound API, but the basic idea should be feasible for most audio libraries, so long as the provide "end of play back" notification.

All this does is, places the sequence you want to play into a queue, it plays the next tone, wait till it completes and plays the next, until there are no more tones in the queue.

Because AudioClip plays in it's own thread, this uses another Thread to allow the example to "wait for" the sequence to play out fully.  If you're doing this from a UI framework, then you could get away without the additional overhead.

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Test {

    public static void main(String[] args) throws InterruptedException {
        try {
            new Test();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
            ex.printStackTrace();
        }
    }

    public Test() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        Sound longBeep = new Sound(new File(...));
        Sound shortBeep = new Sound(new File(...));

        List<Sound> message = new ArrayList<Sound>(9);
        message.add(shortBeep);
        message.add(shortBeep);
        message.add(shortBeep);
        message.add(longBeep);
        message.add(longBeep);
        message.add(longBeep);
        message.add(shortBeep);
        message.add(shortBeep);
        message.add(shortBeep);

        play(message);
    }

    public void play(List<Sound> message) {
        try {
            List<Sound> queue = new ArrayList<>(message);
            Transmit transmit = new Transmit(message);
            Thread thread = new Thread(transmit);
            thread.start();
            transmit.waitFor();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    public class Transmit implements Runnable {

        private List<Sound> queue;
        private ReentrantLock lock;
        private Condition playCondition;

        public Transmit(List<Sound> message) {
            this.queue = new ArrayList<>(message);

            lock = new ReentrantLock();
            playCondition = lock.newCondition();
        }

        @Override
        public void run() {
            playNext();
        }

        public void waitFor() throws InterruptedException {
            lock.lock();
            if (!queue.isEmpty()) {
                try {
                    playCondition.await();
                } finally {
                    lock.unlock();
                }
            } else {
                lock.unlock();
            }
        }

        protected void playNext() {
            if (queue.size() > 0) {
                lock.lock();
                try {
                    System.out.println("Play Next");
                    Sound sound = queue.remove(0);
                    sound.addLineListener(new LineListener() {
                        @Override
                        public void update(LineEvent event) {
                            if (event.getType().equals(LineEvent.Type.STOP)) {
                                sound.removeLineListener(this);
                                System.out.println("Audio Completed");
                                playNext();
                            }
                        }
                    });
                    sound.play();
                } finally {
                    lock.unlock();
                }
            } else {
                lock.lock();
                try {
                    playCondition.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        }

    }

    public class Sound {

        private Clip audio;

        public Sound(AudioInputStream audioInputStream) throws LineUnavailableException, IOException {
            audio = AudioSystem.getClip();
            audio.open(audioInputStream);
        }

        public Sound(File file) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            this(AudioSystem.getAudioInputStream(file));
        }

        public Sound(URL url) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            this(AudioSystem.getAudioInputStream(url));
        }

        public Sound(InputStream stream) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            this(AudioSystem.getAudioInputStream(stream));
        }

        public void close() {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.close();
        }

        public void play() {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.setFramePosition(0);
            audio.start();
        }

        public void addLineListener(LineListener listener) {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.addLineListener(listener);
        }

        public void removeLineListener(LineListener listener) {
            Objects.requireNonNull(audio, "Audio Clip has not been initalised");
            audio.removeLineListener(listener);
        }
    }

}

If you want to know when the sequence completes, without going to trouble of using the waitFor method, you wouldn't be a difficult thing to add an observer into for the Transmit class which generate a "completed sequence" event, but I'll leave that up to you to implement


问:
What measurement do you use in your development process to determine *Doneness* of your software?
I just finished listening to a very eye-opening podcast on Hanselminutes about the definition of "Done". So my question to everyone is "When do you consider a piece of software to be "Done"? Is it when it's fully unit tested? Is it when it's completely documented? What measurement do you use in your development process to determine Doneness of your software?

答:
When the check clears?

Seriously, every time you write a piece of software, you should have defined what "done" means.  First.  If you have a customer, then there should be a contract -- specific, measurable, agreed, and testable -- that defines done.

If you don't know where you're going, how will you know when you get there?

OwnerDisplayName: Micah

OwnerDisplayName: Charlie Martin


问:
Regex: how to stop match on certain words that cannot exists
The title is so confusing, I admit it - if you want to change it you are welcome.

I'm working on PHP and preg_match function.

The problem is this string (just an example)

```<code>ON DELETE SET NULL ON UPDATE CASCADE
</code>```

ON DELETE CASCADE ON UPDATE CASCADE (another example..)

i need to find ON DELETE and ON UPDATE values, but they can't be there both.

So sometimes i have this:

```<code>ON DELETE something
</code>```

and other times:

```<code>ON UPDATE something
</code>```

and other times both.

So, this regex doesn't cover all possibilities:

```<code>/ON DELETE (.+) ON UPDATE (.+)/
</code>```

If i put

/ON DELETE (.+)( ON UPDATE (.*))?/ -- to cover the case in which there isn't ON UPDATE

if ON UPDATE is present, first group results in "SET NULL ON UPDATE CASCADE".

How can i do that?

答:
Use lookaround if you want to avoid matching too much:

Negative lookahead :

```<code>/ON DELETE ((?:(?! ON UPDATE).)+)( ON UPDATE (.*))?/
</code>```

To capture disregarding the order:

```<code>/(?:ON DELETE ((?:(?! ON UPDATE).)+)|ON UPDATE ((?:(?! ON DELETE).)+))/
</code>```

But what exactly do you want? Remove both if they exist?

Body:
The title is so confusing, I admit it - if you want to change it you are welcome.

I'm working on PHP and preg_match function.

The problem is this string (just an example)

ON DELETE SET NULL ON UPDATE CASCADE

ON DELETE CASCADE ON UPDATE CASCADE (another example..)

i need to find ON DELETE and ON UPDATE values, but they can't be there both.

So sometimes i have this:

ON DELETE something

and other times:

ON UPDATE something

and other times both.

So, this regex doesn't cover all possibilities:

/ON DELETE (.+) ON UPDATE (.+)/

If i put

/ON DELETE (.+)( ON UPDATE (.*))?/ -- to cover the case in which there isn't ON UPDATE

if ON UPDATE is present, first group results in "SET NULL ON UPDATE CASCADE".

How can i do that?

Body:
Use lookaround if you want to avoid matching too much:

Negative lookahead :

/ON DELETE ((?:(?! ON UPDATE).)+)( ON UPDATE (.*))?/

To capture disregarding the order:

/(?:ON DELETE ((?:(?! ON UPDATE).)+)|ON UPDATE ((?:(?! ON DELETE).)+))/

But what exactly do you want? Remove both if they exist?


问:
Dynamically compute SVG Path for a full circle with JavaScript
I'm trying to draw the perimeter of a circle depending on the angle inputed by the user. The angle determines the perimeter completion : 360° being the full circle, 180 half of the circle, and so on.

My problem is : given the radius, the angle and the center coordinates of the circle, how can I dynamically compute the path of the perimeter ?

I know it's probably basic math but everything I tried so far didn't work.

Here is my fiddle : https://jsfiddle.net/Hal_9100/L311qq88/
My problem is finding the right formula for the x and y coordinates of the path :

```<code>var x = i * (radius * Math.cos(angle)) + centerX;
var y = i * (radius * Math.sin(angle)) + centerY;
</code>```

Am I going all wrong here ?

Here is an example of what I'm trying to do : please note that only the black perimeter should be drawn : I just used the dotted red lines to give a visual example of how the perimeter should be drawn depending on the value given by the user.

答:
Yes, the problem is your maths.  Here is the correct way to calculate the x,y coordinate pairs (note that the iteration is from zero to the required angle, not from zero to the radius):

```<code>for (var i = 0; i <= angle; i++) {
        var x = (radius * Math.cos((i-90)*Math.PI/180)) + centerX;
        var y = (radius * Math.sin((i-90)*Math.PI/180)) + centerY;
</code>```

Your fiddle works fine if you substitute these three lines.

Body:
I'm trying to draw the perimeter of a circle depending on the angle inputed by the user. The angle determines the perimeter completion : 360° being the full circle, 180 half of the circle, and so on.

My problem is : given the radius, the angle and the center coordinates of the circle, how can I dynamically compute the path of the perimeter ?

I know it's probably basic math but everything I tried so far didn't work.

Here is my fiddle : https://jsfiddle.net/Hal_9100/L311qq88/
My problem is finding the right formula for the x and y coordinates of the path :

var x = i * (radius * Math.cos(angle)) + centerX;
var y = i * (radius * Math.sin(angle)) + centerY;

Am I going all wrong here ?

Here is an example of what I'm trying to do : please note that only the black perimeter should be drawn : I just used the dotted red lines to give a visual example of how the perimeter should be drawn depending on the value given by the user.

Body:
Yes, the problem is your maths.  Here is the correct way to calculate the x,y coordinate pairs (note that the iteration is from zero to the required angle, not from zero to the radius):

for (var i = 0; i <= angle; i++) {
        var x = (radius * Math.cos((i-90)*Math.PI/180)) + centerX;
        var y = (radius * Math.sin((i-90)*Math.PI/180)) + centerY;

Your fiddle works fine if you substitute these three lines.


问:
how to join two tables in two different mysql server machine? ( The two mysql server ip is different)
For example， One mysql server machine A has One table called "tableA" under in a database called databaseA, another mysql server machine B has one table called "tableB" under in a database called databaseB. how to join tableA and tableB? Is there any good solution?

答:
You can write a JOIN tables in two databases hosted in the same MySQL instance by using qualified table names:

```<code>SELECT ...
FROM databaseA.tableA
JOIN databaseB.tableB
  ON <join-condition>
</code>```

But you can't write a query to join across different MySQL instances.

MySQL parses and executes queries within the process of one server instance. If you were to try to reference tables in different instances, which instance would execute the query? Neither one has the ability to access tables in both instances.

You might fake it by using the FEDERATED storage engine, but I don't have confidence in that storage engine.

The general solution is to query the tables in each instance, fetch all the rows from each, and matching the rows using application code.

Body:
You can write a JOIN tables in two databases hosted in the same MySQL instance by using qualified table names:

SELECT ...
FROM databaseA.tableA
JOIN databaseB.tableB
  ON <join-condition>

But you can't write a query to join across different MySQL instances.

MySQL parses and executes queries within the process of one server instance. If you were to try to reference tables in different instances, which instance would execute the query? Neither one has the ability to access tables in both instances.

You might fake it by using the FEDERATED storage engine, but I don't have confidence in that storage engine.

The general solution is to query the tables in each instance, fetch all the rows from each, and matching the rows using application code.