问:
Can you iterate over a list of Thymeleaf fragments?
I have an application with a standard page layout, and many content templates.  Each content template could have one or more content sections that I want to treat as fragments.  I'd like to be able to iterate over each fragment and include it separately after putting in formatting divs.  The idea is that I don't want each content page to have to know how to nest section and div tags to get the page to format correctly. I've tried the following without success:

layout.html:

```<code><html xmlns:th="http://www.thymeleaf.org"
      th:fragment="layout(contentFragments)">
<section class="row-outer-sm"
         th:each="frag,iterStat : ${contentFragments}">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col">
                <div th:if="${iterStat.first}"
                         th:replace="fragments/messages :: messages">
                    Messages go here
                </div>
                <div th:replace="${frag}">
                   Content goes here.
                </div>
            </div>
        </div>
    </div>
</section>
</html>
</code>```

content.html:

```<code><html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      th:replace="fragments/layout :: layout(~{:: div.section-content})">
<div class="section-content">
   Some things for my first section
</div>

<div class="section-content">
    Some things for my second section
</div>
</html>
</code>```

The fragment expression in content.html correctly finds all the divs with the section-content class, but they appear to be passed into layout.html as a single concatenated fragment.  Is there any way to get a list of fragments I can use for the "th:each" tag?

答:
This is not an especially elegant solution, but I think it does what you need. It re-arranges your approach, so it may need some translating to your specific context.

It is a bit brittle because you have to maintain a count of sections (explained below).

The layout.html:

```<code><html xmlns:th="http://www.thymeleaf.org"
      th:fragment="layout">

    <section class="row-outer-sm"
             th:each="i,iterStat : ${#numbers.sequence(1, 3)}"
             th:with="section=${'section-' + i}">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col">

                    <div th:if="${iterStat.first}">
                        Messages go here
                    </div>

                    <div th:replace="~{/content.html :: __${section}__} ">
                        Content goes here.
                    </div>
                </div>
            </div>
        </div>
    </section>

</html>
</code>```

The content.html:

```<code><html lang="en" xmlns:th="http://www.thymeleaf.org">

    <div th:fragment="section-1">
        <div class="section-content">
            Some things for my first section
        </div>
    </div>

    <div th:fragment="section-2">
        <div class="section-content">
            Some things for my second section
        </div>
    </div>

    <div th:fragment="section-3">
        <div class="section-content">
            Some things for my third section
        </div>
    </div>

</html>
</code>```

The layout template builds a dynamically created fragment selector section_n, where n is the iterated value, based on Thymeleaf's sequence generator:

```<code>${#numbers.sequence(1, n)}
</code>```

That is the brittle part - you have to remember to keep the hard-coded value of n in line with the number (and names!) of the section fragments in the content template.

We also use Thymeleaf's preprocesing __${}__ directive to allow the th:replace to operate on a string - the template selector.

In my example, the end result is HTML like this (the format's a bit wonky):

```<code>    <section class="row-outer-sm">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col">

                    <div>
                        Messages go here
                    </div>

                    <div>
        <div class="section-content">
            Some things for my first section
        </div>
    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="row-outer-sm">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col">

                    <div>
        <div class="section-content">
            Some things for my second section
        </div>
    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="row-outer-sm">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col">

                    <div>
        <div class="section-content">
            Some things for my third section
        </div>
    </div>
                </div>
            </div>
        </div>
    </section>
</code>```

Hope that helps, or at least gives you some inspiration.

Body:
I have an application with a standard page layout, and many content templates.  Each content template could have one or more content sections that I want to treat as fragments.  I'd like to be able to iterate over each fragment and include it separately after putting in formatting divs.  The idea is that I don't want each content page to have to know how to nest section and div tags to get the page to format correctly. I've tried the following without success:

layout.html:

                    Messages go here

                   Content goes here.

content.html:

   Some things for my first section

    Some things for my second section

The fragment expression in content.html correctly finds all the divs with the section-content class, but they appear to be passed into layout.html as a single concatenated fragment.  Is there any way to get a list of fragments I can use for the "th:each" tag?

Body:
This is not an especially elegant solution, but I think it does what you need. It re-arranges your approach, so it may need some translating to your specific context.

It is a bit brittle because you have to maintain a count of sections (explained below).

The layout.html:

<html xmlns:th="http://www.thymeleaf.org"
      th:fragment="layout">

    <section class="row-outer-sm"
             th:each="i,iterStat : ${#numbers.sequence(1, 3)}"
             th:with="section=${'section-' + i}">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col">

                    <div th:if="${iterStat.first}">
                        Messages go here
                    </div>

                    <div th:replace="~{/content.html :: __${section}__} ">
                        Content goes here.
                    </div>
                </div>
            </div>
        </div>
    </section>

</html>

The content.html:

<html lang="en" xmlns:th="http://www.thymeleaf.org">

    <div th:fragment="section-1">
        <div class="section-content">
            Some things for my first section
        </div>
    </div>

    <div th:fragment="section-2">
        <div class="section-content">
            Some things for my second section
        </div>
    </div>

    <div th:fragment="section-3">
        <div class="section-content">
            Some things for my third section
        </div>
    </div>

</html>

The layout template builds a dynamically created fragment selector section_n, where n is the iterated value, based on Thymeleaf's sequence generator:

${#numbers.sequence(1, n)}

That is the brittle part - you have to remember to keep the hard-coded value of n in line with the number (and names!) of the section fragments in the content template.

We also use Thymeleaf's preprocesing __${}__ directive to allow the th:replace to operate on a string - the template selector.

In my example, the end result is HTML like this (the format's a bit wonky):

    <section class="row-outer-sm">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col">

                    <div>
                        Messages go here
                    </div>

                    <div>
        <div class="section-content">
            Some things for my first section
        </div>
    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="row-outer-sm">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col">

                    <div>
        <div class="section-content">
            Some things for my second section
        </div>
    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="row-outer-sm">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col">

                    <div>
        <div class="section-content">
            Some things for my third section
        </div>
    </div>
                </div>
            </div>
        </div>
    </section>

Hope that helps, or at least gives you some inspiration.


来源: stackexchange

问:
Newbie with regex
I have to build smth with URL, but only with valid google play links. I will get a link from user and want to check it before connect to it. If i have a Google Play link like this: https://play.google.com/store/apps/details?id=com....
I want to match it with regex and method matches (or should I just use method contains?) If link contains play.google.com - it's true and then do some actions. If false - throw new exception.

I tried with

```<code>\\. + play.google. + \\.
</code>```

but it doesn't work at all.

答:
\. matches a literal, actual dot. You want the actual dot:

```<code>Pattern.compile("^.*play\\.google\\..*$");
</code>```

However, you do not want to do this – here is a URL that will match: https://www.hacker.ru/hahaThisWillMatch?irrelevant=play.google

Put the URI into the java.net.URI class, and ask it what the server is, as well as the port, and the protocol. The port needs to be non-existent, the protocol needs to be https, and the server needs to be play.google.com, I'm not sure what other google domains you're looking for, but if you are, check against them all, don't try to use a regexp, because there are thousands of top level domains and google didn't register 'google' in literally ALL of them.

ContentLicense: CC BY-SA 4.0

Title: Newbie with regex

Body:
I have to build smth with URL, but only with valid google play links. I will get a link from user and want to check it before connect to it. If i have a Google Play link like this: https://play.google.com/store/apps/details?id=com....
I want to match it with regex and method matches (or should I just use method contains?) If link contains play.google.com - it's true and then do some actions. If false - throw new exception.

I tried with

\\. + play.google. + \\.

but it doesn't work at all.

Body:
\. matches a literal, actual dot. You want the actual dot:

Pattern.compile("^.*play\\.google\\..*$");

However, you do not want to do this – here is a URL that will match: https://www.hacker.ru/hahaThisWillMatch?irrelevant=play.google

Put the URI into the java.net.URI class, and ask it what the server is, as well as the port, and the protocol. The port needs to be non-existent, the protocol needs to be https, and the server needs to be play.google.com, I'm not sure what other google domains you're looking for, but if you are, check against them all, don't try to use a regexp, because there are thousands of top level domains and google didn't register 'google' in literally ALL of them.


问:
How to bypass python function definition with decorator?
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example:

```<code>@linux
def my_callback(*args, **kwargs):
    print("Doing something @ Linux")
    return

@windows
def my_callback(*args, **kwargs):
    print("Doing something @ Windows")
    return
</code>```

Then, if someone is using Linux, the first definition of my_callback will be used and the second will be silently ignored.

Its not about determining the OS, its about function definition / decorators.

答:
While @decorator syntax looks nice, you get the exact same behaviour as desired with a simple if.

```<code>linux = platform.system() == "Linux"
windows = platform.system() == "Windows"
macos = platform.system() == "Darwin"

if linux:
    def my_callback(*args, **kwargs):
        print("Doing something @ Linux")
        return

if windows:
    def my_callback(*args, **kwargs):
        print("Doing something @ Windows")
        return
</code>```

If required, this also allows to easily enforce that some case did match.

```<code>if linux:
    def my_callback(*args, **kwargs):
        print("Doing something @ Linux")
        return

elif windows:
    def my_callback(*args, **kwargs):
        print("Doing something @ Windows")
        return

else:
     raise NotImplementedError("This platform is not supported")
</code>```

Body:
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example:

@linux
def my_callback(*args, **kwargs):
    print("Doing something @ Linux")
    return

@windows
def my_callback(*args, **kwargs):
    print("Doing something @ Windows")
    return

Then, if someone is using Linux, the first definition of my_callback will be used and the second will be silently ignored.

Its not about determining the OS, its about function definition / decorators.

Body:
While @decorator syntax looks nice, you get the exact same behaviour as desired with a simple if.

linux = platform.system() == "Linux"
windows = platform.system() == "Windows"
macos = platform.system() == "Darwin"

if linux:
    def my_callback(*args, **kwargs):
        print("Doing something @ Linux")
        return

if windows:
    def my_callback(*args, **kwargs):
        print("Doing something @ Windows")
        return

If required, this also allows to easily enforce that some case did match.

if linux:
    def my_callback(*args, **kwargs):
        print("Doing something @ Linux")
        return

elif windows:
    def my_callback(*args, **kwargs):
        print("Doing something @ Windows")
        return

else:
     raise NotImplementedError("This platform is not supported")


问:
jQuery UI Dialog Scroll Bar + Overlay Settings Won't Unload
Recently, my friend helped me fix a background overlay problem.  I had an issue where if the dialog height extended beyond the original website background, it would cut off the overlay right in the middle.  His fix solved it.

But now I have a minor but annoying problem.  Every time I open a very long dialog, then a short one, the stretched scroll bars from the longer remains.  Like when I open the short afterwards, I can scroll down way beyond the background like with the longer, but I can only see the overlay.  I don’t think the settings are unloading properly once the dialog is closed.

Is there a way around this?  Thank you.

HTML:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/global.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- InstanceBeginEditable name="Meta" -->
<!-- InstanceEndEditable -->
<!-- InstanceBeginEditable name="doctitle" -->
<title>Ricky Tsang | Book | Bonus Features</title>
<!-- InstanceEndEditable -->
<link href="../../css/default.css" type="text/css" rel="stylesheet" />
<link href="../../css/plugins/jquery.jscrollpane.css" type="text/css" rel="stylesheet" />
<link href="../../css/plugins/custom-theme/jquery-ui-1.8.12.custom.css" type="text/css" rel="stylesheet" />
<link rel="shortcut icon" type="image/x-icon" href="http://www.dearricky.com/_rickytsang-ca/favicon.ico">
<!--[if IE 7]>
<link href="../css/ie7.css" type="text/css" rel="stylesheet" />
<![endif]-->
<!-- InstanceBeginEditable name="head" -->
<!-- InstanceEndEditable -->
<style>
a img {
    border:0
}
</style>
<noscript>
    <style>
    #header #inner { width: 820px; }
    #mainmenu { visibility: visible; }
    </style>
</noscript>
</head>

<body class="oneColElsCtrHdr">
<div id="header">
    <div id="top">
      <img src="../../images/logo.png" border="0" usemap="#Map" class="Logo" />
      <map name="Map" id="Map">
        <area shape="circle" coords="85,11,3" href="../../bird/" />
      </map>
</div>
    <div id="inner">
        <div id="mainmenu">
            <ul>
                <li>
                    <a href="../../" class="first">HOME</a>
                </li>
                <li>
                    <a href="../../ricky/aboutricky/" class="first parent">RICKY</a>
                    <div class="sub">
                        <ul>
                            <li><a href="../../ricky/aboutricky/" class="second">About Ricky</a></li>
                            <li><a href="../../ricky/disability/" class="second">Disability</a></li>
                            <li><a href="../../ricky/writing/" class="second">Writing</a></li>
                            <li><a href="../../ricky/questionsanswers/" class="second">Questions & Answers</a></li>
                        </ul>
                        <div class="clear"></div>
                    </div>
                </li>
                <li>
                    <a href="http://www.rickytsang.ca/blog/" class="first">JOURNAL</a>
                </li>
                <li>
                    <a href="../../advice/four/" class="first parent">ADVICE</a>
                    <div class="sub">
                        <ul>
                            <li><a href="../../advice/four/" class="second">4 Steps To Mending A Broken Heart</a></li>
                        </ul>
                        <div class="clear"></div>
                    </div>
                </li>
                <li>
                    <a href="../ridiculous/" class="first parent">BOOK</a>
                    <div class="sub">
                        <ul>
                            <li><a href="../ridiculous/" class="second">Ridiculous</a></li>
                            <li><a href="../excerpts/" class="second">Excerpts</a></li>
                            <li><a href="../bonusfeatures/" class="second">Bonus Features</a></li>
                            <li><a href="../wheretobuy/" class="second">Where To Buy</a></li>
                        </ul>
                        <div class="clear"></div>
                    </div>
                </li>
                <li>
                    <a href="../../music/" class="first">MUSIC</a>
                </li>
                <li>
                    <a href="http://www.rickytsang.ca/forum/" class="first">FORUM</a>
                </li>
                <li>
                    <a href="../../information/news" class="first parent">INFORMATION</a>
                    <div class="sub">
                        <ul>
                            <li><a href="../../information/news/" class="second">News</a></li>
                            <li><a href="../../information/contact/" class="second">Contact</a></li>
                            <li><a href="../../information/links/" class="second">Links</a></li>
                            <li><a href="../../information/website/" class="second">Website</a></li>
                        </ul>
                        <div class="clear"></div>
                    </div>
                </li>
          </ul>
        </div>
        <div class="clear"></div>
    </div>
</div>
<div id="container">
    <!-- InstanceBeginEditable name="AboveContainer" -->

    <!-- InstanceEndEditable -->
    <div id="topContent"></div>
    <div id="mainContent">
        <!-- InstanceBeginEditable name="MainContent" -->
        <div id="fixedHeightContent">
          <h1 align="justify">Bonus Features</h1>
          <p><strong><em><a href="../ridiculous/">Ridiculous:  The Mindful Nonsense of Ricky’s Brain</a></em> is jam-packed with  hundreds of pages of writing, but there are always limitations when it comes to  books.  Below are some extras that readers  may find entertaining, kind of like a DVD!</strong></p>
          <h2><strong><u>From The Book (with  excerpts)</u></strong></h2>
          <p><strong><a href="javascript:openDialog('../../pages/book/bonusfeatures/extras/2009-02-23-the-girl-who-saved-my-life.html');">The Girl Who Saved My Life</a></strong><br />
          A  true story about an amazing girl who stole my heart.  Includes a photo and video of interesting  items.</p>
          <p><strong><a href="javascript:openDialog('../../pages/book/bonusfeatures/extras/2009-08-10-rickys-adventures-in-bikini-land.html');">Ricky’s Adventures In  Bikini Land</a></strong><br />
            A  satirical recount of my “adventures” in Niagara Falls.  Includes a window scene photo from the room  where my family and I stayed.</p>
          <p><strong><a href="javascript:openDialog('../../pages/book/bonusfeatures/extras/2009-08-25-the-brain-behind-his-words.html');">The Brain Behind His Words</a></strong><br />
            A  brutally honest narrative of the things that go on inside my head.  Includes a full-size photo of myself that was  an inspiration for the piece.</p>
          <p><strong><a href="javascript:openDialog('../../pages/book/bonusfeatures/extras/2009-08-30-rickys-moments-of-wtf.html');">Ricky’s Moments Of WTF?!</a></strong><br />
          About  the stranger happenings in the life of yours truly.  Includes a few photos of… embarrassing  things.</p>
          <p><strong><a href="javascript:openDialog('../../pages/book/bonusfeatures/extras/2010-05-09-appreciating-mothers-the-how-to-guide.html');">Appreciating Mothers: The  How-To Guide</a></strong><br />
            A  comical yet hopefully endearing guide on how to appreciate mothers.  Includes a poem I wrote about the uterus.</p>
          <h2><strong><u>Pages That Didn’t Make It</u></strong>
          </h2>
          <p><strong><a href="javascript:openDialog('../../pages/book/bonusfeatures/deletedpages/2005-12-04-rickys-romantic-analogies.html');">Ricky’s Romantic Analogies</a></strong><br />
          No matter how much I edited this  entry, it continued to remain… corny.   Though, it did become a pivotal part of the romantic ideas for my  following writings.</p>
          <p><strong><a href="javascript:openDialog('../../pages/book/bonusfeatures/deletedpages/2006-08-29-monkey-see-monkey-do.html');">Monkey See, Monkey Do</a></strong><br />
            This  one seemed a little out of place for the book, despite the title.  It also had too many photos that only look  good in colour.</p>
        </div>
        <!-- InstanceEndEditable -->
    </div>
    <div id="bottomContent"></div>
</div>

<div id="footer">
    <div class="social">
        <ul>
            <li><a href="http://www.facebook.com/DearRicky/" target="_blank" title="Facebook"><img src="../../images/icons/facebook.png" /></a></li>
            <li><a href="http://www.twitter.com/DearRicky/" target="_blank" title="Twitter"><img src="../../images/icons/twitter.png" /></a></li>
        </ul>
    </div>
    <div class="copyright">
        Copyright © 2011 Ricky Wai Kit Tsang.  All rights reserved.
    </div>
</div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="../../scripts/global.js"></script>
<script type="text/javascript" src="../../scripts/plugins/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="../../scripts/plugins/jquery-ui-1.8.12.custom.min.js"></script>
<script type="text/javascript" src="../../scripts/plugins/jquery.hoverIntent.js"></script>
<script type="text/javascript" src="../../scripts/plugins/jquery.mousewheel.js"></script>
<script type="text/javascript" src="../../scripts/plugins/jquery.jscrollpane.js"></script>
<script type="text/javascript">
    $(function() {
        $("#fixedHeightContent").jScrollPane({
            showArrows: true
        });
    });
</script>

<!-- InstanceBeginEditable name="Scripts" -->
<!-- InstanceEndEditable -->

</body>
<!-- InstanceEnd --></html>
</code>```

CSS:

```<code>body {
    background: url("../images/backgrounds/glowing-clouds.jpg") no-repeat scroll center 130px #000;
    font-family: Arial, Verdana, Helvetica, sans-serif;
    font-size: 12px;
    margin: 0;
    padding: 0;
    text-align: center;
    color: #000000;
}

a {
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}

h1 {
    color: #000;
    margin-bottom: 20px;
    margin-top: 0px;
}

h2 {
    color: #000;
    font-size: 16px;
}

p {
    font-size: 14px;
    line-height: 18px;
    margin-bottom: 10px;
    margin-top: 0px;
}

.clear {
    clear: both;
}

#container {
    width: 880px;
    margin: 20px auto 0px auto;
    text-align: left;
}

#topContent {
    background-image: url("../images/backgrounds/slider-top.png");
    background-repeat: no-repeat;
    height: 15px;
    margin-top: 40px;
    width: 880px;
}

#mainContent {
    background: transparent url("../images/backgrounds/slider-body.png") repeat-y scroll 0 0;
    hasLayout: false;
    padding: 1px 15px;
    width: 850px;
}

#fixedHeightContent {
    height: 440px;
    outline: none;
    overflow: auto;
    padding: 20px;
    width: 810px;
}

#bottomContent {
    background-image: url("../images/backgrounds/slider-bottom.png");
    background-repeat: no-repeat;
    height: 15px;
    width: 880px;
}

#floatContent {
    overflow: hidden} /**clears floats**/

.RightCaptions {/** container **/
    float: right;
    width: auto;
    height:auto;
    border: thin silver solid;
    margin: 0.5em;
    padding: 0.5em;
}

.LeftCaptions {/** container **/
    float: left;
    width: auto;
    height:auto;
    border: thin silver solid;
    margin: 0.5em;
    padding: 0.5em;
}

.RightCaptions p, .LeftCaptions p {/** text captions **/
    text-align: center;
    font-style: italic;
    font-size: small;
    text-indent: 0;
}

#header {
    margin: 0px 0px 10px;
    position: relative;
}

#header #top {
    background-color: #000;
    margin: 0px auto;
}

#header #inner {
    margin: 0px auto;
    width: 820px;
}

#header img.Logo {
    padding: 25px 0px 20px 0px;
    position: relative;
}

#mainmenu {
    float: right;
}

#mainmenu ul {
    list-style: none;
    margin: 0px;
    padding: 0px;
}

#mainmenu ul li {
    display: block;
    float: left;
}

#mainmenu ul li a {
    color: #fff;
    display: block;
    font-size: 14px;
    font-weight: bold;
    height: 35px;
    line-height: 35px;
    padding: 0px 15px;
}

#mainmenu ul li a:hover {
    color: #999;
    text-decoration: none;
}

#mainmenu ul li a.parent {
    background: transparent url("../images/menu/menu-down.png") no-repeat center right;
    margin-right: 15px;
}

#mainmenu .sub {
    border: solid 1px #fff;
    display: none;
    position: absolute;
    z-index: 1000;
}

#mainmenu .sub ul {
    margin: 0px;
}

#mainmenu .sub li {
    border: none;
    display: block;
    float: left;
    height: auto;
    padding: 0px;
    width: auto;
}

#mainmenu .sub a {
    color: #fff;
    display: block;
    font-size: 12px;
    height: auto;
    line-height: 16px;
    padding: 5px 8px 7px;
    text-align: left;
}

#mainmenu .sub a:hover {
    background-image: none;
}

#footer {
    margin: 0px auto;
    padding-bottom: 60px;
    width: 850px;
    position: relative;
    text-align: center;
}

#footer .social {
    position: absolute;
    top: 0;
    left: 10px;
}

#footer .social ul {
    list-style: none;
    margin: 10px 0px 0px;
    padding: 0px;
}

#footer .social li {
    float: left;
    margin-right: 5px;
}

#footer .social img {
    border: 0px;
}

#footer .copyright {
    color: #fff;
    line-height: 32px;
    margin-top: 10px;
}

/*******************************
 * Controls
 ******************************/

.ImageRotator {
    overflow: hidden;
    position: relative;
    width: 850px;
}

.ImageRotator ul {
    list-style-type: none;
    margin: 0px;
    padding: 0px;
    width: 9999px;
}

.ImageRotator ul li {
    display: block;
    float: left;
    height: 440px;
    width: 850px;
    overflow: hidden;
}

.ImageRotator ul li img.gallery {
    border: 0px;
    height: 630px;
    width: 850px;
}

.ImageRotator .toolbar {
    background: url("../images/backgrounds/slider-toolbar.png") repeat scroll 0 0 transparent;
    bottom: 0px;
    color: #fff;
    height: 36px;
    left: 0px;
    position: absolute;
    width: 850px;
    z-index: 100;
}

.ImageRotator .toolbar .desc {
    font-weight: bold;
    margin: 10px;
    text-align: center;
}

.ImageRotator .toolbar .pages {
    margin: 5px;
    position: absolute;
    right: 0px;
}

.ImageRotator .toolbar .pages div {
    background: url("../images/backgrounds/page.png") repeat scroll 0 0 transparent;
    color: #999;
    cursor: pointer;
    float: left;
    font-weight: bold;
    height: 22px;
    padding-top: 6px;
    text-align: center;
    width: 28px;
}

.ImageRotator .toolbar .pages div.Active {
    color: #0f75a7;
}

/*******************************
 * Pages
 ******************************/

 .popupDialog {
    font-family: Arial, Verdana, Helvetica, sans-serif;
    font-size: 12px;
 }
</code>```

Script:

```<code><script type="text/javascript">
function openDialog(url) {
    $("<div class='popupDialog'>Loading...</div>")
        .dialog({
            autoOpen: false,
            closeOnEscape: true,
            width: '900',
            height: 'auto',
            modal: true,
            title: 'Bonus Features',
            autoResize: true,
            beforeClose: function(){   $(this).remove();   }
        }).bind('dialogclose', function() {
            jdialog.dialog('destroy');
        }).load(url, function() {
            $(this).dialog("option", "position", ['center', 'center'] ).bind('dialogopen', function() {
                    adjustJQueryDialogOverlay();
                });
                $(this).dialog("open");
        });
}

$(window).resize(function() {
    $(".ui-dialog-content").dialog("option", "position", ['center', 'center']);
});
</script>
</code>```

答:
Well, you're not supposed to be required to do this, but when I ran into this same sort of problem, the easiest/quickest fix I found was to call the dialog's destroy method before I create a new one. So you'd try something like this:

```<code>$(".ui-dialog-content").dialog("destroy");
</code>```

This goes immediately before the area in your script in which you set up the new dialog.

HTH.

Edit: As requested:

```<code><script>
function openDialog(url) {
    $("<div class='popupDialog'>Loading...</div>").dialog("destroy");

    $("<div class='popupDialog'>Loading...</div>")
        .dialog({
            autoOpen: false,
            closeOnEscape: true,
            width: '900',
            height: 'auto',
            modal: true,
            title: 'Bonus Features',
            autoResize: true,
            beforeClose: function(){   $(this).remove();   }
        }).bind('dialogclose', function() {
            jdialog.dialog('destroy');
        }).load(url, function() {
            $(this).dialog("option", "position", ['center', 'center'] ).bind('dialogopen', function() {
                    adjustJQueryDialogOverlay();
                });
                $(this).dialog("open");
        });
}

$(window).resize(function() {
     $(".ui-dialog-content").dialog("destroy");

     $(".ui-dialog-content").dialog("option", "position", ['center', 'center']);
});
</script>
</code>```

Should only need to update the script part.

ContentLicense: CC BY-SA 3.0

Body:
Recently, my friend helped me fix a background overlay problem.  I had an issue where if the dialog height extended beyond the original website background, it would cut off the overlay right in the middle.  His fix solved it.

But now I have a minor but annoying problem.  Every time I open a very long dialog, then a short one, the stretched scroll bars from the longer remains.  Like when I open the short afterwards, I can scroll down way beyond the background like with the longer, but I can only see the overlay.  I don’t think the settings are unloading properly once the dialog is closed.

Is there a way around this?  Thank you.

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Ricky Tsang | Book | Bonus Features</title>

<link href="../../css/default.css" type="text/css" rel="stylesheet" />
<link href="../../css/plugins/jquery.jscrollpane.css" type="text/css" rel="stylesheet" />
<link href="../../css/plugins/custom-theme/jquery-ui-1.8.12.custom.css" type="text/css" rel="stylesheet" />
<link rel="shortcut icon" type="image/x-icon" href="http://www.dearricky.com/_rickytsang-ca/favicon.ico">

      <map name="Map" id="Map">
        <area shape="circle" coords="85,11,3" href="../../bird/" />
      </map>

                    HOME

                    RICKY

About Ricky

Disability

Writing

Questions & Answers

                    JOURNAL

                    ADVICE

4 Steps To Mending A Broken Heart

                    BOOK

Ridiculous

Excerpts

Bonus Features

Where To Buy

                    MUSIC

                    FORUM

                    INFORMATION

News

Contact

Links

Website

Bonus Features

Ridiculous:  The Mindful Nonsense of Ricky’s Brain is jam-packed with  hundreds of pages of writing, but there are always limitations when it comes to  books.  Below are some extras that readers  may find entertaining, kind of like a DVD!

From The Book (with  excerpts)

The Girl Who Saved My Life

          A  true story about an amazing girl who stole my heart.  Includes a photo and video of interesting  items.

Ricky’s Adventures In  Bikini Land

            A  satirical recount of my “adventures” in Niagara Falls.  Includes a window scene photo from the room  where my family and I stayed.

The Brain Behind His Words

            A  brutally honest narrative of the things that go on inside my head.  Includes a full-size photo of myself that was  an inspiration for the piece.

Ricky’s Moments Of WTF?!

          About  the stranger happenings in the life of yours truly.  Includes a few photos of… embarrassing  things.

Appreciating Mothers: The  How-To Guide

            A  comical yet hopefully endearing guide on how to appreciate mothers.  Includes a poem I wrote about the uterus.

Pages That Didn’t Make It

Ricky’s Romantic Analogies

          No matter how much I edited this  entry, it continued to remain… corny.   Though, it did become a pivotal part of the romantic ideas for my  following writings.

Monkey See, Monkey Do

            This  one seemed a little out of place for the book, despite the title.  It also had too many photos that only look  good in colour.

        Copyright © 2011 Ricky Wai Kit Tsang.  All rights reserved.

CSS:

body {
    background: url("../images/backgrounds/glowing-clouds.jpg") no-repeat scroll center 130px #000;
    font-family: Arial, Verdana, Helvetica, sans-serif;
    font-size: 12px;
    margin: 0;
    padding: 0;
    text-align: center;
    color: #000000;
}

a {
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}

h1 {
    color: #000;
    margin-bottom: 20px;
    margin-top: 0px;
}

h2 {
    color: #000;
    font-size: 16px;
}

p {
    font-size: 14px;
    line-height: 18px;
    margin-bottom: 10px;
    margin-top: 0px;
}

.clear {
    clear: both;
}

#container {
    width: 880px;
    margin: 20px auto 0px auto;
    text-align: left;
}

#topContent {
    background-image: url("../images/backgrounds/slider-top.png");
    background-repeat: no-repeat;
    height: 15px;
    margin-top: 40px;
    width: 880px;
}

#mainContent {
    background: transparent url("../images/backgrounds/slider-body.png") repeat-y scroll 0 0;
    hasLayout: false;
    padding: 1px 15px;
    width: 850px;
}

#fixedHeightContent {
    height: 440px;
    outline: none;
    overflow: auto;
    padding: 20px;
    width: 810px;
}

#bottomContent {
    background-image: url("../images/backgrounds/slider-bottom.png");
    background-repeat: no-repeat;
    height: 15px;
    width: 880px;
}

#floatContent {
    overflow: hidden} /**clears floats**/

.RightCaptions {/** container **/
    float: right;
    width: auto;
    height:auto;
    border: thin silver solid;
    margin: 0.5em;
    padding: 0.5em;
}

.LeftCaptions {/** container **/
    float: left;
    width: auto;
    height:auto;
    border: thin silver solid;
    margin: 0.5em;
    padding: 0.5em;
}

.RightCaptions p, .LeftCaptions p {/** text captions **/
    text-align: center;
    font-style: italic;
    font-size: small;
    text-indent: 0;
}

#header {
    margin: 0px 0px 10px;
    position: relative;
}

#header #top {
    background-color: #000;
    margin: 0px auto;
}

#header #inner {
    margin: 0px auto;
    width: 820px;
}

#header img.Logo {
    padding: 25px 0px 20px 0px;
    position: relative;
}

#mainmenu {
    float: right;
}

#mainmenu ul {
    list-style: none;
    margin: 0px;
    padding: 0px;
}

#mainmenu ul li {
    display: block;
    float: left;
}

#mainmenu ul li a {
    color: #fff;
    display: block;
    font-size: 14px;
    font-weight: bold;
    height: 35px;
    line-height: 35px;
    padding: 0px 15px;
}

#mainmenu ul li a:hover {
    color: #999;
    text-decoration: none;
}

#mainmenu ul li a.parent {
    background: transparent url("../images/menu/menu-down.png") no-repeat center right;
    margin-right: 15px;
}

#mainmenu .sub {
    border: solid 1px #fff;
    display: none;
    position: absolute;
    z-index: 1000;
}

#mainmenu .sub ul {
    margin: 0px;
}

#mainmenu .sub li {
    border: none;
    display: block;
    float: left;
    height: auto;
    padding: 0px;
    width: auto;
}

#mainmenu .sub a {
    color: #fff;
    display: block;
    font-size: 12px;
    height: auto;
    line-height: 16px;
    padding: 5px 8px 7px;
    text-align: left;
}

#mainmenu .sub a:hover {
    background-image: none;
}

#footer {
    margin: 0px auto;
    padding-bottom: 60px;
    width: 850px;
    position: relative;
    text-align: center;
}

#footer .social {
    position: absolute;
    top: 0;
    left: 10px;
}

#footer .social ul {
    list-style: none;
    margin: 10px 0px 0px;
    padding: 0px;
}

#footer .social li {
    float: left;
    margin-right: 5px;
}

#footer .social img {
    border: 0px;
}

#footer .copyright {
    color: #fff;
    line-height: 32px;
    margin-top: 10px;
}

/*******************************
 * Controls
 ******************************/

.ImageRotator {
    overflow: hidden;
    position: relative;
    width: 850px;
}

.ImageRotator ul {
    list-style-type: none;
    margin: 0px;
    padding: 0px;
    width: 9999px;
}

.ImageRotator ul li {
    display: block;
    float: left;
    height: 440px;
    width: 850px;
    overflow: hidden;
}

.ImageRotator ul li img.gallery {
    border: 0px;
    height: 630px;
    width: 850px;
}

.ImageRotator .toolbar {
    background: url("../images/backgrounds/slider-toolbar.png") repeat scroll 0 0 transparent;
    bottom: 0px;
    color: #fff;
    height: 36px;
    left: 0px;
    position: absolute;
    width: 850px;
    z-index: 100;
}

.ImageRotator .toolbar .desc {
    font-weight: bold;
    margin: 10px;
    text-align: center;
}

.ImageRotator .toolbar .pages {
    margin: 5px;
    position: absolute;
    right: 0px;
}

.ImageRotator .toolbar .pages div {
    background: url("../images/backgrounds/page.png") repeat scroll 0 0 transparent;
    color: #999;
    cursor: pointer;
    float: left;
    font-weight: bold;
    height: 22px;
    padding-top: 6px;
    text-align: center;
    width: 28px;
}

.ImageRotator .toolbar .pages div.Active {
    color: #0f75a7;
}

/*******************************
 * Pages
 ******************************/

 .popupDialog {
    font-family: Arial, Verdana, Helvetica, sans-serif;
    font-size: 12px;
 }

Script:

Body:
Well, you're not supposed to be required to do this, but when I ran into this same sort of problem, the easiest/quickest fix I found was to call the dialog's destroy method before I create a new one. So you'd try something like this:

$(".ui-dialog-content").dialog("destroy");

This goes immediately before the area in your script in which you set up the new dialog.

HTH.

Edit: As requested:

<script>
function openDialog(url) {
    $("<div class='popupDialog'>Loading...</div>").dialog("destroy");

    $("<div class='popupDialog'>Loading...</div>")
        .dialog({
            autoOpen: false,
            closeOnEscape: true,
            width: '900',
            height: 'auto',
            modal: true,
            title: 'Bonus Features',
            autoResize: true,
            beforeClose: function(){   $(this).remove();   }
        }).bind('dialogclose', function() {
            jdialog.dialog('destroy');
        }).load(url, function() {
            $(this).dialog("option", "position", ['center', 'center'] ).bind('dialogopen', function() {
                    adjustJQueryDialogOverlay();
                });
                $(this).dialog("open");
        });
}

$(window).resize(function() {
     $(".ui-dialog-content").dialog("destroy");

     $(".ui-dialog-content").dialog("option", "position", ['center', 'center']);
});
</script>

Should only need to update the script part.


问:
Generate a Makefile that compiles and links all the source files in a single step with Automake
I am new with automake. I am trying to write the Makefile.am files for my library, however due to some limitation of the nvcc compiler, I need to compile and link the source files in a single step, without producing the .o files, so that I directly generate the library without having to link separate files. I could find several examples of Makefile.am files in the web, but none of them seemed to fit my need. Here is my (working) Makefile:

```<code>CC=g++
NVCC=nvcc
CXXFLAGS= -O3 -Wall -fPIC
CUDAFLAGS= -arch sm_30 --ptxas-options=-v --relocatable-device-code true
LIBS= -lm
LDFLAGS = -shared   # linking flags

RM = rm -f   # rm command
TARGET_LIB = ./lib/libsharedcuda.so  # target lib

SRC_DIR   = src

SRC_FILES  = $(wildcard $(SRC_DIR)/*.cu)
SRC_FILES += $(wildcard $(SRC_DIR)/*.cpp)

H_FILES   = $(wildcard $(SRC_DIR)/*.h)
H_FILES += $(wildcard $(SRC_DIR)/*.cuh)

.PHONY: all
all: ${TARGET_LIB}

$(TARGET_LIB): $(SRC_FILES)
    $(NVCC) -ccbin=${CC} --compiler-options  '${CXXFLAGS}' ${CUDAFLAGS} ${LDFLAGS} -o $@ $^

.PHONY: clean
clean:
    -${RM} ${TARGET_LIB}
</code>```

How should the Makefile.am be written in order to produce a makefile like this one?

答:
The correct answer to my question is the one written by Sam Varshavchik: as he pointed out, it is not possible. However, for anyone who might be interested, I found a workaround that solves my problem, useful for instance if you want to build a CUDA-C/C++ shared library with Autotools.

The trick is to generate first the src/Makefile.in file using autotools, then modifing this file before the make command.
With my versions of autoconf/automake, the relevant line is:

```<code>    $(AM_V_CXXLD)$(libexample_la_LINK) ...
</code>```

that should be replaced by something like:

```<code>    nvcc -ccbin=g++ --compiler-options  '-O3 -Wall -fPIC' -shared -arch sm_30 --ptxas-options=-v --relocatable-device-code true -o source-files -lm
</code>```

where libexample is the name of the library and source-files is the list of files to be compiled.
 Be careful: the line is preceded by a tab, not by spaces.
 If you want to be able to use "make install", you should also modify the command that installs the library in the proper folder. In my case in:

```<code>    $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)";
</code>```

"$$list2" should be replaced by "libexample.so"

This patch could be done automatically by a shell script launched at the end of the config script.
I have placed a complete working example in  https://github.com/golosio/sharedcuda_autotools

Body:
I am new with automake. I am trying to write the Makefile.am files for my library, however due to some limitation of the nvcc compiler, I need to compile and link the source files in a single step, without producing the .o files, so that I directly generate the library without having to link separate files. I could find several examples of Makefile.am files in the web, but none of them seemed to fit my need. Here is my (working) Makefile:

CC=g++
NVCC=nvcc
CXXFLAGS= -O3 -Wall -fPIC
CUDAFLAGS= -arch sm_30 --ptxas-options=-v --relocatable-device-code true
LIBS= -lm
LDFLAGS = -shared   # linking flags

RM = rm -f   # rm command
TARGET_LIB = ./lib/libsharedcuda.so  # target lib

SRC_DIR   = src

SRC_FILES  = $(wildcard $(SRC_DIR)/*.cu)
SRC_FILES += $(wildcard $(SRC_DIR)/*.cpp)

H_FILES   = $(wildcard $(SRC_DIR)/*.h)
H_FILES += $(wildcard $(SRC_DIR)/*.cuh)

.PHONY: all
all: ${TARGET_LIB}

$(TARGET_LIB): $(SRC_FILES)
    $(NVCC) -ccbin=${CC} --compiler-options  '${CXXFLAGS}' ${CUDAFLAGS} ${LDFLAGS} -o $@ $^

.PHONY: clean
clean:
    -${RM} ${TARGET_LIB}

How should the Makefile.am be written in order to produce a makefile like this one?

Body:
The correct answer to my question is the one written by Sam Varshavchik: as he pointed out, it is not possible. However, for anyone who might be interested, I found a workaround that solves my problem, useful for instance if you want to build a CUDA-C/C++ shared library with Autotools.

The trick is to generate first the src/Makefile.in file using autotools, then modifing this file before the make command.
With my versions of autoconf/automake, the relevant line is:

    $(AM_V_CXXLD)$(libexample_la_LINK) ...

that should be replaced by something like:

    nvcc -ccbin=g++ --compiler-options  '-O3 -Wall -fPIC' -shared -arch sm_30 --ptxas-options=-v --relocatable-device-code true -o source-files -lm

where libexample is the name of the library and source-files is the list of files to be compiled.
 Be careful: the line is preceded by a tab, not by spaces.
 If you want to be able to use "make install", you should also modify the command that installs the library in the proper folder. In my case in:

    $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)";

"$$list2" should be replaced by "libexample.so"

This patch could be done automatically by a shell script launched at the end of the config script.
I have placed a complete working example in  https://github.com/golosio/sharedcuda_autotools


问:
Can I Entity Room data right from RecyclerView and Save it to Room Database?
I have some adapter which use retrofit to get data right from web api and place it to recyclerview

```<code>    public class NoticeAdapter extends RecyclerView.Adapter<NoticeAdapter.EmployeeViewHolder> {
            private  Wind wind;
            private ArrayList<Notice> dataList;
            private Main main;
            private Date currentTime = Calendar.getInstance().getTime();

            private RecyclerItemClickListener recyclerItemClickListener;
            public NoticeAdapter(ArrayList<Notice> dataList, Main main, Wind wind, RecyclerItemClickListener recyclerItemClickListener) {
                this.dataList = dataList;
                this.main = main;
                this.wind = wind;
                this.recyclerItemClickListener = recyclerItemClickListener;
            }
@Override
    public EmployeeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.single_view_row, parent, false);
        return new EmployeeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(EmployeeViewHolder holder, @SuppressLint("RecyclerView") final int position) {
        if(getAddressMap()!=null){holder.txtNoticeAddress.setText("Loc: "+getAddressMap());}else{holder.txtNoticeAddress.setText("Loc: Unknown location");}
        holder.imageIcon.setImageURI(Uri.parse("android.resource://com.locweather/drawable/i"+dataList.get(position).getIcon()));
        holder.txtNoticeWind.setText("Wind: "+roundUp(+wind.getSpeed(),1)+"m/s, "+arrow());
        holder.txtNoticeTempMain.setText(roundUp(+main.getTemp(),1)+"°C");
        holder.txtNoticeWeather.setText(dataList.get(position).getWeather()+" : "+dataList.get(position).getInfo());
        holder.txtNoticeTemp.setText("Feels: "+roundUp(+main.getFeelsLike(),1)+"°C ");
        holder.txtNoticeTime.setText(currentTime.toString());
        holder.txtNoticeHumidity.setText("Humidity: "+main.getHumidity()+"%");
        holder.txtNoticePressure.setText("Pressure: "+main.getPressure()+"hPa");
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerItemClickListener.onItemClick(dataList.get(position));
            }
        });
    }
@Override
    public int getItemCount() {
        return dataList.size();
    }

    class EmployeeViewHolder extends RecyclerView.ViewHolder {
        ImageView imageIcon;
        TextView txtNoticeWeather, txtNoticeTempMain,txtNoticeTemp, txtNoticeHumidity,txtNoticeAddress,txtNoticePressure,txtNoticeWind,txtNoticeTime;

        EmployeeViewHolder(View itemView) {
            super(itemView);
            imageIcon=itemView.findViewById(R.id.image_icon);
            txtNoticeTime= itemView.findViewById(R.id.txt_time);
            txtNoticeWind= itemView.findViewById(R.id.txt_notice_wind);
            txtNoticeAddress=  itemView.findViewById(R.id.txt_notice_title);
            txtNoticeWeather =  itemView.findViewById(R.id.txt_notice_weather);
            txtNoticeTemp =  itemView.findViewById(R.id.txt_notice_temp);
            txtNoticeHumidity =  itemView.findViewById(R.id.txt_notice_humidity);
            txtNoticePressure =  itemView.findViewById(R.id.txt_notice_pressure);
            txtNoticeTempMain =  itemView.findViewById(R.id.txt_notice_temp_main);
        }
    }
</code>```

This is my recyclerview
This works only when network is enabled

The question is how to set this data right from RecyclerView (or other way) to my Room DataBase when network is enabled by Onclick SaveButton to create other recyclerview and set data there, to get it offline later.

I'm trying to create Entity

```<code>  @Entity
    public class WeatherData {
        @PrimaryKey(autoGenerate = true)
        private long id;
        private String address;
        private Double windSpeed;
        private Integer windDegree;
        private String datalistIcon;
        private String datalistInfo;
        private String datalistWeather;
        private Double mainTemp;
        private Double mainFeel;
        private Integer mainHumidity;
        private Integer mainPressure;
        private String time;
        private Double locLat;
        private Double locLon;
        public WeatherData(){}
        @Ignore
        public WeatherData(String address, Double windSpeed, Integer windDegree, String datalistIcon,String datalistInfo,String datalistWeather, Double mainTemp,Double mainFeel,Integer mainHumidity,Integer mainPressure,String time,LatLng currentLocation,Double locLat,Double locLon) {
            this.address = address;
            this.windSpeed = windSpeed;
            this.windDegree = windDegree;
            this.datalistIcon=datalistIcon;
            this.datalistInfo=datalistInfo;
            this.datalistWeather=datalistWeather;
            this.mainTemp=mainTemp;
            this.mainFeel=mainFeel;
            this.mainHumidity=mainHumidity;
            this.mainPressure=mainPressure;
            this.time=time;
            this.locLat=locLat;
            this.locLon=locLon;
        }
</code>```

Dao

```<code>@Dao
public interface WeatherDataDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void saveAll(List<WeatherData> weathers);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void save(WeatherData weather);

    @Update
    void update(WeatherData weather);

    @Delete
    void delete(WeatherData weather);

    @Query("SELECT * FROM WeatherData")
    LiveData<List<WeatherData>> findAll();
}
</code>```

and DataBase

```<code>  @Database(entities = {WeatherData.class}, version = 1)
    public abstract class WeatherDatabase extends RoomDatabase {
        public static WeatherDatabase INSTANCE;
        public abstract WeatherDataDao weatherDao();
        private static final Object sLock = new Object();
        public static WeatherDatabase getInstance(Context context) {
            synchronized (sLock) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            WeatherDatabase.class, "Weathers.db")
                            .allowMainThreadQueries()
                            .build();
                }
                return INSTANCE;
            }
        }
</code>```

Which way do I need to create it?

答:
Create an @Entity Notice which is your data type to be stored in your Room DB.

Create a View Model which is attached to your Activity/Fragment where you need to show this list.

Use your ViewModel to store the list from API into your Room DB.

Create a LiveData which observes on the DB and sends the updated list to the other view.

Code for Saving Data in DB. This needs to be run on Background Thread.

```<code>public static void saveNoticeList(Context context, List<Notice> noticeList) {
     if (context != null && noticeList != null) {
         RoomDatabaseCreator.getInstance(context)
                 .getDatabase()
                 .noticeDao()
                 .saveNotices(noticeList);
     }
 }

// For Saving in background you can use RxJava, I am using a new thread for simplification

backgroundHandler.post(() -> {
            saveNoticeList(getActivity(), dataList);
        });
</code>```

ViewModel

```<code>public class NoticeViewModel extends AndroidViewModel {
    public MutableLiveData<List<Notice>> mNoticesLiveData = new MutableLiveData<>();

    private Context mContext;

    public NoticeViewModel(final Application application) {
        super(application);
        mContext = application.getApplicationContext();

        mNoticesLiveData = Transformations.switchMap(databaseCreated,
                (Function<Boolean, LiveData<List<Notice>>) isDbCreated -> {
                    if (!Boolean.TRUE.equals(isDbCreated)) { // Not needed here, but watch out for null
                        //noinspection unchecked
                        return ABSENT;
                    } else {
                            return databaseCreator.getDatabase()
                                    .noticedao()
                                    .getSavedNotices();
                        }
                    }
                });

    public LiveData<List<Notice> getNoticeLiveData() {
        return mNoticesLiveData;
    }
}
</code>```

Activity Code where you need to show the saved data

```<code>//1. Initialize the viewModel
NoticeViewModel viewModel = ViewModelProviders.of(this).get(NoticeViewModel.class);

//2. Subscribe to the saved notices live-data to get updates in your view
viewModel.getNoticeLiveData().observe(this
       list -> {
                if (list.isEmpty()) {
                       return;
                }

                // Add the list in your adapter

            });
</code>```

Body:
I have some adapter which use retrofit to get data right from web api and place it to recyclerview

    public class NoticeAdapter extends RecyclerView.Adapter<NoticeAdapter.EmployeeViewHolder> {
            private  Wind wind;
            private ArrayList<Notice> dataList;
            private Main main;
            private Date currentTime = Calendar.getInstance().getTime();

            private RecyclerItemClickListener recyclerItemClickListener;
            public NoticeAdapter(ArrayList<Notice> dataList, Main main, Wind wind, RecyclerItemClickListener recyclerItemClickListener) {
                this.dataList = dataList;
                this.main = main;
                this.wind = wind;
                this.recyclerItemClickListener = recyclerItemClickListener;
            }
@Override
    public EmployeeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.single_view_row, parent, false);
        return new EmployeeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(EmployeeViewHolder holder, @SuppressLint("RecyclerView") final int position) {
        if(getAddressMap()!=null){holder.txtNoticeAddress.setText("Loc: "+getAddressMap());}else{holder.txtNoticeAddress.setText("Loc: Unknown location");}
        holder.imageIcon.setImageURI(Uri.parse("android.resource://com.locweather/drawable/i"+dataList.get(position).getIcon()));
        holder.txtNoticeWind.setText("Wind: "+roundUp(+wind.getSpeed(),1)+"m/s, "+arrow());
        holder.txtNoticeTempMain.setText(roundUp(+main.getTemp(),1)+"°C");
        holder.txtNoticeWeather.setText(dataList.get(position).getWeather()+" : "+dataList.get(position).getInfo());
        holder.txtNoticeTemp.setText("Feels: "+roundUp(+main.getFeelsLike(),1)+"°C ");
        holder.txtNoticeTime.setText(currentTime.toString());
        holder.txtNoticeHumidity.setText("Humidity: "+main.getHumidity()+"%");
        holder.txtNoticePressure.setText("Pressure: "+main.getPressure()+"hPa");
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerItemClickListener.onItemClick(dataList.get(position));
            }
        });
    }
@Override
    public int getItemCount() {
        return dataList.size();
    }

    class EmployeeViewHolder extends RecyclerView.ViewHolder {
        ImageView imageIcon;
        TextView txtNoticeWeather, txtNoticeTempMain,txtNoticeTemp, txtNoticeHumidity,txtNoticeAddress,txtNoticePressure,txtNoticeWind,txtNoticeTime;

        EmployeeViewHolder(View itemView) {
            super(itemView);
            imageIcon=itemView.findViewById(R.id.image_icon);
            txtNoticeTime= itemView.findViewById(R.id.txt_time);
            txtNoticeWind= itemView.findViewById(R.id.txt_notice_wind);
            txtNoticeAddress=  itemView.findViewById(R.id.txt_notice_title);
            txtNoticeWeather =  itemView.findViewById(R.id.txt_notice_weather);
            txtNoticeTemp =  itemView.findViewById(R.id.txt_notice_temp);
            txtNoticeHumidity =  itemView.findViewById(R.id.txt_notice_humidity);
            txtNoticePressure =  itemView.findViewById(R.id.txt_notice_pressure);
            txtNoticeTempMain =  itemView.findViewById(R.id.txt_notice_temp_main);
        }
    }

This is my recyclerview
This works only when network is enabled

The question is how to set this data right from RecyclerView (or other way) to my Room DataBase when network is enabled by Onclick SaveButton to create other recyclerview and set data there, to get it offline later.

I'm trying to create Entity

  @Entity
    public class WeatherData {
        @PrimaryKey(autoGenerate = true)
        private long id;
        private String address;
        private Double windSpeed;
        private Integer windDegree;
        private String datalistIcon;
        private String datalistInfo;
        private String datalistWeather;
        private Double mainTemp;
        private Double mainFeel;
        private Integer mainHumidity;
        private Integer mainPressure;
        private String time;
        private Double locLat;
        private Double locLon;
        public WeatherData(){}
        @Ignore
        public WeatherData(String address, Double windSpeed, Integer windDegree, String datalistIcon,String datalistInfo,String datalistWeather, Double mainTemp,Double mainFeel,Integer mainHumidity,Integer mainPressure,String time,LatLng currentLocation,Double locLat,Double locLon) {
            this.address = address;
            this.windSpeed = windSpeed;
            this.windDegree = windDegree;
            this.datalistIcon=datalistIcon;
            this.datalistInfo=datalistInfo;
            this.datalistWeather=datalistWeather;
            this.mainTemp=mainTemp;
            this.mainFeel=mainFeel;
            this.mainHumidity=mainHumidity;
            this.mainPressure=mainPressure;
            this.time=time;
            this.locLat=locLat;
            this.locLon=locLon;
        }

Dao

@Dao
public interface WeatherDataDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void saveAll(List<WeatherData> weathers);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void save(WeatherData weather);

    @Update
    void update(WeatherData weather);

    @Delete
    void delete(WeatherData weather);

    @Query("SELECT * FROM WeatherData")
    LiveData<List<WeatherData>> findAll();
}

and DataBase

  @Database(entities = {WeatherData.class}, version = 1)
    public abstract class WeatherDatabase extends RoomDatabase {
        public static WeatherDatabase INSTANCE;
        public abstract WeatherDataDao weatherDao();
        private static final Object sLock = new Object();
        public static WeatherDatabase getInstance(Context context) {
            synchronized (sLock) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            WeatherDatabase.class, "Weathers.db")
                            .allowMainThreadQueries()
                            .build();
                }
                return INSTANCE;
            }
        }

Which way do I need to create it?

Body:
Create an @Entity Notice which is your data type to be stored in your Room DB.

Create a View Model which is attached to your Activity/Fragment where you need to show this list.

Use your ViewModel to store the list from API into your Room DB.

Create a LiveData which observes on the DB and sends the updated list to the other view.

Code for Saving Data in DB. This needs to be run on Background Thread.

public static void saveNoticeList(Context context, List<Notice> noticeList) {
     if (context != null && noticeList != null) {
         RoomDatabaseCreator.getInstance(context)
                 .getDatabase()
                 .noticeDao()
                 .saveNotices(noticeList);
     }
 }

// For Saving in background you can use RxJava, I am using a new thread for simplification

backgroundHandler.post(() -> {
            saveNoticeList(getActivity(), dataList);
        });

ViewModel

public class NoticeViewModel extends AndroidViewModel {
    public MutableLiveData<List<Notice>> mNoticesLiveData = new MutableLiveData<>();

    private Context mContext;

    public NoticeViewModel(final Application application) {
        super(application);
        mContext = application.getApplicationContext();

        mNoticesLiveData = Transformations.switchMap(databaseCreated,
                (Function<Boolean, LiveData<List<Notice>>) isDbCreated -> {
                    if (!Boolean.TRUE.equals(isDbCreated)) { // Not needed here, but watch out for null
                        //noinspection unchecked
                        return ABSENT;
                    } else {
                            return databaseCreator.getDatabase()
                                    .noticedao()
                                    .getSavedNotices();
                        }
                    }
                });

    public LiveData<List<Notice> getNoticeLiveData() {
        return mNoticesLiveData;
    }
}

Activity Code where you need to show the saved data

//1. Initialize the viewModel
NoticeViewModel viewModel = ViewModelProviders.of(this).get(NoticeViewModel.class);

//2. Subscribe to the saved notices live-data to get updates in your view
viewModel.getNoticeLiveData().observe(this
       list -> {
                if (list.isEmpty()) {
                       return;
                }

                // Add the list in your adapter

            });


问:
mypy: How to define return value as a list of sub-class instances
I'am trying to define a return value of method foo as a list of AbstractChild sub-class instances, but mypy keeps giving me an error.

class AbstractParent(ABC):
    @abstractmethod
    def foo(self) -> List["AbstractChild"]: pass

class AbstractChild(ABC):
    pass

class Parent(AbstractParent):
    def foo(self) -> List["Child"]: pass
#   ^ mypy: error Return type "List[Child]" of "foo" incompatible with return type "List[AbstractChild]" in supertype "AbstractParent"

class Child(AbstractChild):
    pass
```

Changing the return type from the list to a single value will make mypy to stop complaining which I find quite strange, but I'm still getting used to python type system so I might be missing something.

答:
mypy is correct here because your Parent doesn't implement AbstractParent correctly - to do that, it should define a method foo that returns a list of AbstractChildren, not Children. This is because collections are not polymorphic (and this is true for other languages too, e.g. Java): List[AbstractChild] is not the same type as List[Child], and List[Child] doesn't inherit from List[AbstractChild] just because Child does. If we wouldn't have this restriction, errors like this would be possible:

```<code>class AbstractChild(ABC):
    pass

class Child(AbstractChild):
    pass

class GrandChild(AbstractChild):
    pass

grandchildren: List[GrandChild] = [GrandChild()]
all_children: List[AbstractChild] = grandchildren
all_children.append(Child())
grandchild: GrandChild = grandchildren[0]  # would pass typechecks but is a Child, actually
</code>```

(this is a rephrased example of Jon Skeet's answer for a similar question in Java).

Java, for example, catches this type of errors at compilation and requires explicit covariance, e.g. List<? extends Child> for reading from and List<? super Child> for writing to the list.

In your case, you would introduce a generic type as well. In the example below, I change AbstractParent to return a List of elements having the same type C that can be anything that subclasses AbstractChild, and Parent is a concrete implementation of the generic AbstractChild with concrete child type Child:

```<code>from typing import List, TypeVar, Generic

C = TypeVar('C', bound='AbstractChild')

class AbstractParent(ABC, Generic[C]):
    @abstractmethod
    def foo(self) -> List[C]: pass

class Parent(AbstractParent["Child"]):
    def foo(self) -> List["Child"]:
        return []
</code>```

For more examples, check out the Generics chapter from mypy docs, in particular the Variance of generic types section.

Body:
I'am trying to define a return value of method foo as a list of AbstractChild sub-class instances, but mypy keeps giving me an error.

class AbstractParent(ABC):
    @abstractmethod
    def foo(self) -> List["AbstractChild"]: pass

class AbstractChild(ABC):
    pass

class Parent(AbstractParent):
    def foo(self) -> List["Child"]: pass
#   ^ mypy: error Return type "List[Child]" of "foo" incompatible with return type "List[AbstractChild]" in supertype "AbstractParent"

class Child(AbstractChild):
    pass

Changing the return type from the list to a single value will make mypy to stop complaining which I find quite strange, but I'm still getting used to python type system so I might be missing something.

Body:
mypy is correct here because your Parent doesn't implement AbstractParent correctly - to do that, it should define a method foo that returns a list of AbstractChildren, not Children. This is because collections are not polymorphic (and this is true for other languages too, e.g. Java): List[AbstractChild] is not the same type as List[Child], and List[Child] doesn't inherit from List[AbstractChild] just because Child does. If we wouldn't have this restriction, errors like this would be possible:

class AbstractChild(ABC):
    pass

class Child(AbstractChild):
    pass

class GrandChild(AbstractChild):
    pass

grandchildren: List[GrandChild] = [GrandChild()]
all_children: List[AbstractChild] = grandchildren
all_children.append(Child())
grandchild: GrandChild = grandchildren[0]  # would pass typechecks but is a Child, actually

(this is a rephrased example of Jon Skeet's answer for a similar question in Java).

Java, for example, catches this type of errors at compilation and requires explicit covariance, e.g. List<? extends Child> for reading from and List<? super Child> for writing to the list.

In your case, you would introduce a generic type as well. In the example below, I change AbstractParent to return a List of elements having the same type C that can be anything that subclasses AbstractChild, and Parent is a concrete implementation of the generic AbstractChild with concrete child type Child:

from typing import List, TypeVar, Generic

C = TypeVar('C', bound='AbstractChild')

class AbstractParent(ABC, Generic[C]):
    @abstractmethod
    def foo(self) -> List[C]: pass

class Parent(AbstractParent["Child"]):
    def foo(self) -> List["Child"]:
        return []

For more examples, check out the Generics chapter from mypy docs, in particular the Variance of generic types section.


问:
Swift Encodable Array of Objects
I am trying to render a Swift Encodable struct to the following JSON:

```<code>{
   "userID": 1000142,
   "emergencyContactData": {"contact":
       [
           {"firstName": "John"},
           {"lastName": "Doe"},
           {"email": "john.doe567@gmail.com"},
           {"phone": "12345678901"}
       ]
   }
}
</code>```

I tried the following:

```<code>struct UserEmergencyContactRequest: Encodable {
    var userID: String
    var ecData: EmergencyContactData
}

struct EmergencyContactData: Encodable {
    var contact: [[String: String]]
}
</code>```

However, the individual String: String dictionary entries do not render to a JSON object (no curly braces).  How would I alter the [String: String] entry so that when I render it to a JSON structure, the individual String: String values would be enclosed in a set of JSON curly braces?

Note: No, I cannot alter the service to accept a better format, dealing with a legacy service.

答:
The structures are correct

I think the problem is in the way you are populating your structs (not shown in your question).

The error

This is the wrong code that I guess you are using.

Specifically the error is in the way you are populating the dictionaries value. Infact you are creating a an array with a single dictionary having all the values. Instead you should create an array of dictionaries where each dictionary has 1 single entry.

```<code>let dictionaries = [["firstName" : "John", "lastName": "Doe", "email": "john.doe567@gmail.com", "phone": "12345678901"]]
let ecData = EmergencyContactData(contact: dictionaries)
let elm = UserEmergencyContactRequest(userID: "userID", ecData: ecData)

if
    let data = try? JSONEncoder().encode(elm),
    let string = String(data: data, encoding: .utf8) {
    print(string)
}

{"userID":"userID","ecData":{"contact":[{"email":"john.doe567@gmail.com","firstName":"John","lastName":"Doe","phone":"12345678901"}]}}
</code>```

The fix

As said above, let's try to put 1 single entry into each dictionary.

```<code>let dictionaries = [["firstName" : "John"], ["lastName": "Doe"], ["email": "john.doe567@gmail.com"], ["phone": "12345678901"]]

let ecData = EmergencyContactData(contact: dictionaries)
let elm = UserEmergencyContactRequest(userID: "userID", ecData: ecData)

if  let data = try? JSONEncoder().encode(elm),
    let string = String(data: data, encoding: .utf8) {
    print(string)
}
</code>```

Now we get the expected result.

```<code>{"userID":"userID","ecData":{"contact":[{"firstName":"John"},{"lastName":"Doe"},{"email":"john.doe567@gmail.com"},{"phone":"12345678901"}]}}
</code>```

Title: Swift Encodable Array of Objects

Body:
I am trying to render a Swift Encodable struct to the following JSON:

{
   "userID": 1000142,
   "emergencyContactData": {"contact":
       [
           {"firstName": "John"},
           {"lastName": "Doe"},
           {"email": "john.doe567@gmail.com"},
           {"phone": "12345678901"}
       ]
   }
}

I tried the following:

struct UserEmergencyContactRequest: Encodable {
    var userID: String
    var ecData: EmergencyContactData
}

struct EmergencyContactData: Encodable {
    var contact: [[String: String]]
}

However, the individual String: String dictionary entries do not render to a JSON object (no curly braces).  How would I alter the [String: String] entry so that when I render it to a JSON structure, the individual String: String values would be enclosed in a set of JSON curly braces?

Note: No, I cannot alter the service to accept a better format, dealing with a legacy service.

Body:
The structures are correct

I think the problem is in the way you are populating your structs (not shown in your question).

The error

This is the wrong code that I guess you are using.

Specifically the error is in the way you are populating the dictionaries value. Infact you are creating a an array with a single dictionary having all the values. Instead you should create an array of dictionaries where each dictionary has 1 single entry.

let dictionaries = [["firstName" : "John", "lastName": "Doe", "email": "john.doe567@gmail.com", "phone": "12345678901"]]
let ecData = EmergencyContactData(contact: dictionaries)
let elm = UserEmergencyContactRequest(userID: "userID", ecData: ecData)

if
    let data = try? JSONEncoder().encode(elm),
    let string = String(data: data, encoding: .utf8) {
    print(string)
}

{"userID":"userID","ecData":{"contact":[{"email":"john.doe567@gmail.com","firstName":"John","lastName":"Doe","phone":"12345678901"}]}}

The fix

As said above, let's try to put 1 single entry into each dictionary.

let dictionaries = [["firstName" : "John"], ["lastName": "Doe"], ["email": "john.doe567@gmail.com"], ["phone": "12345678901"]]

let ecData = EmergencyContactData(contact: dictionaries)
let elm = UserEmergencyContactRequest(userID: "userID", ecData: ecData)

if  let data = try? JSONEncoder().encode(elm),
    let string = String(data: data, encoding: .utf8) {
    print(string)
}

Now we get the expected result.

{"userID":"userID","ecData":{"contact":[{"firstName":"John"},{"lastName":"Doe"},{"email":"john.doe567@gmail.com"},{"phone":"12345678901"}]}}


问:
Custom loss function for predicting interget outputs?
I'm currenly working on a dataset where I've to predict an integer output. It starts from 1 to N. I've build a network with loss function mse. But I feel like mse loss function may not be an ideal loss function to minimize in the case of integer output.

I'm also round my prediction to get integer output. Is there a way to make/optimize the model better in case of integer output.

Can anyone provide some help on how to deal with integer output/targets. This is the loss function I'm using right now.

```<code>model.compile(optimizer=SGD(0.001), loss='mse')
</code>```

答:
Ordinal regression could be an appropriate approach, in case predicting the wrong month but close to the true month is considered a smaller mistake than predicting a value one year earlier or later. Only you can know that, based on the specific problem you want to solve.

I found an implementation of the appropriate loss function on github (no affiliation). For completeness, below I copy-paste the code from that repo:

```<code>from keras import backend as K
from keras import losses

def loss(y_true, y_pred):
    weights = K.cast(
        K.abs(K.argmax(y_true, axis=1) - K.argmax(y_pred, axis=1))/(K.int_shape(y_pred)[1] - 1),
        dtype='float32'
    )
    return (1.0 + weights) * losses.categorical_crossentropy(y_true, y_pred)
</code>```

Body:
I'm currenly working on a dataset where I've to predict an integer output. It starts from 1 to N. I've build a network with loss function mse. But I feel like mse loss function may not be an ideal loss function to minimize in the case of integer output.

I'm also round my prediction to get integer output. Is there a way to make/optimize the model better in case of integer output.

Can anyone provide some help on how to deal with integer output/targets. This is the loss function I'm using right now.

model.compile(optimizer=SGD(0.001), loss='mse')

Body:
Ordinal regression could be an appropriate approach, in case predicting the wrong month but close to the true month is considered a smaller mistake than predicting a value one year earlier or later. Only you can know that, based on the specific problem you want to solve.

I found an implementation of the appropriate loss function on github (no affiliation). For completeness, below I copy-paste the code from that repo:

from keras import backend as K
from keras import losses

def loss(y_true, y_pred):
    weights = K.cast(
        K.abs(K.argmax(y_true, axis=1) - K.argmax(y_pred, axis=1))/(K.int_shape(y_pred)[1] - 1),
        dtype='float32'
    )
    return (1.0 + weights) * losses.categorical_crossentropy(y_true, y_pred)


问:
How to push data from BMC Remedy to Spring Boot application?
Let me start by saying I have ZERO remedy experience.

We need to push data from Remedy to a Spring Boot application. I have looked at many, many, many examples, but all seem to be connecting to Remedy via Java and requesting data.

I have seen code examples using Java Filter Plugin for Remedy which seems like the correct way to go.

What will be best way to implement this or maybe there is another way?

A Remedy Plugin(which I will develop) to call a Java RESTController in Spring Boot Application. Do I simply hardcode the RESTController URL into my code here? I know how to do this, but not sure if it is the best way.

Use JMS to send a message from Remedy to Spring Boot Application. We will not specify an ActiveMQ installation so Spring Boot activemq will start its own internal one. Which URL's do I use for communication?

Apache Camel maybe?

So basically Remedy will send me a unique id, I will then use this ID, connect back to Remedy and retrieve more information. This I know how to do.

Sorry, but I really need some help here regarding the integration between the two and how to push data from Remedy to Spring Boot. That is actually the main question.

答:
I do not know if this is still relevant, but here is my five cents worth.

There are two ways of using the Java API to send events out of Remedy:

An AR Filter Plugin. This will be triggerable in workflow, any time a filter (server side event), either triggered by a client side action (form submission, update or retrieval), or by an escalation (scheduled event). You can theoretically trigger any Java events like communication via MQ or JMS, or your REST call, but I beleive these are mostly fire and forget.

An ARDBC plugin. This requires you to write workflow pushing to this filter. This can either use a JDBC connection to a database, or another technology like MQ or JMS. You could in theory put a REST interface at the other end, providing the CRUD functions for the plugin. This allows communication both ways, and appears as a "normal" form for remedy workflow. There are built in functions that can be called to get the status of transactions and so on. this gives you the most flexibility.

An ARDBC plugin may be tricky to set up, but may provide the functionality you need.


问:
Ngx-translate giving 404 error Nativescript angular
I'm using Ngx-translate with Nativescript-Angular.
The reason why I'm using ngx-translate is that I need to be able to change the language during runtime.

The error:

```<code>CONSOLE ERROR file:///node_modules/@angular/core/fesm5/core.js:4002:0:ERROR{
   "headers":{
      "normalizedNames":{

      },
      "lazyUpdate":null,
      "headers":{

      }
   },
   "status":404,
   "statusText":"ERROR",
   "url":"/var/mobile/Containers/Data/Application/A1B491BE-90BB-4C1E-BF1D-48C6BC398167/Library/Application Support/LiveSync/app/assets/i18n/ko-KR.json",
   "ok":false,
   "name":"HttpErrorResponse",
   "message":"Http failure response for /var/mobile/Containers/Data/Application/A1B491BE-90BB-4C1E-BF1D-48C6BC398167/Library/Application Support/LiveSync/app/assets/i18n/ko-KR.json: 404 ERROR",
   "error":"Not Found"
}
</code>```

Folder structure:

src

app

app.module.ts

assets

i18n

class

custom-translation.handler.ts

factories

http-loader.factories.ts

app.module.ts

```<code>TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: httpLoaderFactory,
                deps: [HttpClient]
            },
            missingTranslationHandler: {
                provide: MissingTranslationHandler,
                useClass: CustomTranslationHandler
            }
        })

</code>```

custom-translation.handler.ts

```<code>import { MissingTranslationHandler, MissingTranslationHandlerParams } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/internal/operators';

export class CustomTranslationHandler implements MissingTranslationHandler {
    handle(params: MissingTranslationHandlerParams): string | Observable<string> {
        const defaultContext = '@COMMON';
        const missingContext = 'TRANSLATE:';
        const translationKeyArray = params.key.split('.');

        if (
            translationKeyArray[0] === defaultContext ||
            translationKeyArray[1] === missingContext
        ) {
            return params.key;
        }

        translationKeyArray[0] = defaultContext;
        const newTranslationKey = translationKeyArray.join('.');
        return params.translateService
            .get(newTranslationKey, params.interpolateParams)
            .pipe(
                map(v => (v === newTranslationKey ? missingContext + params.key : v))
            );
    }
}

</code>```

http-loader.factories.ts

```<code>import { HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function httpLoaderFactory(http: HttpClient): TranslateHttpLoader {
    return new TranslateHttpLoader(http, '/assets/i18n/', '.json');
}

</code>```

Example translation in a component:

<Button text="{{ tc + '.CONFIRM' | translate }}"></Button>

Where tc is equal to START-UP

The setup of my i18n.json file:

```<code>{
    "@COMMON": {
        "TITLE": "확정하다"
    },
    "START-UP": {
        "CONFIRM": "확정하다"
    }
}

</code>```

WebpackConfig

```<code>new CopyWebpackPlugin([
                { from: { glob: "fonts/**" } },
                { from: { glob: "**/*.+(jpg|png)" } },
                { from: { glob: "assets/**/*" } },
            ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),

</code>```

答:
I think absolute path not work correctly in TranslateHttpLoader.

Try to use relative path like this: TranslateHttpLoader(http, './assets/i18n/');

Body:
I'm using Ngx-translate with Nativescript-Angular.
The reason why I'm using ngx-translate is that I need to be able to change the language during runtime.

The error:

CONSOLE ERROR file:///node_modules/@angular/core/fesm5/core.js:4002:0:ERROR{
   "headers":{
      "normalizedNames":{

      },
      "lazyUpdate":null,
      "headers":{

      }
   },
   "status":404,
   "statusText":"ERROR",
   "url":"/var/mobile/Containers/Data/Application/A1B491BE-90BB-4C1E-BF1D-48C6BC398167/Library/Application Support/LiveSync/app/assets/i18n/ko-KR.json",
   "ok":false,
   "name":"HttpErrorResponse",
   "message":"Http failure response for /var/mobile/Containers/Data/Application/A1B491BE-90BB-4C1E-BF1D-48C6BC398167/Library/Application Support/LiveSync/app/assets/i18n/ko-KR.json: 404 ERROR",
   "error":"Not Found"
}

Folder structure:

src

app

app.module.ts

assets

i18n

class

custom-translation.handler.ts

factories

http-loader.factories.ts

app.module.ts

TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: httpLoaderFactory,
                deps: [HttpClient]
            },
            missingTranslationHandler: {
                provide: MissingTranslationHandler,
                useClass: CustomTranslationHandler
            }
        })

custom-translation.handler.ts

import { MissingTranslationHandler, MissingTranslationHandlerParams } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/internal/operators';

export class CustomTranslationHandler implements MissingTranslationHandler {
    handle(params: MissingTranslationHandlerParams): string | Observable<string> {
        const defaultContext = '@COMMON';
        const missingContext = 'TRANSLATE:';
        const translationKeyArray = params.key.split('.');

        if (
            translationKeyArray[0] === defaultContext ||
            translationKeyArray[1] === missingContext
        ) {
            return params.key;
        }

        translationKeyArray[0] = defaultContext;
        const newTranslationKey = translationKeyArray.join('.');
        return params.translateService
            .get(newTranslationKey, params.interpolateParams)
            .pipe(
                map(v => (v === newTranslationKey ? missingContext + params.key : v))
            );
    }
}

http-loader.factories.ts

import { HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function httpLoaderFactory(http: HttpClient): TranslateHttpLoader {
    return new TranslateHttpLoader(http, '/assets/i18n/', '.json');
}

Example translation in a component:

<Button text="{{ tc + '.CONFIRM' | translate }}"></Button>

Where tc is equal to START-UP

The setup of my i18n.json file:

{
    "@COMMON": {
        "TITLE": "확정하다"
    },
    "START-UP": {
        "CONFIRM": "확정하다"
    }
}

WebpackConfig

new CopyWebpackPlugin([
                { from: { glob: "fonts/**" } },
                { from: { glob: "**/*.+(jpg|png)" } },
                { from: { glob: "assets/**/*" } },
            ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),


问:
What is your favorite C programming trick?
For example, I recently came across this in the linux kernel:

```
/* Force a compilation error if condition is true */
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
```

So, in your code, if you have some structure which must be, say a multiple of 8 bytes in size, maybe because of some hardware constraints, you can do:

```
BUILD_BUG_ON((sizeof(struct mystruct) % 8) != 0);
```

and it won't compile unless the size of struct mystruct is a multiple of 8, and if it is a multiple of 8, no runtime code is generated at all.

Another trick I know is from the book "Graphics Gems" which allows a single header file to both declare and initialize variables in one module while in other modules using that module, merely declare them as externs.

```
#ifdef DEFINE_MYHEADER_GLOBALS
#define GLOBAL
#define INIT(x, y) (x) = (y)
#else
#define GLOBAL extern
#define INIT(x, y)
#endif

GLOBAL int INIT(x, 0);
GLOBAL int somefunc(int a, int b);
```

With that, the code which defines x and somefunc does:

```
#define DEFINE_MYHEADER_GLOBALS
#include "the_above_header_file.h"
```

while code that's merely using x and somefunc() does:

```
#include "the_above_header_file.h"
```

So you get one header file that declares both instances of globals and function prototypes where they are needed, and the corresponding extern declarations.

So, what are your favorite C programming tricks along those lines?

答:
Declaring array's of pointer to functions for implementing finite state machines.

```<code>int (* fsm[])(void) = { ... }
</code>```

The most pleasing advantage is that it is simple to force each stimulus/state to check all code paths.

In an embedded system, I'll often map an ISR to point to such a table and revector it as needed (outside the ISR).

OwnerDisplayName: smcameron

ContentLicense: CC BY-SA 2.5

Body:
For example, I recently came across this in the linux kernel:

/* Force a compilation error if condition is true */
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))

So, in your code, if you have some structure which must be, say a multiple of 8 bytes in size, maybe because of some hardware constraints, you can do:

BUILD_BUG_ON((sizeof(struct mystruct) % 8) != 0);

and it won't compile unless the size of struct mystruct is a multiple of 8, and if it is a multiple of 8, no runtime code is generated at all.

Another trick I know is from the book "Graphics Gems" which allows a single header file to both declare and initialize variables in one module while in other modules using that module, merely declare them as externs.

#ifdef DEFINE_MYHEADER_GLOBALS
#define GLOBAL
#define INIT(x, y) (x) = (y)
#else
#define GLOBAL extern
#define INIT(x, y)
#endif

GLOBAL int INIT(x, 0);
GLOBAL int somefunc(int a, int b);

With that, the code which defines x and somefunc does:

#define DEFINE_MYHEADER_GLOBALS
#include "the_above_header_file.h"

while code that's merely using x and somefunc() does:

#include "the_above_header_file.h"

So you get one header file that declares both instances of globals and function prototypes where they are needed, and the corresponding extern declarations.

So, what are your favorite C programming tricks along those lines?

LastEditorDisplayName: cletus

Body:
Declaring array's of pointer to functions for implementing finite state machines.

int (* fsm[])(void) = { ... }

The most pleasing advantage is that it is simple to force each stimulus/state to check all code paths.

In an embedded system, I'll often map an ISR to point to such a table and revector it as needed (outside the ISR).

OwnerDisplayName: Jamie


问:
Tail file that does not start with symbol
I have set of raw csv files that have comment headers (# symbol) in addition to column names. Like this:

```<code># This data is taken from ....
# ...
# ...
# ...
# col1,col2,...,coln
#
[csv data rows starts here]
</code>```

The number of lines above the row containing the column names is not fixed per file.

How to 'cut' the file (create a new file) that will output a standard CSV format?

```<code>col1,col2,...,coln
[csv data rows starts here]
</code>```

I am using Jupyter notebook to do some data wrangling, so I am interested in doing this both using the inline shell script (using tail perhaps) and Python.

答:
A Python version that should work in your Jupyter notebook is below. You'd need to replace <file_name>s listed in the line file_names = ["<file_name1>","<file_name2>"] with yours.

import os
import sys
import pandas as pd
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

def mine_header(fn):
    '''
    To answer https://stackoverflow.com/q/60249235/8508004

    Takes a file name as input

    Assumes last commented line with contents before the data rows start
    contains the column names. Could be condensed, to read in all text once and
    then rsplit on last `#` but going line by line at start offers more
    opportunity for customizing later if not quite matching pattern seen in
    data files. Also could just assume second last line above the data contains
    the column names? In that case, could skip
    `header = [x for x in header if x]` line and use
    `col_names = header[-2].split(",")` instead.

    Returns list of column names and rest of contents of csv file beyond
    header.
    '''
    # first copy the input file that will be parsed line by to a new file so
    # can parse contents while possibly overwriting the input file with a
    # shorter version if a label for a set encountered inside it
    beyond_header = False
    header = [] # collect the header lines
    data_rows = "" # collect the data rows
    # go through the file line by line until beyond commented out header
    with open(fn, 'r') as input:
        for line in input:
            if beyond_header:
                data_rows += line
            elif line.startswith("#"):
                header.append(line[1:].strip()) # leave off comment symbol and
                # remove any leadding and trailing whitespace
            # If line doesn't start with comment symbol, have hit the end of
            # the header and want to start collecting the csv data tows
            else:
                data_rows += line
                beyond_header = False
    # Now process the header lines to get the column names.
    header = [x for x in header if x]# The last row before the data should be
    # empty now and so that list comprehension should remove it leaving last row
    # as the one with the column names
    col_names = header[-1].split(",")
    return col_names, data_rows

file_names = ["<file_name1>","<file_name2>"]
df_dict = {}
for i,fn in enumerate(file_names):
    col_names, data_rows = mine_header(fn)
    df_dict[i] = pd.read_csv(StringIO(data_rows), header=0, names=col_names)

# display the produced dataframes
from IPython.display import display, HTML
for df in df_dict:
    display(df)
```

<p>A pandas dataframe for each is accessible by index matching the list of files you made. For example, the dataframe made from the third csv file would be <code>df_dict[2]</code>.</p>

<p>I kind of took it beyond what you asked since splitting the columns to a list was easy to design into the mining function and Pandas is set up to deal with everything thereafter.<br>
If you really wanted to make the output as standard CSV, you could use <code>col_names</code> and <code>data_rows</code> returned by <code>col_names, data_rows = mine_header(fn)</code> and save a CSV file as well. You'd combine them to make a string to save like so:</p>

<pre class="lang-py prettyprint-override"><code>col_names_as_string = ",".join(col_names)
string_to_save = col_names_as_string + "\n" + data_rows
</code>```

Body:
I have set of raw csv files that have comment headers (# symbol) in addition to column names. Like this:

# This data is taken from ....
# ...
# ...
# ...
# col1,col2,...,coln
#
[csv data rows starts here]

The number of lines above the row containing the column names is not fixed per file.

How to 'cut' the file (create a new file) that will output a standard CSV format?

col1,col2,...,coln
[csv data rows starts here]

I am using Jupyter notebook to do some data wrangling, so I am interested in doing this both using the inline shell script (using tail perhaps) and Python.

Body:
A Python version that should work in your Jupyter notebook is below. You'd need to replace <file_name>s listed in the line file_names = ["<file_name1>","<file_name2>"] with yours.

import os
import sys
import pandas as pd
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

def mine_header(fn):
    '''
    To answer https://stackoverflow.com/q/60249235/8508004

    Takes a file name as input

    Assumes last commented line with contents before the data rows start
    contains the column names. Could be condensed, to read in all text once and
    then rsplit on last `#` but going line by line at start offers more
    opportunity for customizing later if not quite matching pattern seen in
    data files. Also could just assume second last line above the data contains
    the column names? In that case, could skip
    `header = [x for x in header if x]` line and use
    `col_names = header[-2].split(",")` instead.

    Returns list of column names and rest of contents of csv file beyond
    header.
    '''
    # first copy the input file that will be parsed line by to a new file so
    # can parse contents while possibly overwriting the input file with a
    # shorter version if a label for a set encountered inside it
    beyond_header = False
    header = [] # collect the header lines
    data_rows = "" # collect the data rows
    # go through the file line by line until beyond commented out header
    with open(fn, 'r') as input:
        for line in input:
            if beyond_header:
                data_rows += line
            elif line.startswith("#"):
                header.append(line[1:].strip()) # leave off comment symbol and
                # remove any leadding and trailing whitespace
            # If line doesn't start with comment symbol, have hit the end of
            # the header and want to start collecting the csv data tows
            else:
                data_rows += line
                beyond_header = False
    # Now process the header lines to get the column names.
    header = [x for x in header if x]# The last row before the data should be
    # empty now and so that list comprehension should remove it leaving last row
    # as the one with the column names
    col_names = header[-1].split(",")
    return col_names, data_rows

file_names = ["<file_name1>","<file_name2>"]
df_dict = {}
for i,fn in enumerate(file_names):
    col_names, data_rows = mine_header(fn)
    df_dict[i] = pd.read_csv(StringIO(data_rows), header=0, names=col_names)

# display the produced dataframes
from IPython.display import display, HTML
for df in df_dict:
    display(df)

A pandas dataframe for each is accessible by index matching the list of files you made. For example, the dataframe made from the third csv file would be df_dict[2].

I kind of took it beyond what you asked since splitting the columns to a list was easy to design into the mining function and Pandas is set up to deal with everything thereafter.

If you really wanted to make the output as standard CSV, you could use col_names and data_rows returned by col_names, data_rows = mine_header(fn) and save a CSV file as well. You'd combine them to make a string to save like so:

col_names_as_string = ",".join(col_names)
string_to_save = col_names_as_string + "\n" + data_rows