问:
vue multiple dropdown clicks show
I'm a vuejs newbie, I want to do the dropdown, whichever one is clicked, its menu will be opened, I wonder how can I do this?
whichever dropdown is clicked i want the other to close.
and also if I click the link from the "mobile" menu, the mobile class will be closed.

I apologize in advance for having trouble explaining myself.

```<code><template>
    <li>
        <MenuLink
            :link="items"
            :key="items.name"
            @click.stop="clickShow()"
        />
        <ul class="children" v-if="hasChild" :class="open ? 'show' : 'hidden'">
            <MenuItems
                v-for="subItem in items.children"
                :key="subItem.name"
                :items="subItem"
            />
        </ul>
    </li>

</template>
<script>

export default {
    name: 'MenuItems',
    components: {MenuLink},
    props: {
        items: {type: Object, required: true},
        level: {
            type: Number,
            default: 0
        }
    },
data() {
        return {
            childrenCount: 0,
            active: false,
            show: null,
            open: false,
        };
    },
</code>```

答:
One of the ways to achieve that with class binding:

new Vue({
  el: '#demo',
  data() {
    return {
      show: null
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.show {
  display: block;
}
.hide {
  display: none;
}</code>```

    <button @click="show = null">menu</button>

        Home

        About

        Dropdown 1

            Dropdown 1.1
            Dropdown 1.2

        Contact

        Dropdown 2

            Dropdown 2.1
            Dropdown 2.2

```

Title: vue multiple dropdown clicks show

Body:
I'm a vuejs newbie, I want to do the dropdown, whichever one is clicked, its menu will be opened, I wonder how can I do this?
whichever dropdown is clicked i want the other to close.
and also if I click the link from the "mobile" menu, the mobile class will be closed.

I apologize in advance for having trouble explaining myself.

<template>

        <MenuLink
            :link="items"
            :key="items.name"
            @click.stop="clickShow()"
        />

            <MenuItems
                v-for="subItem in items.children"
                :key="subItem.name"
                :items="subItem"
            />

</template>

Body:
One of the ways to achieve that with class binding:

new Vue({
  el: '#demo',
  data() {
    return {
      show: null
    }
  }
})

.show {
  display: block;
}
.hide {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div class="mobil" >
    <button @click="show = null">menu</button>
    <ul :class="show === 0 ? 'hide' : 'show'" @click="show = 0">
      <li>
        <a href="#/home">Home</a>
      </li>
      <li>
        <a href="#/about">About</a>
      </li>
      <li>
        <a @click.stop="show = 1" href="#">Dropdown 1</a>
        <ul :class="show === 1 ? 'show' : 'hide'">
          <li>
            <a href="#/dropdown11">Dropdown 1.1</a>
            <a href="#/dropdown12">Dropdown 1.2</a>
          </li>
        </ul>
      </li>
      <li>
        <a href="#/contact">Contact</a>
      </li>
      <li>
        <a @click.stop="show = 2" href="#">Dropdown 2</a>
        <ul :class="show === 2 ? 'show' : 'hide'">
          <li>
            <a href="#/dropdown21">Dropdown 2.1</a>
            <a href="#/dropdown22">Dropdown 2.2</a>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div>


来源: stackexchange

问:
Apache Camel - Split and aggregate - Old Exchange is always null
I see that this question has been asked a number of times but none of post helped or had a conclusive solution. I am splitting a message and then aggregating it using Aggregator2. The code was throwing exception because oldExchange was always null. So to test I designed a small code.

I read an orders,xml file which looks like this

```<code><Orders xmlns="http://some/schema/Order">
    <Order>
            <orderNum>1</orderNum>
    </Order>
    <Order>
            <orderNum>2</orderNum>
    </Order>
    <Order>
            <orderNum>3</orderNum>
    </Order>
    <Order>
            <orderNum>5</orderNum>
    </Order>
    <Order>
            <orderNum>6</orderNum>
    </Order>
</code>```

My camel Context Looks like this

```<code><camel:route>
<camel:from uri="file:src/data/catask/test?noop=true"/>
<camel:log message="${body}"></camel:log>
<camel:split>
<camel:xpath>//te:Orders/*</camel:xpath>
<camel:to uri="direct:logQueries"/>
<camel:to uri="direct:aggegateQueries"/>
</camel:split>

</camel:route>

<camel:route>
<camel:from uri="direct:logQueries"/>
<camel:log message="After the call : \n ${body}"></camel:log>
</camel:route>

 <camel:route>
<camel:from uri="direct:aggegateQueries"/>
<camel:aggregate strategyRef="aggrTask" completionInterval="8000" >
<camel:correlationExpression>
<camel:xpath>//te:Order</camel:xpath>
</camel:correlationExpression>
<camel:to uri="file:src/data/catask/output?fileName=output.xml"/>

</camel:aggregate>
</camel:route>
</code>```

My Aggregation Strategy class looks like this

```<code>   public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
            if (oldExchange == null) {
            System.out.println("Returning new exchange");
                return newExchange;
            }

            String oldBody = oldExchange.getIn().getBody(String.class);
            String newBody = newExchange.getIn().getBody(String.class);
            oldExchange.getIn().setBody(oldBody + "+" + newBody);
            return oldExchange;
        }
</code>```

The problem is that when the aggregated result is saved in output.xml file it contains only the last record it read from Orders.xml.

i.e.

```<code><Order xmlns="http://some/schema/Order">
            <orderNum>6</orderNum>
    </Order>
</code>```

I looked into it further and found that this was happening because after the first call oldExchange should have some value but it turns out it is always null. I think that because it is reading everything from a single file and splitting it, there is only exchange.

> Any suggestions??

UPDATE 1: Per Claus I can use Splitter only to solve this issue. I did that and was able to successfully join all the messages. However I am still looking for a way to use Aggregator2. Here how I did it using Splitter only.

```<code>camel:route>
<camel:from uri="file:src/data/catask/test?noop=true"/>
<camel:log message="${body}"></camel:log>
<camel:split strategyRef="aggrTask">
<camel:xpath>//te:Orders/*</camel:xpath>
<camel:to uri="direct:logQueries"/>
 <
</camel:split>

</camel:route>

<camel:route>
<camel:from uri="direct:logQueries"/>
<camel:log message="After the call : \n ${body}"></camel:log>
</camel:route>
</code>```

答:
```<code><camel:correlationExpression>
  <simple>header.id</simple>
</camel:correlationExpression>
</code>```

could be replaced by:

```<code><!-- Required! The expression to retrieve the correlation key. When no key the constant true could be used. -->
<camel:correlationExpression>
  <constant>true</constant>
</camel:correlationExpression>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I see that this question has been asked a number of times but none of post helped or had a conclusive solution. I am splitting a message and then aggregating it using Aggregator2. The code was throwing exception because oldExchange was always null. So to test I designed a small code.

I read an orders,xml file which looks like this

<Orders xmlns="http://some/schema/Order">
    <Order>
            <orderNum>1</orderNum>
    </Order>
    <Order>
            <orderNum>2</orderNum>
    </Order>
    <Order>
            <orderNum>3</orderNum>
    </Order>
    <Order>
            <orderNum>5</orderNum>
    </Order>
    <Order>
            <orderNum>6</orderNum>
    </Order>

My camel Context Looks like this

<camel:route>
<camel:from uri="file:src/data/catask/test?noop=true"/>
<camel:log message="${body}"></camel:log>
<camel:split>
<camel:xpath>//te:Orders/*</camel:xpath>
<camel:to uri="direct:logQueries"/>
<camel:to uri="direct:aggegateQueries"/>
</camel:split>

</camel:route>

<camel:route>
<camel:from uri="direct:logQueries"/>
<camel:log message="After the call : \n ${body}"></camel:log>
</camel:route>

 <camel:route>
<camel:from uri="direct:aggegateQueries"/>
<camel:aggregate strategyRef="aggrTask" completionInterval="8000" >
<camel:correlationExpression>
<camel:xpath>//te:Order</camel:xpath>
</camel:correlationExpression>
<camel:to uri="file:src/data/catask/output?fileName=output.xml"/>

</camel:aggregate>
</camel:route>

My Aggregation Strategy class looks like this

   public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
            if (oldExchange == null) {
            System.out.println("Returning new exchange");
                return newExchange;
            }

            String oldBody = oldExchange.getIn().getBody(String.class);
            String newBody = newExchange.getIn().getBody(String.class);
            oldExchange.getIn().setBody(oldBody + "+" + newBody);
            return oldExchange;
        }

The problem is that when the aggregated result is saved in output.xml file it contains only the last record it read from Orders.xml.

i.e.

<Order xmlns="http://some/schema/Order">
            <orderNum>6</orderNum>
    </Order>

I looked into it further and found that this was happening because after the first call oldExchange should have some value but it turns out it is always null. I think that because it is reading everything from a single file and splitting it, there is only exchange.

> Any suggestions??

UPDATE 1: Per Claus I can use Splitter only to solve this issue. I did that and was able to successfully join all the messages. However I am still looking for a way to use Aggregator2. Here how I did it using Splitter only.

camel:route>
<camel:from uri="file:src/data/catask/test?noop=true"/>
<camel:log message="${body}"></camel:log>
<camel:split strategyRef="aggrTask">
<camel:xpath>//te:Orders/*</camel:xpath>
<camel:to uri="direct:logQueries"/>
 <
</camel:split>

</camel:route>

<camel:route>
<camel:from uri="direct:logQueries"/>
<camel:log message="After the call : \n ${body}"></camel:log>
</camel:route>

Body:
<camel:correlationExpression>
  <simple>header.id</simple>
</camel:correlationExpression>

could be replaced by:

<!-- Required! The expression to retrieve the correlation key. When no key the constant true could be used. -->
<camel:correlationExpression>
  <constant>true</constant>
</camel:correlationExpression>

ContentLicense: CC BY-SA 4.0


问:
Bootstrap: prevent panel from collapsing on checkbox click
So I've a panel heading which contains some text and a checkbox.
How do I prevent the panel from collapsing when I toggle the checkbox?

```<code><div class="panel-heading panel-heading-fail">
    <div class="panel-title" data-target="#panel_body"
                             data-toggle="collapse" data-parent="#panel_meta"
                             aria-expanded="true">
        <span class="pull-left">
            <input type="checkbox" class="form-check-input" id="exampleCheck1">
        </span>
        Some Text
    </div>
</div>
</code>```

Every time I toggle the checkbox it opens/closes the panel.
How can I prevent it from doing that?

Thanks.

答:
Move the input to outside the 'panel-title' and use a 'd-flex' div to keep it inline:

```<code><div class="panel-heading panel-heading-fail">
  <div class='d-flex'>
    <input type="checkbox" class="custom-chkbox form-check-input" id="exampleCheck1">
    <div class="custom-text panel-title" data-target="#panel_body" data-toggle="collapse" data-parent="#panel_meta" aria-expanded="true">
      Some Text
    </div>
  </div>
</div>
</code>```

Use the 'custom-chkbox'/'custom-text' classes to adjust the checkbox and text as desired.

Body:
So I've a panel heading which contains some text and a checkbox.
How do I prevent the panel from collapsing when I toggle the checkbox?

            <input type="checkbox" class="form-check-input" id="exampleCheck1">

        Some Text

Every time I toggle the checkbox it opens/closes the panel.
How can I prevent it from doing that?

Thanks.

Body:
Move the input to outside the 'panel-title' and use a 'd-flex' div to keep it inline:

<div class="panel-heading panel-heading-fail">
  <div class='d-flex'>
    <input type="checkbox" class="custom-chkbox form-check-input" id="exampleCheck1">
    <div class="custom-text panel-title" data-target="#panel_body" data-toggle="collapse" data-parent="#panel_meta" aria-expanded="true">
      Some Text
    </div>
  </div>
</div>

Use the 'custom-chkbox'/'custom-text' classes to adjust the checkbox and text as desired.


问:
Why don't we use const char* const for constant strings?
The standard way to store a constant string in C++ is to use const char*.
In the interest of precision and correctness, why don't we write const char* const?

Is this just because people are too lazy to write the extra const, or because it really does have some disadvantage?

EDIT: I guess I should have been more clear, I don't need an explanation for what const does in it's various positions, I know that much already. What I wanted to know is why the convention is to write const char* even for variables where you know you are never going to change the pointer. Is it just a matter of taste and style?

答:
A variable of type int can easily be modified by accident, by passing it to a function that takes int&. This is "invisible" at the call site, in the sense that calling a function that takes int& looks the same as calling a function that takes int or const int&. To guard against this, we make the variable const if possible.

With a variable of class type, not only do we have the above issue, but we also might modify it by accident by calling a non-const member function, which looks the same as a call to a const member function. So again, marking the variable const often helps catch bugs like this at compile time.

With const char* variables, it's rare that you'll accidentally modify them by passing them to functions taking const char*& (because such functions are rarely declared), and of course, pointers do not have member functions. Thus, protecting the pointed-to data with const is enough to prevent most unintended modifications. Of course, there could still have an assignment somewhere that changes the value of the pointer variable, but usually you can spot this during code review. If you want to write const char* const anyway, I see no reason not to, but some people will consider it as unnecessary clutter.


问:
Get SLF4J loggers for given package
For my current application, I am attempting to get the loggers for the given package. However, after multiple attempts still I am unable to do that. I will add the sample code block for what I've been trying so far.

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

  private final Logger logger;

  private TestUtils(String thePackageOrLoggerName) {
    ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
    this.logger = iLoggerFactory.getLogger(thePackageOrLoggerName);
  }
</code>```

However, the logger I get from the above code does not work. It has the name attribute with the package I've given but it doesn't contain any loggers within the package. In the above example I am only based on SLF4J and does not relay on Log4j2 or Logback because I want this implementation to be independent of underlying logging framework.

However, I could accomplish what I want to do in my previous attempt but I did use logback-core library. I will also add the code block for that as well for a better understanding of what I am going to do.

```<code>import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;

  private final Logger logger;

  private testUtils(String thePackageOrLoggerName) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    this.logger = context.getLogger(thePackageOrLoggerName);
  }
</code>```

With the above implementation, my logger contains all the logger instances for the given package. I want to accomplish the same behaviour without using the logback-core and only using SLF4J related libraries. Can anyone give me insights to proceed further and it is much appreciated.

答:
Try using lombok instead and add @Slf4j above the class.
Now you can do like:

```<code>LOGGER.info("Text");
LOGGER.getName();
LOGGER...{etc}
</code>```

Will make things super easy.  You just need to add @Slf4j above any class you want a logger in. And it will do the rest for you.

If you only wanted a single logger. You can make a single logger class this way. And just create methods to call the logger inside the class

```<code>@Slf4j
@NoArgsConstructor
@Component
public class TestLogger() {
    public void logWarning(String warn){
        LOGGER.warn(warn);
    }

    public void logError(String error){
        LOGGER.error(error);
    }
}
</code>```

Then just Autowire this class into each area you need it.

All code is untested and was written in the text field provided here.

https://mvnrepository.com/artifact/org.projectlombok/lombok

Title: Get SLF4J loggers for given package

Body:
For my current application, I am attempting to get the loggers for the given package. However, after multiple attempts still I am unable to do that. I will add the sample code block for what I've been trying so far.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

  private final Logger logger;

  private TestUtils(String thePackageOrLoggerName) {
    ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
    this.logger = iLoggerFactory.getLogger(thePackageOrLoggerName);
  }

However, the logger I get from the above code does not work. It has the name attribute with the package I've given but it doesn't contain any loggers within the package. In the above example I am only based on SLF4J and does not relay on Log4j2 or Logback because I want this implementation to be independent of underlying logging framework.

However, I could accomplish what I want to do in my previous attempt but I did use logback-core library. I will also add the code block for that as well for a better understanding of what I am going to do.

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;

  private final Logger logger;

  private testUtils(String thePackageOrLoggerName) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    this.logger = context.getLogger(thePackageOrLoggerName);
  }

With the above implementation, my logger contains all the logger instances for the given package. I want to accomplish the same behaviour without using the logback-core and only using SLF4J related libraries. Can anyone give me insights to proceed further and it is much appreciated.

Body:
Try using lombok instead and add @Slf4j above the class.
Now you can do like:

LOGGER.info("Text");
LOGGER.getName();
LOGGER...{etc}

Will make things super easy.  You just need to add @Slf4j above any class you want a logger in. And it will do the rest for you.

If you only wanted a single logger. You can make a single logger class this way. And just create methods to call the logger inside the class

@Slf4j
@NoArgsConstructor
@Component
public class TestLogger() {
    public void logWarning(String warn){
        LOGGER.warn(warn);
    }

    public void logError(String error){
        LOGGER.error(error);
    }
}

Then just Autowire this class into each area you need it.

All code is untested and was written in the text field provided here.

https://mvnrepository.com/artifact/org.projectlombok/lombok


问:
Presto lag dates, group/partitioned by id
Say that I want to find every time that a client updated their budget.

Here's what my data looks like

```<code>datetime, client_id, new_budget
__________,__________,___________
2022-01-01,1,        ,100
2022-01-01,2,        ,300
2022-01-02,1,        ,80
2022-01-02,2,        ,80

</code>```

And the code I've run.

```<code>SELECT datetime AS dt_1,
       LAG(datetime) OVER (ORDER BY client_id, datetime) AS dt_2,
       client_id,
       new_budget
FROM budget_table
</code>```

What I'm expecting returned will be

```<code>dt_1,      dt_2,      client_id, new_budget
__________,__________,__________,___________
2022-01-01,NULL,      1         , 100
2022-01-02,2022-01-01,1         , 80
2022-01-01,NULL,      2         , 300
2022-01-02,2022-01-01,2         , 80
</code>```

Hence there are NULL values for dt_2 in the first entry of each client_id. I'm not sure what code will accomplish this effect; is a GROUP BY clause will be necessary (or a partition over clause.)

But here's the output to the SQL that I ran

```<code>dt_1,      dt_2,      client_id, new_budget
__________,__________,__________,___________
2022-01-01,NULL,      1         , 100
2022-01-02,2022-01-01,1         , 80
2022-01-01,2022-01-02,2         , 300
2022-01-02,2022-01-01,2         , 80
</code>```

So the huge issue here is that it's not recognizing that the dt_2 should be NULL if the previous row is from a different client_id.

Which syntax is recommended to accomplish this effect?

答:
You need to partition by client_id:

The PARTITION BY clause separates the input rows into different partitions. This is analogous to how the GROUP BY clause separates rows into different groups for aggregate functions. If PARTITION BY is not specified, the entire input is treated as a single partition.

SELECT datetime AS dt_1,
       LAG(datetime) OVER (PARTITION BY client_id ORDER BY datetime) AS dt_2,
       client_id,
       new_budget
FROM budget_table
```

Body:
Say that I want to find every time that a client updated their budget.

Here's what my data looks like

datetime, client_id, new_budget
__________,__________,___________
2022-01-01,1,        ,100
2022-01-01,2,        ,300
2022-01-02,1,        ,80
2022-01-02,2,        ,80

And the code I've run.

SELECT datetime AS dt_1,
       LAG(datetime) OVER (ORDER BY client_id, datetime) AS dt_2,
       client_id,
       new_budget
FROM budget_table

What I'm expecting returned will be

dt_1,      dt_2,      client_id, new_budget
__________,__________,__________,___________
2022-01-01,NULL,      1         , 100
2022-01-02,2022-01-01,1         , 80
2022-01-01,NULL,      2         , 300
2022-01-02,2022-01-01,2         , 80

Hence there are NULL values for dt_2 in the first entry of each client_id. I'm not sure what code will accomplish this effect; is a GROUP BY clause will be necessary (or a partition over clause.)

But here's the output to the SQL that I ran

dt_1,      dt_2,      client_id, new_budget
__________,__________,__________,___________
2022-01-01,NULL,      1         , 100
2022-01-02,2022-01-01,1         , 80
2022-01-01,2022-01-02,2         , 300
2022-01-02,2022-01-01,2         , 80

So the huge issue here is that it's not recognizing that the dt_2 should be NULL if the previous row is from a different client_id.

Which syntax is recommended to accomplish this effect?


问:
htaccess redirecting to files available in the public directory
[ Background ]

This is the structure to my application:

```<code>app/
    controllers/
        ...
    modules/
        ...
    views/
        ...
public/
    css/
        main.css
    images/
        ...
    js/
        ...
    index.php
.htaccess
</code>```

For various reasons (security, organization, etc.) the public application (website) is loaded and displayed by public/index.php At the "root" of my server I have the following .htaccess file:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /BU/cs-602/developer-story/
    RewriteRule ^(\/||index\.*)$ public/index.php [L,QSA]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RedirectMatch ^(/BU/cs-602/developer-story.)([\w\d\s\/\-\:\_%\ ]*\.css)$ $1public/$2 [L]
    RewriteRule ^([\w\d\-\_\/\ ]*)$ public/index.php?p=$1 [L,QSA]
</IfModule>
</code>```

These rules should rewrite/ redirect all requests from the server "root" to public/index.php Since I am developing locally on my development server this project is not actually at the root of my server but is located at /BU/cs-602/developer-story/ This is why I added the RewriteBase rule.

If I remove the RedirectMatch rule everything from an MVC standpoint works:

URLs like http://localhost/BU/cs-602/developer-story or http://localhost/BU/cs-602/developer-story/ become http://localhost/BU/cs-602/developer-story/public/index.php AND URLs like http://localhost/BU/cs-602/developer-story/user/id become http://localhost/BU/cs-602/developer-story/public/index.php?p=user/id.

Here is a live htaccess test.

[ Question ]

How can I fix the .htaccess file or the RedirectMatch rule to redirect request to resources like CSS or JS files? The current rule works in the tester but not on my server unless I remove the RedirectMatch rule.

I would like a URL like http://localhost/BU/cs-602/developer-story/css/main.css to become http://localhost/BU/cs-602/developer-story/public/css/main.css that way in my HTML I do something like:

```
<p>The server actually loads:</p>
<pre class="lang-html prettyprint-override"><code><img src="public/images/logo.png">
</code>```

This way I do not have to prefix all my resources with public/.

[ Disclosure ]

This question is for help with a final project at my University, but this type question is allowed and not violating academic policies. Making a project with htaccess and MVC is not a requirement, just something I'm doing to challenge myself.

UPDATE:

Here is my original RedirectMacth rule. Anything that is not a PHP or HTML file is redirected:

```<code>RedirectMatch ([\w\d\s\/\-\:\_%\ ]*\.(?!php|htm|html)) $1 [L]
</code>```

答:
I found the solution after reviewing the error logs on my server. My various attempts were causing redirect loops. Here is my working .htaccess file in case it helps anyone trying to do something similar.

The key is to short circuit the .htaccess file when necessary so it doesn't keep rewriting your URLs infinitely. I added inline comments to explain the process:

# Redirect all requests to the public directory.
<IfModule mod_rewrite.c>
    RewriteEngine On
    # Only needing for local develoment in my case.
    RewriteBase /BU/cs-602/developer-story/
    # If nothing or an index page is requested go to `public/index.php` and stop processing.
    RewriteRule ^(\/||.*index\..*)$ public/index.php [L,QSA]
    # If the URL already contains the `public/` directory go to URL and stop processing.
    RewriteRule ^(.*public\/.*)$ $1 [L,QSA]
    # If it appears this URL is for a resource (JS, CSS, etc.) prefix with `public/`.
    RewriteCond %{REQUEST_URI} ^([\w\d\s\-\_\/\%]*)\.(?!php|htm|html).*$
    # Go to the modified URL if the last rule triggered and stop processing.
    RewriteRule ^(.*)$ public/$1 [L,QSA]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    # Rewrite all remaing URLs to our apps MVC structure.
    RewriteRule ^([\w\d\s\-\_\/\%]*)$ public/index.php?p=$1 [L,QSA]
</IfModule>
```

Body:
[ Background ]

This is the structure to my application:

app/
    controllers/
        ...
    modules/
        ...
    views/
        ...
public/
    css/
        main.css
    images/
        ...
    js/
        ...
    index.php
.htaccess

For various reasons (security, organization, etc.) the public application (website) is loaded and displayed by public/index.php At the "root" of my server I have the following .htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /BU/cs-602/developer-story/
    RewriteRule ^(\/||index\.*)$ public/index.php [L,QSA]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RedirectMatch ^(/BU/cs-602/developer-story.)([\w\d\s\/\-\:\_%\ ]*\.css)$ $1public/$2 [L]
    RewriteRule ^([\w\d\-\_\/\ ]*)$ public/index.php?p=$1 [L,QSA]
</IfModule>

These rules should rewrite/ redirect all requests from the server "root" to public/index.php Since I am developing locally on my development server this project is not actually at the root of my server but is located at /BU/cs-602/developer-story/ This is why I added the RewriteBase rule.

If I remove the RedirectMatch rule everything from an MVC standpoint works:

URLs like http://localhost/BU/cs-602/developer-story or http://localhost/BU/cs-602/developer-story/ become http://localhost/BU/cs-602/developer-story/public/index.php AND URLs like http://localhost/BU/cs-602/developer-story/user/id become http://localhost/BU/cs-602/developer-story/public/index.php?p=user/id.

Here is a live htaccess test.

[ Question ]

How can I fix the .htaccess file or the RedirectMatch rule to redirect request to resources like CSS or JS files? The current rule works in the tester but not on my server unless I remove the RedirectMatch rule.

I would like a URL like http://localhost/BU/cs-602/developer-story/css/main.css to become http://localhost/BU/cs-602/developer-story/public/css/main.css that way in my HTML I do something like:

The server actually loads:

This way I do not have to prefix all my resources with public/.

[ Disclosure ]

This question is for help with a final project at my University, but this type question is allowed and not violating academic policies. Making a project with htaccess and MVC is not a requirement, just something I'm doing to challenge myself.

UPDATE:

Here is my original RedirectMacth rule. Anything that is not a PHP or HTML file is redirected:

RedirectMatch ([\w\d\s\/\-\:\_%\ ]*\.(?!php|htm|html)) $1 [L]


问:
Remove duplicates from list but keep by color preference
I have a list that contains duplicates like this..

```<code>"id","name","type","price","color"
"23","item1","t-shirt","37","red"
"56","item66","jumper","3","yellow"
"366","item7","jumper","55","yellow"
"366","item7","jumper","55","red"
"745","item 9","t-shirt","45","green"
"3245","item 12","t-shirt","67","red"
"3245","item 12","t-shirt","67","purple"
"654","item 88","jumper","66","blue"
"2","item 99","jumper","77","purple"
"2","item 99","jumper","77","green"
</code>```

I want to remove the duplicates but keep the one by order or color prefence by this table..

```<code>1 - Red
2 - Purple
3 - Blue
4 - Green
5 - Yellow
</code>```

So the final list would look like this..

```<code>"id","name","type","price","color"
"23","item1","t-shirt","37","red"
"56","item66","jumper","3","yellow"
"366","item7","jumper","55","red"
"745","item 9","t-shirt","45","green"
"3245","item 12","t-shirt","67","red"
"654","item 88","jumper","66","blue"
"2","item 99","jumper","77","purple"
</code>```

What is my best approach? Would sorting them by color prefernce first and then removing duplicates be a workable solution? If so, does anybody have an example of something similar being achieved? I am not sure how to sort by order of preferenc.

答:
I am assuming the original is a list of lists (one list for each line)

convert it to a single list where each item is an id followed by a tuple ("name", "type", "price", "color")

```<code>    list2=[]
    for item in list1:
      x= [item[0],tuple(item[1:])]
      list2.append(x)
</code>```

Now make a dictionary out of list 2.  This will have no duplicate keys  (id numbers) but there is no guarantee which line will be used

```<code>    dict1=dict(list2)
</code>```

If we just sort the dictionary the sorting will be done by id.   So we use the key parameter of sorted.   Key is a function, normally a lambda function is used here, but a regular named function will work.   It should take one parameter, an item of the thing being sorted and return something that can be checked for order.  We specify the order a list.

```<code>    Order_list=["red","purple","blue","green","yellow"]

    def sort_key(x):
        check = x[1][3]   #(a color)
        key = Order_list.index(check)
        return key
</code>```

And now we can sort our dictionary

```<code>    sorted(dict1, key = sort_key)
</code>```

The return value will be a list of k:value pairs with the value of each pair a 4 tuple.

Body:
I have a list that contains duplicates like this..

"id","name","type","price","color"
"23","item1","t-shirt","37","red"
"56","item66","jumper","3","yellow"
"366","item7","jumper","55","yellow"
"366","item7","jumper","55","red"
"745","item 9","t-shirt","45","green"
"3245","item 12","t-shirt","67","red"
"3245","item 12","t-shirt","67","purple"
"654","item 88","jumper","66","blue"
"2","item 99","jumper","77","purple"
"2","item 99","jumper","77","green"

I want to remove the duplicates but keep the one by order or color prefence by this table..

1 - Red
2 - Purple
3 - Blue
4 - Green
5 - Yellow

So the final list would look like this..

"id","name","type","price","color"
"23","item1","t-shirt","37","red"
"56","item66","jumper","3","yellow"
"366","item7","jumper","55","red"
"745","item 9","t-shirt","45","green"
"3245","item 12","t-shirt","67","red"
"654","item 88","jumper","66","blue"
"2","item 99","jumper","77","purple"

What is my best approach? Would sorting them by color prefernce first and then removing duplicates be a workable solution? If so, does anybody have an example of something similar being achieved? I am not sure how to sort by order of preferenc.

Body:
I am assuming the original is a list of lists (one list for each line)

convert it to a single list where each item is an id followed by a tuple ("name", "type", "price", "color")

    list2=[]
    for item in list1:
      x= [item[0],tuple(item[1:])]
      list2.append(x)

Now make a dictionary out of list 2.  This will have no duplicate keys  (id numbers) but there is no guarantee which line will be used

    dict1=dict(list2)

If we just sort the dictionary the sorting will be done by id.   So we use the key parameter of sorted.   Key is a function, normally a lambda function is used here, but a regular named function will work.   It should take one parameter, an item of the thing being sorted and return something that can be checked for order.  We specify the order a list.

    Order_list=["red","purple","blue","green","yellow"]

    def sort_key(x):
        check = x[1][3]   #(a color)
        key = Order_list.index(check)
        return key

And now we can sort our dictionary

    sorted(dict1, key = sort_key)

The return value will be a list of k:value pairs with the value of each pair a 4 tuple.


问:
how to see all directory sizes named invoices in a bash script
I have a list of directories and was wondering if there was a bash script to do maybe a for loop to go through and enter du -h at the last directory (/something/something/invoices). Or is there a better command to do than: find / -type d -name "/something/something/invoices" -ls
that would include the invoices directory sizes.

Thank you and hope to hear from someone.

答:
If invoices can appear on any depth in the subtree, use find's -exec option:

find / -type d -name invoices -exec du -h {} \;
```
```3,5M    /here/there/invoices
1,6M    /somewhere/else/invoices
560K    /nested/really/really/really/deep/invoices
:
```

Body:
If invoices can appear on any depth in the subtree, use find's -exec option:

find / -type d -name invoices -exec du -h {} \;

3,5M    /here/there/invoices
1,6M    /somewhere/else/invoices
560K    /nested/really/really/really/deep/invoices
:


问:
What is this function statement?
What does this do? Is this something like an empty function? Can't find any information on this, in what use case this is used?

(() => {
 console.log("test");
})
```

答:
If it had another set of parenthesis at the end, it would be a self executing function

(() => {
 console.log("test");
})()
```

but as is, it does nothing.

Title: What is this function statement?

Body:
If it had another set of parenthesis at the end, it would be a self executing function

(() => {
 console.log("test");
})()

but as is, it does nothing.


问:
error installing cmc and linear models python packages in Jupyter. Error: "& was unexpected at this time."
I keep getting an error when I install python packages in Jupyter.

Even after restarting the kernel, I still get the "& was unexpected at this time." error and cannot call functions from the package.Any idea how to resolve this?

```<code>!pip install cmc
pip install linearmodels
</code>```

答:
It's possible that the error occurs because your Jupyter runs a "wrong" terminal (e.g., sh instead of bash). Try a "cell magic", it should help if my suspicion is correct:

```<code>%%bash
pip install cmc
</code>```

Body:
I keep getting an error when I install python packages in Jupyter.

Even after restarting the kernel, I still get the "& was unexpected at this time." error and cannot call functions from the package.Any idea how to resolve this?

!pip install cmc
pip install linearmodels

Body:
It's possible that the error occurs because your Jupyter runs a "wrong" terminal (e.g., sh instead of bash). Try a "cell magic", it should help if my suspicion is correct:

%%bash
pip install cmc


问:
How do I create a view, select from it, and join it with an existing table
So here's the code producing the data that I want for table 1.

```<code>with data as
(
    select
        CP_REF,
        count(*) * 1.0 /
          nullif(count(case when QUANTITY > 0 then 1 end), 0) as ADI,
          stdevp(QUANTITY) / nullif(avg(QUANTITY), 0) as COV
    from
        DF_ALL_DEMAND_BY_ROW_V
    where
        parent is not null
    group by
        CP_REF
)
select
    CP_REF, ADI, COV
    case
        when ADI <  1.32 and COV * COV <  0.49 then 'Smooth'
        when ADI >= 1.32 and COV * COV <  0.49 then 'Intermittent'
        when ADI <  1.32 and COV * COV >= 0.49 then 'Erratic'
        when ADI >= 1.32 and COV * COV <= 0.49 then 'Lumpy'
        else 'No Quantity Measured'
    end
from data;
</code>```

This provides a very elegant solution like this...

This is what I'm looking for, however, now I need to take this data and join it with the original table DF_ALL_DEMAND_BY_ROW_V. I want it to have everything that exists in DF_ALL_DEMAND_BY_ROW_V but joining the data above on CP_REF, which I think is a LEFT JOIN but I can't figure it out.

答:
Not sure if this is what you mean however why not create a second CTE and join to that, eg</p>
```<code>with data as (
    select
    ...
), Q2 as (
  select
    CP_REF, ADI,
    case
        when ADI <  1.32 and COV * COV <  0.49 then 'Smooth'
        when ADI >= 1.32 and COV * COV <  0.49 then 'Intermittent'
        when ADI <  1.32 and COV * COV >= 0.49 then 'Erratic'
        when ADI >= 1.32 and COV * COV <= 0.49 then 'Lumpy'
        else 'Smooth'
    end as StatusOrWhatever
  from data
)
select stuff
from DF_ALL_DEMAND_BY_ROW_V v
left join Q2 on D2.CF_REF = v.CP_REF
</code>```

Body:
So here's the code producing the data that I want for table 1.

with data as
(
    select
        CP_REF,
        count(*) * 1.0 /
          nullif(count(case when QUANTITY > 0 then 1 end), 0) as ADI,
          stdevp(QUANTITY) / nullif(avg(QUANTITY), 0) as COV
    from
        DF_ALL_DEMAND_BY_ROW_V
    where
        parent is not null
    group by
        CP_REF
)
select
    CP_REF, ADI, COV
    case
        when ADI <  1.32 and COV * COV <  0.49 then 'Smooth'
        when ADI >= 1.32 and COV * COV <  0.49 then 'Intermittent'
        when ADI <  1.32 and COV * COV >= 0.49 then 'Erratic'
        when ADI >= 1.32 and COV * COV <= 0.49 then 'Lumpy'
        else 'No Quantity Measured'
    end
from data;

This provides a very elegant solution like this...

This is what I'm looking for, however, now I need to take this data and join it with the original table DF_ALL_DEMAND_BY_ROW_V. I want it to have everything that exists in DF_ALL_DEMAND_BY_ROW_V but joining the data above on CP_REF, which I think is a LEFT JOIN but I can't figure it out.

Body:
Not sure if this is what you mean however why not create a second CTE and join to that, eg

with data as (
    select
    ...
), Q2 as (
  select
    CP_REF, ADI,
    case
        when ADI <  1.32 and COV * COV <  0.49 then 'Smooth'
        when ADI >= 1.32 and COV * COV <  0.49 then 'Intermittent'
        when ADI <  1.32 and COV * COV >= 0.49 then 'Erratic'
        when ADI >= 1.32 and COV * COV <= 0.49 then 'Lumpy'
        else 'Smooth'
    end as StatusOrWhatever
  from data
)
select stuff
from DF_ALL_DEMAND_BY_ROW_V v
left join Q2 on D2.CF_REF = v.CP_REF


问:
Trying to find memory leak if it exists for a GUI application
I have a very simple GUI application that runs HIL tests for a system. I select a test from a combo box, then click run. This starts the test and runs for 27 minutes. During this time, the CPU is capturing data and storing the data in String Builder. When the test is done, the string builder writes the captured data to a file. I ran the same test 3 times to check for memory leaks. Please look at the attached picture.

Snapshot#1: Start of the GUI
Snapshot#19: End of the first try
SnapShot#33: End of the second try
Snapshot#38: End of the third try

if we compare 33 and 38, we can see that the objects and heap size are the same which leads me to believe that there is no memory leak.

but if we compare 19 and 33/38, we can see that the no of objects increased by 1 and the heap size increased by 0.1KB which leads me to believe that there is a small memory leak.

If we compare 1 with the others, we see that the no of objects and the heap size increased quite a bit relatively speaking.

So my question is, is there a memory leak here? How do I come to a solid conclusion?

答:
C# uses a concept of garbage collection (GC), which means that objects are not freed at the end of a scope but some arbitrary time after that, which can be seconds or even minutes.

In your tool a GC run it is indicated by a small yellow tickmark at the top of the memory bar.

As you can see, only one garbage collection happened about at about 37:00 in time (which is ~2200 seconds).

So my question is, is there a memory leak here?

At the moment it's too little data to say for sure.

How do I come to a solid conclusion?

You need a tool that is .NET specific, i.e. it knows that .NET is garbage collected and will perform a garbage collection before measuring. E.g. Jetbrains dotMemory (part of Resharper).

Setup everything for measuring

Run the test sequence once. This will ensure that DLLs are loaded, static stuff is initialized, lazy loading stuff has been loaded etc.

Take a snapshot

Run the test sequence 5 times (use a prime number)

Take a snapshot again

Run the test sequence 7 times (use a prime number)

Analyze the differences between snapshots.

Any leak typically leaks 5 times during the first run and 7 times during the second run or a multiple of that. You can hardly leak 2 objects in 7 runs if all runs are identical (could happen with a lot of ifs; make sure each run does the same thing).

If you have such a leak, do a code review to check where it's gonna be freed.

Potential false positives:

caches

log files or similar which are appended to during the whole test sequence

Note: In Visual Studio, don't just use the diagnostic tool that automatically runs when you start debugging. Instead, use Debug / Performance Profiler and choose "Memory usage"

That one allows you to force a GC and take a snapshot.


问:
Docker container CMAKE gives crypto/fips/fips.c:153: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE - dracut-fips crypto.fips_enabled = 1
Getting crypto/fips/fips.c:153: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE when

dracut-fips package is installed and sysctl -a shows crypto.fips_enabled = 1

Restriction: Can not disable dracut-fips package or crypto.fips_enable setting in my case.

QUESTION:

How can I get cmake --version working inside the container?

This host is where the issue is coming inside the container but not of the HOST OS.

```<code>someLinuxUser@jenkins-project_team_rh ~]$ hostname -f; hostname -i
jenkins-project_team_rh.lewisville.us.company.com
10.20.20.10[someLinuxUser@jenkins-project_team_rh ~]$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)
[someLinuxUser@jenkins-project_team_rh ~]$
[someLinuxUser@jenkins-project_team_rh ~]$ cmake --version
cmake version 3.18.2

CMake suite maintained and supported by Kitware (kitware.com/cmake).
</code>```

List and Start OpenSuse 15.2 container

```<code>[someLinuxUser@jenkins-project_team_rh ~]$ sudo docker image ls
REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE
opensuse-image                15.2                618840498a55        3 hours ago         2.59GB
</code>```

Run Docker container

NOW I'm inside the container. Running "cmake --version" here fails with an error.

NOTE: The same docker image will work fine if you have ANY host OS, where "sysctl -a | grep fips" will show "crypto.fips_enabled = 0" in it's output. So, we may need to have this value set as 0.

```<code>[someLinuxUser@jenkins-project_team_rh ~]$ sudo docker run -it opensuse-image:15.2 bash
Active Directory Password:
WARNING: IPv4 forwarding is disabled. Networking will not work.
docker_nonroot_user@eaa40032f4d3:~/git>

docker_nonroot_user@eaa40032f4d3:~/git> which cmake; cmake --version
/usr/bin/cmake
crypto/fips/fips.c:153: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE
Aborted (core dumped)
docker_nonroot_user@eaa40032f4d3:~/git>

docker_nonroot_user@3e63938cf7e7:~/git> cat /etc/os-release
NAME="openSUSE Leap"
VERSION="15.2"
ID="opensuse-leap"
ID_LIKE="suse opensuse"
VERSION_ID="15.2"
PRETTY_NAME="openSUSE Leap 15.2"
ANSI_COLOR="0;32"
CPE_NAME="cpe:/o:opensuse:leap:15.2"
BUG_REPORT_URL="https://bugs.opensuse.org"
HOME_URL="https://www.opensuse.org/"
</code>```

Either on HOST OS (RH 7.9) --/-- inside the Docker container (OpenSuse 15.2) Running:

```<code>[someLinuxUser@jenkins-project_team_rh ~]$ sysctl -a | grep fips_enabled
crypto.fips_enabled = 1
</code>```

i.e. it shows, fips is enabled on this HOST machine. I think if this (crypto.fips_enabled was set to = 0) then we may not see this issue with cmake, but in my case, I can't disable this setting.

On the Host machine, some related packages are:

```<code>[someLinuxUser@jenkins-project_team_rh ~]$ sudo yum list installed | egrep "fips|openssl|dracut"
dracut-fips.x86_64                  033-572.el7           @rhel-x86_64-server-7
fipscheck.x86_64                    1.4.1-6.el7           @anaconda/7.6
fipscheck-lib.x86_64                1.4.1-6.el7           @anaconda/7.6
CentrifyDC-openssl.x86_64           5.7.1-347             installed
openssl.x86_64                      1:1.0.2k-22.el7_9     @q1_rhel-x86_64-server-7
openssl-devel.x86_64                1:1.0.2k-22.el7_9     @q1_rhel-x86_64-server-7
openssl-libs.x86_64                 1:1.0.2k-22.el7_9     @q1_rhel-x86_64-server-7
openssl098e.x86_64                  0.9.8e-29.el7_2.3     @anaconda/7.6
xmlsec1-openssl.x86_64              1.2.20-7.el7_4        @anaconda/7.6
dracut.x86_64                       033-572.el7           @rhel-x86_64-server-7
dracut-config-rescue.x86_64         033-572.el7           @rhel-x86_64-server-7
dracut-network.x86_64               033-572.el7           @rhel-x86_64-server-7
[someLinuxUser@jenkins-project_team_rh ~]$
</code>```

NOW, Proof that DOCKER image/container used above is not bad.

Using same Docker image on a different machine, same HOST OS.

On this another RH 7.9 OS host machine I have, I have the same docker image SCP'ed, when I start the same OpenSuse 15.2 image as docker container and run cmake --version, everything works fine and I don't see this error.

Running:

```<code>[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ hostname -f; hostname -i
rh_7_9_os_machine.company.local
10.100.100.10
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo docker image ls
REPOSITORY                     TAG                IMAGE ID            CREATED             SIZE
opensuse-image                 15.2               618840498a55        3 hours ago         2.59GB
</code>```

This HOST shows:

```<code>[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sysctl -a 2>/dev/null | grep fips_enabled
crypto.fips_enabled = 0
</code>```

Running Docker image --> container and cmake --version in it, works!

```<code>[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo docker run -it opensuse-image:15.2 bash
docker_nonroot_user@fb751d198066:~/git>
docker_nonroot_user@fb751d198066:~/git> sysctl -a 2>/dev/null | grep fips
crypto.fips_enabled = 0
docker_nonroot_user@fb751d198066:~/git>
docker_nonroot_user@fb751d198066:~/git> cmake --version
cmake version 3.17.0

CMake suite maintained and supported by Kitware (kitware.com/cmake).
docker_nonroot_user@fb751d198066:~/git> exit
</code>```

YUM packages on HOST machine are:

```<code>[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo yum list installed |grep fips
fipscheck.x86_64             1.4.1-6.el7        @anaconda/7.4
fipscheck-lib.x86_64         1.4.1-6.el7        @anaconda/7.4
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo yum list installed |grep openssl
openssl.x86_64               1:1.0.2k-22.el7_9   @rhel-7-server-rhui-rpms
openssl-devel.x86_64         1:1.0.2k-22.el7_9   @rhel-7-server-rhui-rpms
openssl-libs.x86_64          1:1.0.2k-22.el7_9   @rhel-7-server-rhui-rpms
openssl11-libs.x86_64        1:1.1.1g-2.el7      @epel
xmlsec1-openssl.x86_64       1.2.20-7.el7_4      @rhui-REGION-rhel-server-releases
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo yum list installed |grep dracut\-fips
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo yum list installed |grep dracut
dracut.x86_64                033-572.el7       @rhel-7-server-rhui-rpms
dracut-config-generic.x86_64 033-572.el7       @rhel-7-server-rhui-rpms
dracut-config-rescue.x86_64  033-572.el7       @rhel-7-server-rhui-rpms
dracut-network.x86_64        033-572.el7       @rhel-7-server-rhui-rpms
</code>```

As you can see above, there's NO package named dracut-fips installed on this machine,  assuming that's why crypto.fips_enabled = 0 and "cmake --version" works on this HOST and within container as  well!!

QUESTION:

How can I get cmake --version working inside the container? when I can't uninstall dracut-fips package and disable FIPS by having crypto.fips_enabled = 0 on the first HOST OS.

答:
Found the solution

WHY this issue was coming:
Docker build (to create the image) was run on a machine (the other machine, where cmake was working inside the docker container)... i.e. where FIPS was not installed.
During the build step, Docker file was running
zypper install cmake (or yum install cmake).

As FIPS was disabled on the machine where docker image was built, cmake was installed in docker image, without understanding FIPS being enabled / dracut-fips being installed.

Then, when you copy this image and consume it on a machine where FIPS is actually ENABLED, then cmake was failing with that error mesg: crypto/fips/fips.c:153: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE

Actually there are 2 solutions.

--

Solution #1: Tag your docker image appropriately.

Summary:

PS: If you do install cmake using the above, then it'll only work on target machine where you run container, if that machine's FIPS is disabled or enabled at build time. i.e. if FIPS was enabled, you install cmake and run it on a machine where it's NOT same FIPS setting as the host, where image was built, then you'll be reading this post for help.

Better way in case you want to install cmake using the above package managers, would be, tag your docker image appropriately during image creation time i.e.:

docker build -t <image-name>-fips-enabled ... if FIPS is enabled

and

docker build -t <image-name>-fips-disabled ... if FIPS on that that machine is disabled.

That way, you can pick the correct docker image imagename-fips-enabled vs imagename-fips-disabled acc. to what your target machine FIPS setting is (where you'll actually perform docker run ... using this image).

--

Solution #2: Don't use zypper (OpenSuse) or yum if you have RedHat container.
and this solution is flexible in the sense, that it's independent of FIPS setting = 0 / 1 on the host, where image was built.

I didn't use zypper/yum to install cmake inside Dockerfile, but just grabbed cmake-3.18.2-Linux-x86_64.tar.gz bundle file.

Within Dockerfile, I simply extracted this .tar.gz file inside some directory.
Also I set export PATH:/path/where/I/installed/cmake-3.18.2../bin:/..some_other_paths:/...:/.... in Dockerfile inside RUN statement.

i.e.
RUN export PATH=/path/where/I/installed/cmake-3.18.2../bin:/...... && <more cmds here> && <some other cmds here> && ... etc, so it can find the extracted cmake 3.18.2 for any buil-time (cmake operations) and also SET the same PATH=/... variable as ENV PATH=/.... same value used during RUN for PATH so at runtime, when the container runs, $PATH is all set for finding cmake (3.18.2 version) rather than using any existing /usr/bin/cmake or some other shit).

Dockerfile snapshot:

```<code>#    curl -k -sSf -H "X-JFrog-Art-Api:dslfhjlieurqwihlj233lk2l4j6p9usdkajdfasddl809842iijhlkhflhafOHIHFLyeaGoodLuck" \
#    -o /tmp/cmake.tar.gz https://artifactory.company.com/artifactory/some-Local/cmake/cmake-3.18.2-Linux-x86_64.tar.gz && \
</code>```

and

as my umask settings were set to 022, I didn't have to do any chicken chmod operation post untar:

```<code>#    echo -e "\n-- Installing CMake ...\n" && \
#    tar -xvzpf /tmp/cmake.tar.gz -C /home/docker_nonroot_user/tools/ && \
</code>```

Inside the docker container, as ENV PATH=/... was set in Dockerfile for this target path as well, the correct cmake 3.18.2 was used at docker container runtime action.

cmake installed location in my case was:

```<code>/home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin/cmake
</code>```

PATH inside docker container was:

```<code>/home/docker_nonroot_user/tools/cov-analysis/bin:/home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
</code>```

RESULT:

Using a Docker image built using SOLUTION #2 above, i.e. docker image built on a machine where FIPS = 0 aka DISABLED and then later, using this same image to create a container on a totally different target host machine where FIPS = 1 aka ENABLED, I see:

```<code>87d8104d8c41:/home/docker_nonroot_user # sysctl -a|grep fips_en
crypto.fips_enabled = 1
87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # which cmake
/usr/bin/cmake
87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # cmake --version
crypto/fips/fips.c:153: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE
Aborted (core dumped)
87d8104d8c41:/home/docker_nonroot_user #

87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # ls -l /home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin
total 75504
-rwxr-xr-x 1 root root 11908568 Aug 20  2020 ccmake
-rwxr-xr-x 1 root root 12096216 Aug 20  2020 cmake
-rwxr-xr-x 1 root root 27476480 Aug 20  2020 cmake-gui
-rwxr-xr-x 1 root root 12398808 Aug 20  2020 cpack
-rwxr-xr-x 1 root root 13318712 Aug 20  2020 ctest
87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # ls -l /home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin/cmake
-rwxr-xr-x 1 root root 12096216 Aug 20  2020 /home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin/cmake
87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # /home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin/cmake --version
cmake version 3.18.2

CMake suite maintained and supported by Kitware (kitware.com/cmake).
87d8104d8c41:/home/docker_nonroot_user # : Merry X-mas Baaaaeeebyyy! - no more FIPS shit error now. Next I'll fix some chown on ~<user> and close my story.
</code>```

SOLUTION #3: You can disable FIPS but only if you are allowed to do so, then you don't need solution #1 or solution #2.

MISC Info on OpenSSL errors:

The effects of self-test failures in the Module differ depending on the type of self-test that failed.

The FIPS_mode_set() function verifies the integrity of the runtime executable using a HMAC SHA-256 digest,
which is computed at build time. If this computed HMAC SHA-256 digest matches the stored, known digest, then
the power-up self-test (consisting of the algorithm-specific Pairwise Consistency and Known Answer tests) is
performed.

Non-fatal self-test errors transition the module into an error state. The application must be restarted to recover
from these errors. The non-fatal self-test errors are:

FIPS_R_FINGERPRINT_DOES_NOT_MATCH - The integrity verification check failed

FIPS_R_FIPS_SELFTEST_FAILED - a known answer test failed

FIPS_R_SELFTEST_FAILED - a known answer test failed

FIPS_R_TEST_FAILURE – a known answer test failed (RSA); pairwise consistency test failed (DSA)

FIPS_R_PAIRWISE_TEST_FAILED – a pairwise consistency test during DSA or RSA key generation failed

FIPS_R_FIPS_MODE_ALREADY_SET - the application initializes the FIPS mode when it is already initialized

These errors are reported through the regular ERR interface of the shared libraries and can be queried by
functions such as ERR_get_error(). See the OpenSSL Module manual page for the function description.

A fatal error occurs only when the module is in the error state (a self-test has failed) and the application calls a
crypto function of the module that cannot return an error in normal circumstances (void return functions). The
error message: 'FATAL FIPS SELFTEST FAILURE' is printed to stderr and the application is terminated with the
abort() call.

The only way to recover from a fatal error is to restart the application. If failures persist, you must reinstall the Module. If you downloaded the software, verify the package hash to confirm a proper download.

IMPORTANT NOTE:

If you installed a newer version of OpenSSL x.y.z (rpm/etc) and didn't reboot/restart your machine, some of the libraries which consume openssl will be vulnerable / error out too with similar errors.

You can test this by running:

uptime command to see how long your server/machine has been UP n running.

sudo lsof | grep libssl.so or to Find processes running with deleted OpenSSL libraries, run:

sudo lsof | grep DEL.*libssl

So, try rebooting your machine and see if the errors goes away and check the output of the above commands.

For more info, refer this link: https://raymii.org/s/snippets/Find_all_services_using_libssl_to_restart_after_an_OpenSSL_update.html

Body:
Getting crypto/fips/fips.c:153: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE when

dracut-fips package is installed and sysctl -a shows crypto.fips_enabled = 1

Restriction: Can not disable dracut-fips package or crypto.fips_enable setting in my case.

QUESTION:

How can I get cmake --version working inside the container?

This host is where the issue is coming inside the container but not of the HOST OS.

someLinuxUser@jenkins-project_team_rh ~]$ hostname -f; hostname -i
jenkins-project_team_rh.lewisville.us.company.com
10.20.20.10[someLinuxUser@jenkins-project_team_rh ~]$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)
[someLinuxUser@jenkins-project_team_rh ~]$
[someLinuxUser@jenkins-project_team_rh ~]$ cmake --version
cmake version 3.18.2

CMake suite maintained and supported by Kitware (kitware.com/cmake).

List and Start OpenSuse 15.2 container

[someLinuxUser@jenkins-project_team_rh ~]$ sudo docker image ls
REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE
opensuse-image                15.2                618840498a55        3 hours ago         2.59GB

Run Docker container

NOW I'm inside the container. Running "cmake --version" here fails with an error.

NOTE: The same docker image will work fine if you have ANY host OS, where "sysctl -a | grep fips" will show "crypto.fips_enabled = 0" in it's output. So, we may need to have this value set as 0.

[someLinuxUser@jenkins-project_team_rh ~]$ sudo docker run -it opensuse-image:15.2 bash
Active Directory Password:
WARNING: IPv4 forwarding is disabled. Networking will not work.
docker_nonroot_user@eaa40032f4d3:~/git>

docker_nonroot_user@eaa40032f4d3:~/git> which cmake; cmake --version
/usr/bin/cmake
crypto/fips/fips.c:153: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE
Aborted (core dumped)
docker_nonroot_user@eaa40032f4d3:~/git>

docker_nonroot_user@3e63938cf7e7:~/git> cat /etc/os-release
NAME="openSUSE Leap"
VERSION="15.2"
ID="opensuse-leap"
ID_LIKE="suse opensuse"
VERSION_ID="15.2"
PRETTY_NAME="openSUSE Leap 15.2"
ANSI_COLOR="0;32"
CPE_NAME="cpe:/o:opensuse:leap:15.2"
BUG_REPORT_URL="https://bugs.opensuse.org"
HOME_URL="https://www.opensuse.org/"

Either on HOST OS (RH 7.9) --/-- inside the Docker container (OpenSuse 15.2) Running:

[someLinuxUser@jenkins-project_team_rh ~]$ sysctl -a | grep fips_enabled
crypto.fips_enabled = 1

i.e. it shows, fips is enabled on this HOST machine. I think if this (crypto.fips_enabled was set to = 0) then we may not see this issue with cmake, but in my case, I can't disable this setting.

On the Host machine, some related packages are:

[someLinuxUser@jenkins-project_team_rh ~]$ sudo yum list installed | egrep "fips|openssl|dracut"
dracut-fips.x86_64                  033-572.el7           @rhel-x86_64-server-7
fipscheck.x86_64                    1.4.1-6.el7           @anaconda/7.6
fipscheck-lib.x86_64                1.4.1-6.el7           @anaconda/7.6
CentrifyDC-openssl.x86_64           5.7.1-347             installed
openssl.x86_64                      1:1.0.2k-22.el7_9     @q1_rhel-x86_64-server-7
openssl-devel.x86_64                1:1.0.2k-22.el7_9     @q1_rhel-x86_64-server-7
openssl-libs.x86_64                 1:1.0.2k-22.el7_9     @q1_rhel-x86_64-server-7
openssl098e.x86_64                  0.9.8e-29.el7_2.3     @anaconda/7.6
xmlsec1-openssl.x86_64              1.2.20-7.el7_4        @anaconda/7.6
dracut.x86_64                       033-572.el7           @rhel-x86_64-server-7
dracut-config-rescue.x86_64         033-572.el7           @rhel-x86_64-server-7
dracut-network.x86_64               033-572.el7           @rhel-x86_64-server-7
[someLinuxUser@jenkins-project_team_rh ~]$

NOW, Proof that DOCKER image/container used above is not bad.

Using same Docker image on a different machine, same HOST OS.

On this another RH 7.9 OS host machine I have, I have the same docker image SCP'ed, when I start the same OpenSuse 15.2 image as docker container and run cmake --version, everything works fine and I don't see this error.

Running:

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ hostname -f; hostname -i
rh_7_9_os_machine.company.local
10.100.100.10
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo docker image ls
REPOSITORY                     TAG                IMAGE ID            CREATED             SIZE
opensuse-image                 15.2               618840498a55        3 hours ago         2.59GB

This HOST shows:

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sysctl -a 2>/dev/null | grep fips_enabled
crypto.fips_enabled = 0

Running Docker image --> container and cmake --version in it, works!

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo docker run -it opensuse-image:15.2 bash
docker_nonroot_user@fb751d198066:~/git>
docker_nonroot_user@fb751d198066:~/git> sysctl -a 2>/dev/null | grep fips
crypto.fips_enabled = 0
docker_nonroot_user@fb751d198066:~/git>
docker_nonroot_user@fb751d198066:~/git> cmake --version
cmake version 3.17.0

CMake suite maintained and supported by Kitware (kitware.com/cmake).
docker_nonroot_user@fb751d198066:~/git> exit

YUM packages on HOST machine are:

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo yum list installed |grep fips
fipscheck.x86_64             1.4.1-6.el7        @anaconda/7.4
fipscheck-lib.x86_64         1.4.1-6.el7        @anaconda/7.4
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo yum list installed |grep openssl
openssl.x86_64               1:1.0.2k-22.el7_9   @rhel-7-server-rhui-rpms
openssl-devel.x86_64         1:1.0.2k-22.el7_9   @rhel-7-server-rhui-rpms
openssl-libs.x86_64          1:1.0.2k-22.el7_9   @rhel-7-server-rhui-rpms
openssl11-libs.x86_64        1:1.1.1g-2.el7      @epel
xmlsec1-openssl.x86_64       1.2.20-7.el7_4      @rhui-REGION-rhel-server-releases
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$

[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo yum list installed |grep dracut\-fips
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$
[gigauser@rh_7_9_os_machine opensuse-x-project_team_-mse]$ sudo yum list installed |grep dracut
dracut.x86_64                033-572.el7       @rhel-7-server-rhui-rpms
dracut-config-generic.x86_64 033-572.el7       @rhel-7-server-rhui-rpms
dracut-config-rescue.x86_64  033-572.el7       @rhel-7-server-rhui-rpms
dracut-network.x86_64        033-572.el7       @rhel-7-server-rhui-rpms

As you can see above, there's NO package named dracut-fips installed on this machine,  assuming that's why crypto.fips_enabled = 0 and "cmake --version" works on this HOST and within container as  well!!

QUESTION:

How can I get cmake --version working inside the container? when I can't uninstall dracut-fips package and disable FIPS by having crypto.fips_enabled = 0 on the first HOST OS.

Body:
Found the solution

WHY this issue was coming:
Docker build (to create the image) was run on a machine (the other machine, where cmake was working inside the docker container)... i.e. where FIPS was not installed.
During the build step, Docker file was running
zypper install cmake (or yum install cmake).

As FIPS was disabled on the machine where docker image was built, cmake was installed in docker image, without understanding FIPS being enabled / dracut-fips being installed.

Then, when you copy this image and consume it on a machine where FIPS is actually ENABLED, then cmake was failing with that error mesg: crypto/fips/fips.c:153: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE

Actually there are 2 solutions.

--

Solution #1: Tag your docker image appropriately.

Summary:

PS: If you do install cmake using the above, then it'll only work on target machine where you run container, if that machine's FIPS is disabled or enabled at build time. i.e. if FIPS was enabled, you install cmake and run it on a machine where it's NOT same FIPS setting as the host, where image was built, then you'll be reading this post for help.

Better way in case you want to install cmake using the above package managers, would be, tag your docker image appropriately during image creation time i.e.:

docker build -t <image-name>-fips-enabled ... if FIPS is enabled

and

docker build -t <image-name>-fips-disabled ... if FIPS on that that machine is disabled.

That way, you can pick the correct docker image imagename-fips-enabled vs imagename-fips-disabled acc. to what your target machine FIPS setting is (where you'll actually perform docker run ... using this image).

--

Solution #2: Don't use zypper (OpenSuse) or yum if you have RedHat container.
and this solution is flexible in the sense, that it's independent of FIPS setting = 0 / 1 on the host, where image was built.

I didn't use zypper/yum to install cmake inside Dockerfile, but just grabbed cmake-3.18.2-Linux-x86_64.tar.gz bundle file.

Within Dockerfile, I simply extracted this .tar.gz file inside some directory.
Also I set export PATH:/path/where/I/installed/cmake-3.18.2../bin:/..some_other_paths:/...:/.... in Dockerfile inside RUN statement.

i.e.
RUN export PATH=/path/where/I/installed/cmake-3.18.2../bin:/...... && <more cmds here> && <some other cmds here> && ... etc, so it can find the extracted cmake 3.18.2 for any buil-time (cmake operations) and also SET the same PATH=/... variable as ENV PATH=/.... same value used during RUN for PATH so at runtime, when the container runs, $PATH is all set for finding cmake (3.18.2 version) rather than using any existing /usr/bin/cmake or some other shit).

Dockerfile snapshot:

#    curl -k -sSf -H "X-JFrog-Art-Api:dslfhjlieurqwihlj233lk2l4j6p9usdkajdfasddl809842iijhlkhflhafOHIHFLyeaGoodLuck" \
#    -o /tmp/cmake.tar.gz https://artifactory.company.com/artifactory/some-Local/cmake/cmake-3.18.2-Linux-x86_64.tar.gz && \

and

as my umask settings were set to 022, I didn't have to do any chicken chmod operation post untar:

#    echo -e "\n-- Installing CMake ...\n" && \
#    tar -xvzpf /tmp/cmake.tar.gz -C /home/docker_nonroot_user/tools/ && \

Inside the docker container, as ENV PATH=/... was set in Dockerfile for this target path as well, the correct cmake 3.18.2 was used at docker container runtime action.

cmake installed location in my case was:

/home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin/cmake

PATH inside docker container was:

/home/docker_nonroot_user/tools/cov-analysis/bin:/home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

RESULT:

Using a Docker image built using SOLUTION #2 above, i.e. docker image built on a machine where FIPS = 0 aka DISABLED and then later, using this same image to create a container on a totally different target host machine where FIPS = 1 aka ENABLED, I see:

87d8104d8c41:/home/docker_nonroot_user # sysctl -a|grep fips_en
crypto.fips_enabled = 1
87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # which cmake
/usr/bin/cmake
87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # cmake --version
crypto/fips/fips.c:153: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE
Aborted (core dumped)
87d8104d8c41:/home/docker_nonroot_user #

87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # ls -l /home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin
total 75504
-rwxr-xr-x 1 root root 11908568 Aug 20  2020 ccmake
-rwxr-xr-x 1 root root 12096216 Aug 20  2020 cmake
-rwxr-xr-x 1 root root 27476480 Aug 20  2020 cmake-gui
-rwxr-xr-x 1 root root 12398808 Aug 20  2020 cpack
-rwxr-xr-x 1 root root 13318712 Aug 20  2020 ctest
87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # ls -l /home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin/cmake
-rwxr-xr-x 1 root root 12096216 Aug 20  2020 /home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin/cmake
87d8104d8c41:/home/docker_nonroot_user #
87d8104d8c41:/home/docker_nonroot_user # /home/docker_nonroot_user/tools/cmake-3.18.2-Linux-x86_64/bin/cmake --version
cmake version 3.18.2

CMake suite maintained and supported by Kitware (kitware.com/cmake).
87d8104d8c41:/home/docker_nonroot_user # : Merry X-mas Baaaaeeebyyy! - no more FIPS shit error now. Next I'll fix some chown on ~<user> and close my story.

SOLUTION #3: You can disable FIPS but only if you are allowed to do so, then you don't need solution #1 or solution #2.

MISC Info on OpenSSL errors:

The effects of self-test failures in the Module differ depending on the type of self-test that failed.

The FIPS_mode_set() function verifies the integrity of the runtime executable using a HMAC SHA-256 digest,
which is computed at build time. If this computed HMAC SHA-256 digest matches the stored, known digest, then
the power-up self-test (consisting of the algorithm-specific Pairwise Consistency and Known Answer tests) is
performed.

Non-fatal self-test errors transition the module into an error state. The application must be restarted to recover
from these errors. The non-fatal self-test errors are:

FIPS_R_FINGERPRINT_DOES_NOT_MATCH - The integrity verification check failed

FIPS_R_FIPS_SELFTEST_FAILED - a known answer test failed

FIPS_R_SELFTEST_FAILED - a known answer test failed

FIPS_R_TEST_FAILURE – a known answer test failed (RSA); pairwise consistency test failed (DSA)

FIPS_R_PAIRWISE_TEST_FAILED – a pairwise consistency test during DSA or RSA key generation failed

FIPS_R_FIPS_MODE_ALREADY_SET - the application initializes the FIPS mode when it is already initialized

These errors are reported through the regular ERR interface of the shared libraries and can be queried by
functions such as ERR_get_error(). See the OpenSSL Module manual page for the function description.

A fatal error occurs only when the module is in the error state (a self-test has failed) and the application calls a
crypto function of the module that cannot return an error in normal circumstances (void return functions). The
error message: 'FATAL FIPS SELFTEST FAILURE' is printed to stderr and the application is terminated with the
abort() call.

The only way to recover from a fatal error is to restart the application. If failures persist, you must reinstall the Module. If you downloaded the software, verify the package hash to confirm a proper download.

IMPORTANT NOTE:

If you installed a newer version of OpenSSL x.y.z (rpm/etc) and didn't reboot/restart your machine, some of the libraries which consume openssl will be vulnerable / error out too with similar errors.

You can test this by running:

uptime command to see how long your server/machine has been UP n running.

sudo lsof | grep libssl.so or to Find processes running with deleted OpenSSL libraries, run:

sudo lsof | grep DEL.*libssl

So, try rebooting your machine and see if the errors goes away and check the output of the above commands.

For more info, refer this link: https://raymii.org/s/snippets/Find_all_services_using_libssl_to_restart_after_an_OpenSSL_update.html


问:
How to extend ESP32 heap size?
I'm writing a code about play gif from SDCard on TFT Screen, so I create a array to put the gif file. (Using Nodemcu-32s 4MB)

```<code>#include<TFT_eSPI.h>
#include<SPI.h>
#include<AnimatedGIF.h>

TFT_eSPI tft;
AnimatedGIF gif;
uint8_t *gifArray;
int gifArrayLen;

void setup(){
  tft.init();
  tft.setRotation(2);
  tft.fillScreen(TFT_BLACK);

  File fgif=SD.open("/test.gif",FILE_READ);
  gifArrayLen=fgif.size();
  gifArray=(uint8_t *)malloc(gifArrayLen);
  for(int i=0;i<gifArrayLen;i++) gifArray[i]=fgif.read();
  fgif.close();
}

void loop(){
  tft.startWrite();
  gif.open(gifArray,gifArrayLen*sizeof(uint8_t),GIFDraw);
  while(gif.playFrame(true,NULL)) yield();
  gif.close();
  tft.endWrite();
}
</code>```

But if gif size > 131KB, it will trigger fatal error like this.

Guru Meditation Error: Core  1 panic'ed (StoreProhibited). Exception was unhandled.

After malloc the array, when I set a value on it, it triggered.

I found some forum says it's because it over the FreeRTOS heap size.

Can I extend the heap size or use another storage method to replace it?

答:
The heap is the pool of memory available to your program to allocate storage.

You're using an ESP32, which is a small CPU that has a small amount of RAM, roughly 400KB.

You cannot extend the heap on the ESP32. Unlike Linux which has virtual memory, there's nothing to extend it with.

However, you can add additional storage in the form of external PSRAM - additional RAM that is accessed via SPI. PSRAM will be slower than internal RAM and will have some restrictions on its use (for instance, call stacks cannot live in PSRAM and certain DMA buffers cannot be located there).

The ESP32's manufacturer, Espressif, has documented how to use PSRAM with the ESP32.

You'll generally (maybe exclusively) find PSRAM available built onto ESP32 boards, so if you're using an ESP32 module that doesn't already have it you'll need a new ESP32 module that does.

And as other people have pointed out, you can artificially cause less memory to be available in the heap by over-allocating and freeing memory, fragmenting the heap so that there are no large pieces still available. This is called heap fragmentation and has been written about extensively here on Stack Overflow and other web sites.

Title: How to extend ESP32 heap size?

Body:
I'm writing a code about play gif from SDCard on TFT Screen, so I create a array to put the gif file. (Using Nodemcu-32s 4MB)

#include<TFT_eSPI.h>
#include<SPI.h>
#include<AnimatedGIF.h>

TFT_eSPI tft;
AnimatedGIF gif;
uint8_t *gifArray;
int gifArrayLen;

void setup(){
  tft.init();
  tft.setRotation(2);
  tft.fillScreen(TFT_BLACK);

  File fgif=SD.open("/test.gif",FILE_READ);
  gifArrayLen=fgif.size();
  gifArray=(uint8_t *)malloc(gifArrayLen);
  for(int i=0;i<gifArrayLen;i++) gifArray[i]=fgif.read();
  fgif.close();
}

void loop(){
  tft.startWrite();
  gif.open(gifArray,gifArrayLen*sizeof(uint8_t),GIFDraw);
  while(gif.playFrame(true,NULL)) yield();
  gif.close();
  tft.endWrite();
}

But if gif size > 131KB, it will trigger fatal error like this.

Guru Meditation Error: Core  1 panic'ed (StoreProhibited). Exception was unhandled.

After malloc the array, when I set a value on it, it triggered.

I found some forum says it's because it over the FreeRTOS heap size.

Can I extend the heap size or use another storage method to replace it?


问:
Generate HTML elements automatically with python Flask
So I am using python flask along with some HTML and CSS to create a dynamic website to display reviews about universities. However I am facing a slight issue in that I have flask gives HTML reviews and reviews contain attributes such as username, date, the review comments, and overall rating (out of 5). However for the overall rating I want to display them on the website as starts, so I have 5 stars and have 2 different icons for the starts 1 that is filled and 1 that is hollow, so e.g if a review was rated 3/5 I have 3 filled stars and 2 hollow stars. Currently, I have to "hard code" e.g rating through if statements and it looks messy and doesn't really work well if I have to add other ratings.

HTML code

```<code><section id="reviews">
        <div class="review-box-container">
            <!-- Get all the data from postgres database-->
            {% for review in reviews.items %}
            <div class="review-box">
                <div class="box-top">

                    <div class="profile">
                        <div class="profile-img">
                            <img src="{{ url_for('static', filename='images/Lincoln-Logo.png') }}" width="50" height="50" alt="profile">
                        </div>
                        <div class="name-user">
                            <strong>{{ review.user_name }}</strong>
                            <span> {{ review.date.strftime('%Y-%m-%d') }}</span>
                        </div>
                    </div>

                    <!--Hard coded the overall rating star display (How can I do this better?)-->
                    <div class="review-content">
                        {% if review.overall_rating == 1 %}
                        <i class="fas fa-star"></i>
                        <i class="far fa-star"></i>
                        <i class="far fa-star"></i>
                        <i class="far fa-star"></i>
                        <i class="far fa-star"></i> <!-- Holo star -->
                        {% endif %}
                        {% if review.overall_rating == 2 %}
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="far fa-star"></i>
                        <i class="far fa-star"></i>
                        <i class="far fa-star"></i>
                        {% endif %}
                        {% if review.overall_rating == 3 %}
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="far fa-star"></i>
                        <i class="far fa-star"></i>
                        {% endif %}
                        {% if review.overall_rating == 4 %}
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="far fa-star"></i>
                        {% endif %}
                        {% if review.overall_rating == 5 %}
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        {% endif %}
                    </div>
                </div>

                <div class="review-comment">
                    <p>{{ review.comments}}</p>
                </div>
            </div>
            {% endfor %}
        </div>
    </section>
</code>```

So I am wondering If there is a way to get rid of the if statements for each value from 1 - 5 and do it in a less hardcoded fashion, so it makes it easier when adding other ratings.

答:
you can make two loops in total without if loops, first for loop to print the full stars X times (where X is the rating), and 2nd the half star loop for 5 - X times.

in my example the overall_rating is the variable with value 0 to 5:

jinja template:

```<code>```
{% for ii in range(1, overall_rating + 1) %}

{% endfor %}
{% for ii in range(1, 5 - overall_rating + 1) %}

{% endfor %}
```

Edited to adjust the template more to your case

Body:
So I am using python flask along with some HTML and CSS to create a dynamic website to display reviews about universities. However I am facing a slight issue in that I have flask gives HTML reviews and reviews contain attributes such as username, date, the review comments, and overall rating (out of 5). However for the overall rating I want to display them on the website as starts, so I have 5 stars and have 2 different icons for the starts 1 that is filled and 1 that is hollow, so e.g if a review was rated 3/5 I have 3 filled stars and 2 hollow stars. Currently, I have to "hard code" e.g rating through if statements and it looks messy and doesn't really work well if I have to add other ratings.

HTML code

            {% for review in reviews.items %}

                            {{ review.user_name }}
                             {{ review.date.strftime('%Y-%m-%d') }}

                        {% if review.overall_rating == 1 %}

                        {% endif %}
                        {% if review.overall_rating == 2 %}

                        {% endif %}
                        {% if review.overall_rating == 3 %}

                        {% endif %}
                        {% if review.overall_rating == 4 %}

                        {% endif %}
                        {% if review.overall_rating == 5 %}

                        {% endif %}

{{ review.comments}}

            {% endfor %}

So I am wondering If there is a way to get rid of the if statements for each value from 1 - 5 and do it in a less hardcoded fashion, so it makes it easier when adding other ratings.

Body:
you can make two loops in total without if loops, first for loop to print the full stars X times (where X is the rating), and 2nd the half star loop for 5 - X times.

in my example the overall_rating is the variable with value 0 to 5:

jinja template:

<pre>
{% for ii in range(1, overall_rating + 1) %}
<i class="fas fa-star"></i>
{% endfor %}
{% for ii in range(1, 5 - overall_rating + 1) %}
<i class="far fa-star"></i> <!-- Holo star -->
{% endfor %}

Edited to adjust the template more to your case


问:
Cancel subsequent axios api calls, keep the last
I have a text input which value most be unique, to ensure that, I make an API call every time the input changes its value, giving a instantly feedback to the user of whether the input is valid or not.

There are 2 problems with this aproach:

1- Too many innecesary API calls.

2- When the user types fast enought there is a chance that responses came out of order.

For example: If type "foo bar" there will be 7 request checking for:
"f","fo","foo","foo ","foo b","foo ba","foo bar" in that exact order.
Lets say if "foo ba" is valid but "foo bar" is NOT.
If typing is relativly slow it will be ok but if it is fast enough can happend that response from "foo ba" is returned last, meaning the state will be "valid" when it is not

Posible solution will be that any api call cancels all previus calls in progress.

答:
I think your hunch that doing a call for every character being wrong is correct. You really should either verify on post that the entry is unique, and if not tell the user. If you want more real time feedback, you could send all the current entries from your DB once on page load, and loop through that on the front end (still not a great solution)

if you are married to your idea, you could solve it as follows:

Generate a unique id for each call and include it in your request.

when you make the call, save that id to a variable, something like lastCall.
Every call you make will update the id of last call. Then, when you start getting responses, you only need to react to responses that contain the same id that its in lastCall.

Again, I would recommend changing your approach, but this solution will help fix the issue of calls coming in out of sync. You will still be spamming your backend though.


问:
Retain cycle on `self` with blocks
I'm afraid this question is pretty basic, but I think it's relevant to a lot of Objective-C programmers who are getting into blocks.

What I've heard is that since blocks capture local variables referenced within them as const copies, using self within a block can result in a retain cycle, should that block be copied. So, we are supposed to use __block to force the block to deal directly with self instead of having it copied.

```<code>__block typeof(self) bself = self;
[someObject messageWithBlock:^{ [bself doSomething]; }];
</code>```

instead of just

```<code>[someObject messageWithBlock:^{ [self doSomething]; }];
</code>```

What I'd like to know is the following: if this is true, is there a way that I can avoid the ugliness (aside from using GC)?

答:
Posting another answer because this was a problem for me too. I originally thought I had to use blockSelf anywhere there was a self reference inside a block. This is not the case, it is only when the object itself has a block in it. And in fact, if you use blockSelf in these cases the object can get dealloc'd before you get the result back from the block and then it will crash when it tries to call it, so clearly you want self to be retained until the response comes back.

First case demonstrates when a retain cycle will occur because it contains a block which is referenced in the block:

```<code>#import <Foundation/Foundation.h>

typedef void (^MyBlock)(void);

@interface ContainsBlock : NSObject

@property (nonatomic, copy) MyBlock block;

- (void)callblock;

@end

@implementation ContainsBlock
@synthesize block = _block;

- (id)init {
    if ((self = [super init])) {

        //__block ContainsBlock *blockSelf = self; // to fix use this.
        self.block = ^{
                NSLog(@"object is %@", self); // self retain cycle
            };
    }
    return self;
}

- (void)dealloc {
    self.block = nil;
    NSLog (@"ContainsBlock"); // never called.
    [super dealloc];
}

- (void)callblock {
    self.block();
}

@end

 int main() {
    ContainsBlock *leaks = [[ContainsBlock alloc] init];
    [leaks callblock];
    [leaks release];
}
</code>```

You don't need blockSelf in the second case because the calling object does not have a block in it that will cause a retain cycle when you reference self:

```<code>#import <Foundation/Foundation.h>

typedef void (^MyBlock)(void);

@interface BlockCallingObject : NSObject
@property (copy, nonatomic) MyBlock block;
@end

@implementation BlockCallingObject
@synthesize block = _block;

- (void)dealloc {
    self.block = nil;
    NSLog(@"BlockCallingObject dealloc");
    [super dealloc];
}

- (void)callblock {
    self.block();
}
@end

@interface ObjectCallingBlockCallingObject : NSObject
@end

@implementation ObjectCallingBlockCallingObject

- (void)doneblock {
    NSLog(@"block call complete");
}

- (void)dealloc {
    NSLog(@"ObjectCallingBlockCallingObject dealloc");
    [super dealloc];
}

- (id)init {
    if ((self = [super init])) {

        BlockCallingObject *myobj = [[BlockCallingObject alloc] init];
        myobj.block = ^() {
            [self doneblock]; // block in different object than this object, no retain cycle
        };
        [myobj callblock];
        [myobj release];
    }
    return self;
}
@end

int main() {

    ObjectCallingBlockCallingObject *myObj = [[ObjectCallingBlockCallingObject alloc] init];
    [myObj release];

    return 0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Retain cycle on `self` with blocks

Body:
I'm afraid this question is pretty basic, but I think it's relevant to a lot of Objective-C programmers who are getting into blocks.

What I've heard is that since blocks capture local variables referenced within them as const copies, using self within a block can result in a retain cycle, should that block be copied. So, we are supposed to use __block to force the block to deal directly with self instead of having it copied.

__block typeof(self) bself = self;
[someObject messageWithBlock:^{ [bself doSomething]; }];

instead of just

[someObject messageWithBlock:^{ [self doSomething]; }];

What I'd like to know is the following: if this is true, is there a way that I can avoid the ugliness (aside from using GC)?

Body:
Posting another answer because this was a problem for me too. I originally thought I had to use blockSelf anywhere there was a self reference inside a block. This is not the case, it is only when the object itself has a block in it. And in fact, if you use blockSelf in these cases the object can get dealloc'd before you get the result back from the block and then it will crash when it tries to call it, so clearly you want self to be retained until the response comes back.

First case demonstrates when a retain cycle will occur because it contains a block which is referenced in the block:

#import <Foundation/Foundation.h>

typedef void (^MyBlock)(void);

@interface ContainsBlock : NSObject

@property (nonatomic, copy) MyBlock block;

- (void)callblock;

@end

@implementation ContainsBlock
@synthesize block = _block;

- (id)init {
    if ((self = [super init])) {

        //__block ContainsBlock *blockSelf = self; // to fix use this.
        self.block = ^{
                NSLog(@"object is %@", self); // self retain cycle
            };
    }
    return self;
}

- (void)dealloc {
    self.block = nil;
    NSLog (@"ContainsBlock"); // never called.
    [super dealloc];
}

- (void)callblock {
    self.block();
}

@end

 int main() {
    ContainsBlock *leaks = [[ContainsBlock alloc] init];
    [leaks callblock];
    [leaks release];
}

You don't need blockSelf in the second case because the calling object does not have a block in it that will cause a retain cycle when you reference self:

#import <Foundation/Foundation.h>

typedef void (^MyBlock)(void);

@interface BlockCallingObject : NSObject
@property (copy, nonatomic) MyBlock block;
@end

@implementation BlockCallingObject
@synthesize block = _block;

- (void)dealloc {
    self.block = nil;
    NSLog(@"BlockCallingObject dealloc");
    [super dealloc];
}

- (void)callblock {
    self.block();
}
@end

@interface ObjectCallingBlockCallingObject : NSObject
@end

@implementation ObjectCallingBlockCallingObject

- (void)doneblock {
    NSLog(@"block call complete");
}

- (void)dealloc {
    NSLog(@"ObjectCallingBlockCallingObject dealloc");
    [super dealloc];
}

- (id)init {
    if ((self = [super init])) {

        BlockCallingObject *myobj = [[BlockCallingObject alloc] init];
        myobj.block = ^() {
            [self doneblock]; // block in different object than this object, no retain cycle
        };
        [myobj callblock];
        [myobj release];
    }
    return self;
}
@end

int main() {

    ObjectCallingBlockCallingObject *myObj = [[ObjectCallingBlockCallingObject alloc] init];
    [myObj release];

    return 0;
}


问:
How to create type-hints for method chaining?
I'm writing a library containing an object that allows for method chaining on some of its methods. I'd like to provide users of this library with an easy way to know if any specific method supports chaining (and "users" includes IDEs that offer auto-completion).

According to this question and this question, chaining is easily accomplished by returning self at the end of the method call(s) that support chaining.

However, neither of those questions address how to indicate to a user that a method supports chaining (aside from the obvious docstring comment). As shown in the example code below, I tried to add a type hint, but since the class A isn't fully defined by the time I try to use it in a type hint, Python fails to instantiate an instance of the class.

class A():

    def chain(self) -> A:  # `self` is of type A, so `-> A` is an appropriate return type
        print("Chaining!")
        return self        # Enable method chaining
```
<pre class="lang-py prettyprint-override"><code>>>> A().chain().chain().chain()       # Should print "Chaining!" three times.
Traceback (most recent call last):
  File "scratch.py", line 1, in <module>
    class A():
  File "scratch.py", line 3, in A
    def chain(self) -> A:
NameError: name 'A' is not defined
</code>```

What is an effective way to indicate that a method supports chaining in Python?

An ideal answer will use type hints or some other construct that allows IDEs to support auto-completion.

答:
class A():
    def chain(self) -> 'A':  # `self` is of type A, so `-> A` is an appropriate return type
        print("Chaining!")
        return self

A().chain().chain().chain()
```

In your code A is not defined in quotes so it is counted as a variable

Body:
I'm writing a library containing an object that allows for method chaining on some of its methods. I'd like to provide users of this library with an easy way to know if any specific method supports chaining (and "users" includes IDEs that offer auto-completion).

According to this question and this question, chaining is easily accomplished by returning self at the end of the method call(s) that support chaining.

However, neither of those questions address how to indicate to a user that a method supports chaining (aside from the obvious docstring comment). As shown in the example code below, I tried to add a type hint, but since the class A isn't fully defined by the time I try to use it in a type hint, Python fails to instantiate an instance of the class.

class A():

    def chain(self) -> A:  # `self` is of type A, so `-> A` is an appropriate return type
        print("Chaining!")
        return self        # Enable method chaining

>>> A().chain().chain().chain()       # Should print "Chaining!" three times.
Traceback (most recent call last):
  File "scratch.py", line 1, in <module>
    class A():
  File "scratch.py", line 3, in A
    def chain(self) -> A:
NameError: name 'A' is not defined

What is an effective way to indicate that a method supports chaining in Python?

An ideal answer will use type hints or some other construct that allows IDEs to support auto-completion.

Body:
class A():
    def chain(self) -> 'A':  # `self` is of type A, so `-> A` is an appropriate return type
        print("Chaining!")
        return self

A().chain().chain().chain()

In your code A is not defined in quotes so it is counted as a variable


问:
Why not sprite larger images that are page content?
The typical rule of thumb when it comes to using CSS sprites for images is that you should only do it for smaller images (like icons) and that actual image content should always be represented through  elements. My question is: why? Aren't the advantages of spriting worthwhile for content images as well?

One reason I have read is to enable the use of alt text, to be more syntactically correct and accessible to screen-readers. However, when that is a concern, couldn't you just as easily use a single tiny transparent image with all the syntactical sugar atop a sprite that presents the real visual content?

答:
You could, but:

Content images don’t tend to be re-used as much as UI-type images like icons. Imagine a newspaper site: if every content image they used in every story was part of a sprite, that sprite would very quickly get huge, and would be downloaded even by users who only looked at one story.

Website content is generally expected to be maintained by people who don’t know CSS. It’s a bit unreasonable to expect content editors to edit a master sprite image file, re-save out to a JPG, and pop in some CSS just to put an image on a page.

If you sprite a lot of large image files, the sprite file will get really large. It might take an unacceptably long time to download when the user first visits the page, or it might use up too much bandwidth on users who only end up seeing one of the images within the sprite.

Obviously, those are generalisations — in a specific situation, it might make perfect sense to sprite larger/more content-y images.

On using an  tag with a tiny transparent image file for sprites, you can do that for any sprite images — it’s often useful for clipping and positioning the sprite image beyond what background-position allows.

Body:
You could, but:

Content images don’t tend to be re-used as much as UI-type images like icons. Imagine a newspaper site: if every content image they used in every story was part of a sprite, that sprite would very quickly get huge, and would be downloaded even by users who only looked at one story.

Website content is generally expected to be maintained by people who don’t know CSS. It’s a bit unreasonable to expect content editors to edit a master sprite image file, re-save out to a JPG, and pop in some CSS just to put an image on a page.

If you sprite a lot of large image files, the sprite file will get really large. It might take an unacceptably long time to download when the user first visits the page, or it might use up too much bandwidth on users who only end up seeing one of the images within the sprite.

Obviously, those are generalisations — in a specific situation, it might make perfect sense to sprite larger/more content-y images.

On using an <img> tag with a tiny transparent image file for sprites, you can do that for any sprite images — it’s often useful for clipping and positioning the sprite image beyond what background-position allows.


答:
You can use your class in type hints, according to this excellent post, using your class as string.

In this case, you will need to modify your function signature as the following:

def chain(self) -> "A":
```

Title: How to create type-hints for method chaining?