问:
How to change background image in js file but not hard coding url
I cannot figure out why I can't change background images when I use onmouseover events. My goal is when I put mouse over first pic, then this pic will show up on the top of page, when I move my mouse to another pic, then this new pic will show up on the top instead, then when I move mouse to the third pic, the third pic will show up on the top. Here I attached my html code and js code. Please help me.

function upDate(previewPic){
    // document.getElementById("image").style.backgroundColor = "green";
    document.getElementById("image").style.backgroundColor = "url(previewPic.src)";
    document.getElementById("image").innerHTML = previewPic.alt + ".  this is onmouseover events";
}

function unDo(){
    document.getElementById("image").style.backgroundColor = "#8e68ff";
    document.getElementById("image").innerHTML = "Hover over an image below to display here.";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id = "image">
    Hover over an image below to display here.
</div>

<img class = "preview"
     alt = "Styling with a Bandana"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()">

<img class = "preview"
     alt = "With My Boy"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()">

<img class = "preview"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg"
     alt = "Young Puppy"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()"></code>```

答:
You need to change below things.

div should have backgroundImage not backgroundColor.

you have to set url this way "url('" + previewPic.src + "')"

Remove backgroundImage in unDo() with document.getElementById("image").style.backgroundImage = "";

All you need to update is one line like this document.getElementById("image").style.backgroundImage = "url('" + previewPic.src + "')";

Check your result below.

function upDate(previewPic){
    // document.getElementById("image").style.backgroundColor = "green";
    document.getElementById("image").style.backgroundImage = "url('" + previewPic.src + "')";
    document.getElementById("image").innerHTML = previewPic.alt + ".  this is onmouseover events";
}

function unDo(){
    document.getElementById("image").style.backgroundImage = "";
    document.getElementById("image").style.backgroundColor = "#8e68ff";
    document.getElementById("image").innerHTML = "Hover over an image below to display here.";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id = "image">
    Hover over an image below to display here.
</div>

<img class = "preview"
     alt = "Styling with a Bandana"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()">

<img class = "preview"
     alt = "With My Boy"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()">

<img class = "preview"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg"
     alt = "Young Puppy"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()"></code>```

Body:
I cannot figure out why I can't change background images when I use onmouseover events. My goal is when I put mouse over first pic, then this pic will show up on the top of page, when I move my mouse to another pic, then this new pic will show up on the top instead, then when I move mouse to the third pic, the third pic will show up on the top. Here I attached my html code and js code. Please help me.

function upDate(previewPic){
    // document.getElementById("image").style.backgroundColor = "green";
    document.getElementById("image").style.backgroundColor = "url(previewPic.src)";
    document.getElementById("image").innerHTML = previewPic.alt + ".  this is onmouseover events";
}

function unDo(){
    document.getElementById("image").style.backgroundColor = "#8e68ff";
    document.getElementById("image").innerHTML = "Hover over an image below to display here.";
}

    Hover over an image below to display here.

Body:
You need to change below things.

div should have backgroundImage not backgroundColor.

you have to set url this way "url('" + previewPic.src + "')"

Remove backgroundImage in unDo() with document.getElementById("image").style.backgroundImage = "";

All you need to update is one line like this document.getElementById("image").style.backgroundImage = "url('" + previewPic.src + "')";

Check your result below.

function upDate(previewPic){
    // document.getElementById("image").style.backgroundColor = "green";
    document.getElementById("image").style.backgroundImage = "url('" + previewPic.src + "')";
    document.getElementById("image").innerHTML = previewPic.alt + ".  this is onmouseover events";
}

function unDo(){
    document.getElementById("image").style.backgroundImage = "";
    document.getElementById("image").style.backgroundColor = "#8e68ff";
    document.getElementById("image").innerHTML = "Hover over an image below to display here.";
}

<div id = "image">
    Hover over an image below to display here.
</div>

<img class = "preview"
     alt = "Styling with a Bandana"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()">

<img class = "preview"
     alt = "With My Boy"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()">

<img class = "preview"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg"
     alt = "Young Puppy"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()">


来源: stackexchange

问:
is it possible to create an OBIEE Analytics on user activity report?
I am a BI administrator and author on my OBIEE (12.2.1.3.0). I need to create an analytics on users' browsing history. And then share it to their manager who is just another normal user himself (not an administrator). So I searched on Google for a solution. but, I didn't find anything other than "Manage Sessions" section in administration. However, that just shows online sessions, but I need the report per user and their last login time and browsing information. Besides, I don't want to give the manager administration privilege to access this section. instead, I want to create an analytics for him. but for analytics I need a relevant "Subject Area". I don't know if there is a table in OBIEE repository where I can query from. or generally, I might be thinking incorrectly and there are other ways to handle this kind of requirement. Any idea?

答:
Actually yes, it is possible. As you may know, OBIEE repository tables,  which can be used to show to end users as subject area that this is usgae tracking utility, just track information around sent queries to BI server and not more about users specifically.
In this occasion, you can use a method which called enhanced usage tracking for OBIEE that is presented completely here:
https://www.rittmanmead.com/blog/2016/12/enhanced-usage-tracking-for-obiee-now-available-as-open-source/

This is exactly what you want. All detail information about users activities in OBIEE and enve some redundant ones. You can create a physical table, then add it to repository file and display as subject area to end user with any permission.
Of course, according to your software environment or implementation structure, you are supposed to make some changes in this manner.

I hope this goes well.

ContentLicense: CC BY-SA 4.0


问:
Conditional Aggregation of one column based on values of other in Pyspark
Though I have seen one question on similar lines but it doesn't fit my purpose. So posting it here and looking forward to getting answers.
I have 2 pyspark data frames : Customers weekly spend on the product

Product first and last week of sales

I need to get customers' spend in the category corresponding to each product depending on products' first and last week of sales.
For e.g
Corresponding to Product W, since it was present only in 2nd week, so I need to consider only customers' category spend in 2nd week only

I am struggling to get my head around it but no luck. Looking for suggestions.

答:
I think I get it.  This is more complicated than I would have thought, but I think this does what you want:

```<code>select t1.*, t2.category_spend
from table1 t1 join
     (select t2.product, sum(t1.spend) as category_spend
      from table1 t1 join
           table2 t2
           on t1.week between t2.weekstart between t2.weekend
      group by t2.product
     ) t2w
     on t2w.product = t1.product;
</code>```

EDIT:

Based on your comment, the logic is basically the same.  The customer isn't differentiated it the question, so it can just be included "everywhere":

```<code>select t1.*, t2.category_spend
from table1 t1 join
     (select t1.customer, t2.product, sum(t1.spend) as category_spend
      from table1 t1 join
           table2 t2
           on t1.week between t2.weekstart between t2.weekend
      group by t2.product, t1.customer
     ) t2w
     on t2w.product = t1.product and t2w.customer = t1.customer;
</code>```

Body:
I think I get it.  This is more complicated than I would have thought, but I think this does what you want:

select t1.*, t2.category_spend
from table1 t1 join
     (select t2.product, sum(t1.spend) as category_spend
      from table1 t1 join
           table2 t2
           on t1.week between t2.weekstart between t2.weekend
      group by t2.product
     ) t2w
     on t2w.product = t1.product;

EDIT:

Based on your comment, the logic is basically the same.  The customer isn't differentiated it the question, so it can just be included "everywhere":

select t1.*, t2.category_spend
from table1 t1 join
     (select t1.customer, t2.product, sum(t1.spend) as category_spend
      from table1 t1 join
           table2 t2
           on t1.week between t2.weekstart between t2.weekend
      group by t2.product, t1.customer
     ) t2w
     on t2w.product = t1.product and t2w.customer = t1.customer;


问:
A difficult SQL query: tag popularity for models with complex associations
I'm not even sure this is possible to do efficiently, but here's my problem:

I'm writing what's essentially a blog engine where a blog post and all replies to each blog post can tagged.

So, I could have a blog post tagged "stack", and a reply to that post tagged "overflow".

Right now, I'm trying to generate a list of the most popular tags when a user hits a special page in my application.  It should return not only the n most popular tags by descending number of blog posts, but also the number of blog posts associated with each tag, even if a reply in that post but not the post itself is tagged with that tag.

So, if BlogPost A is tagged with "foo", and a reply in BlogPost B is tagged with "foo", the popular tag summary should count that as two blog posts in total, even though BlogPost B is not technically tagged.

Here's a description of the tables/fields that might be relevant:

```<code>BlogPosts
| id     # Primary key for all tables, Rails-style

BlogComments
| id
| blog_post_id

Tags
| id
| name   # 'foo'

Taggings
| id
| tag_id
| blog_post_id
| blog_comment_id
</code>```

There's some denormalization in Taggings for the sake of convenience.  If someone tags BlogPost, it fills in the blog_post_id field, and blog_comment_id remains NULL.  If someone tags a comment to a post, it fills in both blog_post_id and blog_comment_id.

Is there some way to return a sorted list of the most popular tags in one or several SQL queries?  I'm thinking I might need to just run a computationally-expensive script every few minutes on a cron job and render the cached output instead of running this every time somebody hits the page...

Thanks!

答:
I didn't tried, but what about something like this?:</p>

```<code>select t.Id,
    t.Name,
    count(*)

from Taggings tings
inner join Tags t
    on (t.id = tings.blog_post_id or t.id = tings.blog_comment_id)

group by t.Id, t.Name
order by count(*) desc
</code>```

OwnerDisplayName: O. Frabjous-Dey

ContentLicense: CC BY-SA 2.5

Body:
I'm not even sure this is possible to do efficiently, but here's my problem:

I'm writing what's essentially a blog engine where a blog post and all replies to each blog post can tagged.

So, I could have a blog post tagged "stack", and a reply to that post tagged "overflow".

Right now, I'm trying to generate a list of the most popular tags when a user hits a special page in my application.  It should return not only the n most popular tags by descending number of blog posts, but also the number of blog posts associated with each tag, even if a reply in that post but not the post itself is tagged with that tag.

So, if BlogPost A is tagged with "foo", and a reply in BlogPost B is tagged with "foo", the popular tag summary should count that as two blog posts in total, even though BlogPost B is not technically tagged.

Here's a description of the tables/fields that might be relevant:

BlogPosts
| id     # Primary key for all tables, Rails-style

BlogComments
| id
| blog_post_id

Tags
| id
| name   # 'foo'

Taggings
| id
| tag_id
| blog_post_id
| blog_comment_id

There's some denormalization in Taggings for the sake of convenience.  If someone tags BlogPost, it fills in the blog_post_id field, and blog_comment_id remains NULL.  If someone tags a comment to a post, it fills in both blog_post_id and blog_comment_id.

Is there some way to return a sorted list of the most popular tags in one or several SQL queries?  I'm thinking I might need to just run a computationally-expensive script every few minutes on a cron job and render the cached output instead of running this every time somebody hits the page...

Thanks!

Body:
I didn't tried, but what about something like this?:

select t.Id,
    t.Name,
    count(*)

from Taggings tings
inner join Tags t
    on (t.id = tings.blog_post_id or t.id = tings.blog_comment_id)

group by t.Id, t.Name
order by count(*) desc

OwnerDisplayName: diegojancic


问:
add java applet to php
I'm trying to add java applet to my php code really I'm trying but still have the same error that the applet and the .jar not found can any one give me hello world example for that issue.</p>

答:
Rather that using applet tag look into using object tag instead. Applet is deprecated and isn't supported by all browsers.

And yeah, you don't need any PHP. It's HTML tags.

ContentLicense: CC BY-SA 3.0

Title: add java applet to php


问:
Change chart property with onClick event
I'm trying to change data vizualization with an onClick event. But since property is defined when chart is called I can´t get the property to update. I'm using a button from exporting menu, so I don´t think using a jQuery method to update would work.

What I'm trying to achieve is this:

          customButton: {
            text: "Update",
            onclick: function() {
              if (!isStackingPercentage) {
                handlePercentageClick()
                //redraw chart?
              }
              else if (isStackingPercentage) {
                handleStackingClick()
                //redraw chart?
              }
            }
          }
```

<p>The property is defined this way</p>

<pre class="lang-js prettyprint-override"><code>    plotOptions: {
        column: {
          stacking: isStackingPercentage ? "percent" : "stacking",
          dataLabels: {
            enabled: false
          }
        }
      },
</code>```

Here is a working example

答:
You can access chart reference through this in onclick function and use update method:

```<code>  exporting: {
    buttons: {
      customButton: {
        text: "Update",
        onclick: function() {
          if (!isStackingPercentage) {
            handlePercentageClick();
            this.update({
              plotOptions: {
                column: {
                  stacking: 'percent'
                }
              }
            });
          } else if (isStackingPercentage) {
            handleStackingClick();
            this.update({
              plotOptions: {
                column: {
                  stacking: 'normal'
                }
              }
            });
          }
        }
      }
    }
  }
</code>```

Live demo: https://jsfiddle.net/BlackLabel/rb584w70/

API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update

Body:
I'm trying to change data vizualization with an onClick event. But since property is defined when chart is called I can´t get the property to update. I'm using a button from exporting menu, so I don´t think using a jQuery method to update would work.

What I'm trying to achieve is this:

          customButton: {
            text: "Update",
            onclick: function() {
              if (!isStackingPercentage) {
                handlePercentageClick()
                //redraw chart?
              }
              else if (isStackingPercentage) {
                handleStackingClick()
                //redraw chart?
              }
            }
          }

The property is defined this way

    plotOptions: {
        column: {
          stacking: isStackingPercentage ? "percent" : "stacking",
          dataLabels: {
            enabled: false
          }
        }
      },

Here is a working example

Body:
You can access chart reference through this in onclick function and use update method:

  exporting: {
    buttons: {
      customButton: {
        text: "Update",
        onclick: function() {
          if (!isStackingPercentage) {
            handlePercentageClick();
            this.update({
              plotOptions: {
                column: {
                  stacking: 'percent'
                }
              }
            });
          } else if (isStackingPercentage) {
            handleStackingClick();
            this.update({
              plotOptions: {
                column: {
                  stacking: 'normal'
                }
              }
            });
          }
        }
      }
    }
  }

Live demo: https://jsfiddle.net/BlackLabel/rb584w70/

API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update


问:
Why not use Double or Float to represent currency?
I've always been told never to represent money with double or float types, and this time I pose the question to you: why?

I'm sure there is a very good reason, I simply do not know what it is.

答:
Float is binary form of Decimal with different design; they are two different things. There are little errors between two types when converted to each other. Also, float is designed to represent infinite large number of values for scientific. That means it is designed to lost precision to extreme small and extreme large number with that fixed number of bytes. Decimal can't represent infinite number of values, it bounds to just that number of decimal digits. So Float and Decimal are for different purpose.

There are some ways to manage the error for currency value:

Use long integer and count in cents instead.

Use double precision, keep your significant digits to 15 only so decimal can be exactly simulated. Round before presenting values; Round often when doing calculations.

Use a decimal library like Java BigDecimal so you don't need to use double to simulate decimal.

p.s. it is interesting to know that most brands of handheld scientific calculators works on decimal instead of float. So no one complaint float conversion errors.


问:
Error when starting an application compiled with static linking of libraries in release mode
The launch and operation of my application are possible and successful when compiled in debug mode. Also, the build in release mode does not give any errors.

```<code>21:45:27: Launch: "D:\TTTTTTTTTTTTTTTTTTTTTTTTTTT\qt\Tools\mingw730_64\bin\mingw32-make.exe" -j4
D:\TTTTTTTTTTTTTTTTTTTTTTTTTTT\qt\5.12.7\mingw73_64\bin\qmake.exe -o Makefile ..\B\B.pro -spec win32-g++ "CONFIG+=qtquickcompiler"
D:/TTTTTTTTTTTTTTTTTTTTTTTTTTT/qt/Tools/mingw730_64/bin/mingw32-make -f Makefile.Release
mingw32-make[1]: Entering directory 'C:/Users/**/Desktop/gl/2/BattleShips/build-B-Desktop_Qt_5_12_7_MinGW_64_bit-Release'
mingw32-make[1]: Nothing to be done for 'first'.
mingw32-make[1]: Leaving directory 'C:/Users/**/Desktop/**/2/BattleShips/build-B-Desktop_Qt_5_12_7_MinGW_64_bit-Release'
21:45:29: Process"D:\TTTTTTTTTTTTTTTTTTTTTTTTTTT\qt\Tools\mingw730_64\bin\mingw32-make.exe" ended normally.
21:45:29: Time has passed: 00:02.
</code>```

I focus on:

```<code>mingw32-make[1]: Nothing to be done for 'first'.
</code>```

What is it and what does it do ?

But when I run the (pseudo-) builded application, I get:

```<code>21:25:57: Starting C:\Users\**\Desktop\**\2\BattleShips\build-B-Desktop_Qt_5_12_7_MinGW_64_bit-Release\release\B.exe ...
21:25:57: The process was ended forcefully.
21:25:57: C:\Users\**\Desktop\**\2\BattleShips\build-B-Desktop_Qt_5_12_7_MinGW_64_bit-Release\release\B.exe crashed.
</code>```

when I try to run the builded application manually from the explorer, I get typical link errors (as if dynamic linking of libraries was used)

```<code>Qt5core.dll can not be found
</code>```

and the other about the lack of some gcc libraries.

I suppose there is something wrong with my .pro file.
Here is it:

```<code>static {
    CONFIG += static
    QT += core gui network widgets
    DEFINES += STATIC
    message("Static build.")
}
CONFIG +=  static -std=c++2a

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    battlefield.cpp \
    image.cpp \
    main.cpp \
    player.cpp \
    server.cpp \
    window.cpp

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

FORMS += \
    window.ui

HEADERS += \
    includes.h \
    player.h \
    window.h
</code>```

Ide : windows 10 +  qt 5.12.0 + mingw7.3.0 64 bit provided with qt.

Any suggestions how to build and launch this application properly?

答:
2 things: the Qt files need to be in the PATH and Qt must be able to find its plugins.

You could launch a Command Prompt and run this:

```<code>SET PATH=<qt_path>\bin:$PATH
SET QT_PLUGIN_PATH=<qt_path>\plugins
</code>```

before running your compiled .exe from that same Command Prompt.

Body:
The launch and operation of my application are possible and successful when compiled in debug mode. Also, the build in release mode does not give any errors.

21:45:27: Launch: "D:\TTTTTTTTTTTTTTTTTTTTTTTTTTT\qt\Tools\mingw730_64\bin\mingw32-make.exe" -j4
D:\TTTTTTTTTTTTTTTTTTTTTTTTTTT\qt\5.12.7\mingw73_64\bin\qmake.exe -o Makefile ..\B\B.pro -spec win32-g++ "CONFIG+=qtquickcompiler"
D:/TTTTTTTTTTTTTTTTTTTTTTTTTTT/qt/Tools/mingw730_64/bin/mingw32-make -f Makefile.Release
mingw32-make[1]: Entering directory 'C:/Users/**/Desktop/gl/2/BattleShips/build-B-Desktop_Qt_5_12_7_MinGW_64_bit-Release'
mingw32-make[1]: Nothing to be done for 'first'.
mingw32-make[1]: Leaving directory 'C:/Users/**/Desktop/**/2/BattleShips/build-B-Desktop_Qt_5_12_7_MinGW_64_bit-Release'
21:45:29: Process"D:\TTTTTTTTTTTTTTTTTTTTTTTTTTT\qt\Tools\mingw730_64\bin\mingw32-make.exe" ended normally.
21:45:29: Time has passed: 00:02.

I focus on:

mingw32-make[1]: Nothing to be done for 'first'.

What is it and what does it do ?

But when I run the (pseudo-) builded application, I get:

21:25:57: Starting C:\Users\**\Desktop\**\2\BattleShips\build-B-Desktop_Qt_5_12_7_MinGW_64_bit-Release\release\B.exe ...
21:25:57: The process was ended forcefully.
21:25:57: C:\Users\**\Desktop\**\2\BattleShips\build-B-Desktop_Qt_5_12_7_MinGW_64_bit-Release\release\B.exe crashed.

when I try to run the builded application manually from the explorer, I get typical link errors (as if dynamic linking of libraries was used)

Qt5core.dll can not be found

and the other about the lack of some gcc libraries.

I suppose there is something wrong with my .pro file.
Here is it:

static {
    CONFIG += static
    QT += core gui network widgets
    DEFINES += STATIC
    message("Static build.")
}
CONFIG +=  static -std=c++2a

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    battlefield.cpp \
    image.cpp \
    main.cpp \
    player.cpp \
    server.cpp \
    window.cpp

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

FORMS += \
    window.ui

HEADERS += \
    includes.h \
    player.h \
    window.h

Ide : windows 10 +  qt 5.12.0 + mingw7.3.0 64 bit provided with qt.

Any suggestions how to build and launch this application properly?

Body:
2 things: the Qt files need to be in the PATH and Qt must be able to find its plugins.

You could launch a Command Prompt and run this:

SET PATH=<qt_path>\bin:$PATH
SET QT_PLUGIN_PATH=<qt_path>\plugins

before running your compiled .exe from that same Command Prompt.


问:
How can I automate antivirus/WSUS patch testing of my Windows driver and binary?
My (rather small) company develops a popular Windows application, but one thing we've always struggled with is testing - it frequently is only tested by the developers on a system similar to the one they developed it on, and when an update is pushed out to customers, there is a segment of our base that experiences issues due to some weird functionality with a Windows patch, or in the case of certain paranoid antivirus applications (I'm looking at you, Comodo and Kaspersky!), they will false-positive on our app.

We do manual testing on what 70% of our users use, but it's slow and painful, and sometimes isn't as complete as it should be. Management keeps insisting that we need to do better, but they keep punting on the issue when it comes time to release (testing will take HOW LONG? Just push it out and we'll issue a patch to customers who experience issues!).

I'd like to design a better system of automated testing using VMs, but could use some ideas on how to implement it, or if there's a COTS product out there, any suggestions would be great. I'm hacking a Python script together that "runs" every feature of our product, but I'm not sure how to go about testing if we get a Windows crash (besides just checking to see if it's still in the process list), or worse yet, if Comodo has flagged it for some stupid reason.

To best simulate the test environment, I'm trying to keep the VM as "pure" as possible and not load a lot of crap on it outside of the OS and the antivirus, and some common apps (Acrobat Reader, Firefox etc).

Any ideas would be most appreciated!

答:
Interesting problem. One thing to avoid is using the antivirus APIs to check to see if your application triggers them. You want a real live deployment of your application, on the expected operating system, with a real live AV install monitoring it. That way you'll trigger the heuristics monitoring as well as the simple "does this code match that checksum" that the API works with.

You haven't told us what your application is written in, but if your test suite for your application actually exercises portions of the application, rather than testing single code paths, that may be a good start. Ideally, your integration test suite is the same test suite you use to check for problems on your deploy targets. Your integration testing should verify the input AND the output for each test in a live environment, which SHOULD catch crashes and the like. Also, don't forget to check for things that take much longer than they should, that's an unfortunately common failure mode. Most importantly, your test suite needs to be easy enough to write, change, and improve that it actually stays in sync with the product. Tests that don't test everything are useless, and tests that aren't run are even worse. If we had more information about how your program works, we could give better advice about how to automate that.

You'll probably want a suite of VM images across your intended deploy targets, in various states of patch (and unpatch). For some applications, you'll need a separate VM for each variant of IE, since that changes other aspects of the system. Be very careful about which combination of things you have in each VM. Don't test more than one AV at a time. Update the AVs in your snapshots before running your tests. If you have a large enough combination software in your images, you might need to automate image creation - get a base system build, update to the latest patch level, then script the installation of AV and other application combinations.

Yes, maintaining this farm of VMs will be a pain, but if you script the deploy of your application, and have good snapshots and a plan for patching and updating the snapshots, the actual test suite itself shouldn't take all that long to run given appropriate hardware. You'll need to investigate the VM solutions, but I'd probably start with VMWare.


问:
Confused with rake error in Rails 3
Noob trying to decipher what to do with the following error:

rake aborted!
You have already activated rake 0.9.1, but your Gemfile requires rake 0.8.7. Consider using bundle exec.

Any help is greatly appreciated.

答:
This worked for me:

Add rake 0.8.7 to your Gemfile

```<code>gem 'rake', '0.8.7'
</code>```

remove rake 0.9.1 by doing

```<code>gem uninstall rake -v=0.9.1
</code>```

run bundle update on the terminal

```<code>bundle update
</code>```

Hope that helps.
Thanks

Antonio

Title: Confused with rake error in Rails 3

Body:
This worked for me:

Add rake 0.8.7 to your Gemfile

gem 'rake', '0.8.7'

remove rake 0.9.1 by doing

gem uninstall rake -v=0.9.1

run bundle update on the terminal

bundle update

Hope that helps.
Thanks

Antonio


问:
Rewrite the recursive function into tail recursive function
Problem: Count the number of ways to construct sum n by throwing a dice one or more times. Each throw produces an outcome between 1 and 6.

Solution: I have written a recursive solution for it which outputs correct answer. For large values of n it should hit stack overflow. So I want to avoid it and  rewrite the code using tail recursive approach. Here's my code:

```<code>def numWays(n, arr):
  answer = 0
  for item in arr:
    if item <= n:
      if n == item:
        answer += 1
      else:
        answer += numWays(n-item, arr)

  return answer

li = [i for i in range(1,7)]
print(numWays(5, li)) #example n=5
</code>```

I've seen example of writing factorial function as tail recursive on web but that was easy. Not able to apply that accumulator trick to store the required answer as an additional argument in the function call. Are there any other tricks which work in general?

This could be rewritten as iterative function also but I am looking for ways in general to convert recursive functions to tail-recursive. The given problem, code, and Python is just for an example. Nothing specific about those.

答:
One way for you to get around the stack overflow problem would be to simulate the callstack manually.

def numWays(n, arr):
    call_stack = [(n, arr)]
    answer = 0
    while call_stack:
        n, arr = call_stack.pop(0)
        for item in arr:
            if item <= n:
                if n == item:
                    answer += 1
                else:
                    call_stack.insert(0, (n-item, arr))
    return answer

li = [i for i in range(1, 7)]
print(numWays(5, li))
```

<p>Output:</p>

```16
```

Body:
Problem: Count the number of ways to construct sum n by throwing a dice one or more times. Each throw produces an outcome between 1 and 6.

Solution: I have written a recursive solution for it which outputs correct answer. For large values of n it should hit stack overflow. So I want to avoid it and  rewrite the code using tail recursive approach. Here's my code:

def numWays(n, arr):
  answer = 0
  for item in arr:
    if item <= n:
      if n == item:
        answer += 1
      else:
        answer += numWays(n-item, arr)

  return answer

li = [i for i in range(1,7)]
print(numWays(5, li)) #example n=5

I've seen example of writing factorial function as tail recursive on web but that was easy. Not able to apply that accumulator trick to store the required answer as an additional argument in the function call. Are there any other tricks which work in general?

This could be rewritten as iterative function also but I am looking for ways in general to convert recursive functions to tail-recursive. The given problem, code, and Python is just for an example. Nothing specific about those.

Body:
One way for you to get around the stack overflow problem would be to simulate the callstack manually.

def numWays(n, arr):
    call_stack = [(n, arr)]
    answer = 0
    while call_stack:
        n, arr = call_stack.pop(0)
        for item in arr:
            if item <= n:
                if n == item:
                    answer += 1
                else:
                    call_stack.insert(0, (n-item, arr))
    return answer

li = [i for i in range(1, 7)]
print(numWays(5, li))

Output:

16


问:
C# how to read a low quality barcode?
Goal:

I am aiming to read a bar code that has poor quality. Code works fine if the bar code is in it's highest quality.

Image:

Code:

To crop the barcode code:

```<code>    private Point LocationXY;
    private Point LocationX1Y1;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            LocationXY = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            LocationX1Y1 = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            LocationX1Y1 = e.Location;

            pictureBox1.Invalidate();
            pictureBox2.Invalidate();
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle currentSelection = GetRect();
        if (currentSelection != Rectangle.Empty)
        {
            e.Graphics.DrawRectangle(Pens.Red, currentSelection);
        }
    }

    private void pictureBox2_Paint(object sender, PaintEventArgs e)
    {
        var src = GetRect();

        if (src == Rectangle.Empty) return;

        var des = new Rectangle(0, 0, src.Width, src.Height);

        e.Graphics.DrawImage(pictureBox1.Image,
            des, src, GraphicsUnit.Pixel);
    }

    private Rectangle GetRect()
    {
        return new Rectangle(
            Math.Min(LocationXY.X, LocationX1Y1.X),
            Math.Min(LocationXY.Y, LocationX1Y1.Y),
            Math.Abs(LocationXY.X - LocationX1Y1.X),
            Math.Abs(LocationXY.Y - LocationX1Y1.Y)
            );
    }

    private Bitmap GetCroppedImage()
    {
        var des = GetRect();

        if (des == Rectangle.Empty) return null;

        var b = new Bitmap(des.Width, des.Height);

        using (var g = Graphics.FromImage(b))
        {
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, des.Width, des.Height), des, GraphicsUnit.Pixel);
        }
        return b;

    }
</code>```

Class where the image is saved and able to return the image:

```<code>public class BarcodeImage
{
    private static Image _image;

    public static Image _Image
    {
        get
        {
            return _image;
        }
        set
        {
            _image = value;
        }
    }
}
</code>```

Here I click a button to save the image to class and check the barcode:

```<code>   private void checkBarcode_Click(object sender, EventArgs e)
    {
        BarcodeImage._Image = GetCroppedImage();

        ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
        var result = reader.Decode((Bitmap)BarcodeImage._Image);
        if (result != null)
        {
            MessageBox.Show(result.ToString());
        }
    }
</code>```

Using the code:

Here I highlight the barcode and save it into picturebox2.

Next by clicking checkBarcode_Click it should show the barcode value - but it doesen't. Becasue of the quality of the image.

I have tested it with high quality barcode images and it works fine!

Question:

How can I improve the quality of the Cropped Image and return me the Barcode value?

Edit: 29/05/2020

I have asked a new question on this community seeing if I can I increase size of the cropped image. But that did not improve anything:

https://stackoverflow.com/a/62068397/12485722

High Quality Barcode:

The image is taken out from specific program.

I print screen the images and they must be specifically like this this:

But it does not detect the barcode.

This is a zoomed in version of the image using 2x on the program:

Unfortunately I cannot use the x2 zoom in option as some of the data will move on the image and not giving an accurate final image. On top of that, the barcode is recognized!

答:
You are seeing too much subpixel data loss here for this barcode to be read with any software.

Barcodes work using the relative width of the bars - they are quite clever about how they do this and there is some room for tolerance, but only a small amount.

Here is your original barcode, a scaled up version and a readable version:

If you look at the farthest right bars on yours vs the readable barcode you can see that they are not equal sizes - they should be, but they are not.

The original image is only adequate if it has enough resolution to correctly capture the relative sizes of all bars.

You need to get better data from whatever your source is.

Edit:

Based on your comments, you say you are taking a print-screen of the bartender label - there's no reason you shouldn't be able to zoom to get a higher resolution print-screen, but if you can't then you can print the label to a file/image (such as a PDF) and use that.

It's also worth noting that BarTender has a .NET API that you can talk to directly if you need to, and that the data for BarTender can be exported as an Excel/CSV format (assuming you are using it as a driver for the barcode output).

You also mention that you want to check if a barcode is already in your database - you might be able to do this using the API instead.

I really can't tell you much more since I don't know what data you are generating labels from or if the labels are all ad-hoc; but I know that what you are trying to achieve is entirely possible if you zoom into the image enough to allow enough pixels for the individual barcode bars to render correctly relative to their full width - that's the important bit!

Title: C# how to read a low quality barcode?

Body:
Goal:

I am aiming to read a bar code that has poor quality. Code works fine if the bar code is in it's highest quality.

Image:

Code:

To crop the barcode code:

    private Point LocationXY;
    private Point LocationX1Y1;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            LocationXY = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            LocationX1Y1 = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            LocationX1Y1 = e.Location;

            pictureBox1.Invalidate();
            pictureBox2.Invalidate();
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle currentSelection = GetRect();
        if (currentSelection != Rectangle.Empty)
        {
            e.Graphics.DrawRectangle(Pens.Red, currentSelection);
        }
    }

    private void pictureBox2_Paint(object sender, PaintEventArgs e)
    {
        var src = GetRect();

        if (src == Rectangle.Empty) return;

        var des = new Rectangle(0, 0, src.Width, src.Height);

        e.Graphics.DrawImage(pictureBox1.Image,
            des, src, GraphicsUnit.Pixel);
    }

    private Rectangle GetRect()
    {
        return new Rectangle(
            Math.Min(LocationXY.X, LocationX1Y1.X),
            Math.Min(LocationXY.Y, LocationX1Y1.Y),
            Math.Abs(LocationXY.X - LocationX1Y1.X),
            Math.Abs(LocationXY.Y - LocationX1Y1.Y)
            );
    }

    private Bitmap GetCroppedImage()
    {
        var des = GetRect();

        if (des == Rectangle.Empty) return null;

        var b = new Bitmap(des.Width, des.Height);

        using (var g = Graphics.FromImage(b))
        {
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, des.Width, des.Height), des, GraphicsUnit.Pixel);
        }
        return b;

    }

Class where the image is saved and able to return the image:

public class BarcodeImage
{
    private static Image _image;

    public static Image _Image
    {
        get
        {
            return _image;
        }
        set
        {
            _image = value;
        }
    }
}

Here I click a button to save the image to class and check the barcode:

   private void checkBarcode_Click(object sender, EventArgs e)
    {
        BarcodeImage._Image = GetCroppedImage();

        ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
        var result = reader.Decode((Bitmap)BarcodeImage._Image);
        if (result != null)
        {
            MessageBox.Show(result.ToString());
        }
    }

Using the code:

Here I highlight the barcode and save it into picturebox2.

Next by clicking checkBarcode_Click it should show the barcode value - but it doesen't. Becasue of the quality of the image.

I have tested it with high quality barcode images and it works fine!

Question:

How can I improve the quality of the Cropped Image and return me the Barcode value?

Edit: 29/05/2020

I have asked a new question on this community seeing if I can I increase size of the cropped image. But that did not improve anything:

https://stackoverflow.com/a/62068397/12485722

High Quality Barcode:

The image is taken out from specific program.

I print screen the images and they must be specifically like this this:

But it does not detect the barcode.

This is a zoomed in version of the image using 2x on the program:

Unfortunately I cannot use the x2 zoom in option as some of the data will move on the image and not giving an accurate final image. On top of that, the barcode is recognized!


问:
Unable to create Java Library Binding with native .SO
I am creating a Java Library Binding project. The purpose is to create a simple application for RFID scanning, deployed on a Android-based RFID handheld scanner.
I have native libraries. There is one.JAR and a few.SO files.
I have created a Xamarin Java Binding project in VS2017 and put the .JAR in "Jars" folder. I have set the Build Action to EmbeddedJar.
I have created a separate folder for native libs and in there put the .SO file with Build Action EmbeddedNativeLibrary.
I get the following error on build:

The "CreateNativeLibraryArchive" task failed unexpectedly.
  System.IO.FileNotFoundException: Could not find file 'C:\src\RfidSDK\RfidSDK\obj\Debug__AndroidNativeLibraries__.zip.new'.
  File name: 'C:\src\RfidSDK\RfidSDK\obj\Debug__AndroidNativeLibraries__.zip.new'
     at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
     at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
     at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
     at Xamarin.Android.Tools.Files.CopyIfZipChanged(String source, String destination)
     at Xamarin.Android.Tools.Files.ArchiveZip(String target, Action`1 archiver)
     at Xamarin.Android.Tasks.CreateNativeLibraryArchive.Execute()
     at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
     at Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext()

I am not sure what the issue is...

Many Thanks for any help,

Tried switching the Target framework, no difference.

答: Following the solution in @RoleyBaxter's comment:


问:
Symfony 5 - Multiple client domains
Not too sure on the best way to go about this. But what i'm trying to create is very similar to a generic shared hosting provider but in Symfony.

Lets say i have a site, myawesomesite.com. Users can signup and have their own space myawesomesite.com/sites/theusersdomain.com/.

I can create a route like this, no problems...

```<code>    /**
     * @Route("/sites/{client_website_address}", name="client_public")
     */
    public function _client_index($client_website_address) {

        return new Response($client_website_address);

    }
</code>```

Ultimately i would like the user to have their own domain name pointing to this route. Can this be done through Apache VirtualHost? (I will need this for SSL/TLS cert) I have done this but can't figure out how to point to the route.

```<code>UseCanonicalName Off

LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon

#Client websites
<VirtualHost *:80>

    VirtualDocumentRoot "/var/www/html/myawesomesite.com/public"

    <Directory "/var/www/html/myawesomesite.com/public">
        Options -Indexes +FollowSymLinks
        AllowOverride All
    </Directory>

</VirtualHost>
</code>```

Will i need to add to my current .htaccess file also? My current .htaccess is standard for Symfony.. (i'll probably combine the .htaccess file with the VirtualHosts later)

```<code><IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/index.php [L]
</IfModule>
</code>```

I have researched a few similar like this but nothing that achieves this, unless there is a better way? I need the domains to be dynamic. The user will go to their URL and their doc root should be my Symfony route (https://myawesomesite.com/sites/theusersdomain.com/).

答:
Just for future Googlers.

I decided to rethink and have come up with an easier solution that should work.

Basically keep the VirtualHosts as is and keep the .htaccess file as is.

I have created a separate Symfony controller for clients homepage by detecting the "host" and matching the requirements with regex.

```<code>class ClientController extends AbstractController {

    /**
     * @Route("/", host="{domain_name}", requirements={"domain_name"="^(?!(www\.)?myawesomewebsite\.com$).*$"}, name="client_public")
     */
    public function _client_index() {

        return new Response('This is the client web page controller.');

    }

}
</code>```

It will basically detect any other incoming domain other than my own and match. Probably improvements to be made, but for now this seems to work for my requirements.

Title: Symfony 5 - Multiple client domains

Body:
Not too sure on the best way to go about this. But what i'm trying to create is very similar to a generic shared hosting provider but in Symfony.

Lets say i have a site, myawesomesite.com. Users can signup and have their own space myawesomesite.com/sites/theusersdomain.com/.

I can create a route like this, no problems...

    /**
     * @Route("/sites/{client_website_address}", name="client_public")
     */
    public function _client_index($client_website_address) {

        return new Response($client_website_address);

    }

Ultimately i would like the user to have their own domain name pointing to this route. Can this be done through Apache VirtualHost? (I will need this for SSL/TLS cert) I have done this but can't figure out how to point to the route.

UseCanonicalName Off

LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon

#Client websites
<VirtualHost *:80>

    VirtualDocumentRoot "/var/www/html/myawesomesite.com/public"

    <Directory "/var/www/html/myawesomesite.com/public">
        Options -Indexes +FollowSymLinks
        AllowOverride All
    </Directory>

</VirtualHost>

Will i need to add to my current .htaccess file also? My current .htaccess is standard for Symfony.. (i'll probably combine the .htaccess file with the VirtualHosts later)

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/index.php [L]
</IfModule>

I have researched a few similar like this but nothing that achieves this, unless there is a better way? I need the domains to be dynamic. The user will go to their URL and their doc root should be my Symfony route (https://myawesomesite.com/sites/theusersdomain.com/).

Body:
Just for future Googlers.

I decided to rethink and have come up with an easier solution that should work.

Basically keep the VirtualHosts as is and keep the .htaccess file as is.

I have created a separate Symfony controller for clients homepage by detecting the "host" and matching the requirements with regex.

class ClientController extends AbstractController {

    /**
     * @Route("/", host="{domain_name}", requirements={"domain_name"="^(?!(www\.)?myawesomewebsite\.com$).*$"}, name="client_public")
     */
    public function _client_index() {

        return new Response('This is the client web page controller.');

    }

}

It will basically detect any other incoming domain other than my own and match. Probably improvements to be made, but for now this seems to work for my requirements.


问:
when to use ListPath (querydsl)?
I have a current code that use listPath, but I encounter problems to understand it in order to add changes.

I didn't find useful informations when searching in google.

Any explanation when and how to use it ?

答:
You can for example join a ListPath

Given the entity metamodel:

```<code>@Generated("com.querydsl.codegen.EntitySerializer")
public class QCat extends EntityPathBase<Cat> {
    // Other fields omitted for brevity

    public final ListPath<Cat, QCat> kittens = this.<Cat, QCat>createList("kittens", Cat.class, QCat.class, PathInits.DIRECT2);
</code>```

You could for example do:

```<code>query().from(cat, cats)
           .innerJoin(cat.kittens, kitten).where(kitten.name.eq("Kitty"))
           .select(cat).fetch();
</code>```

Title: when to use ListPath (querydsl)?

Body:
You can for example join a ListPath

Given the entity metamodel:

@Generated("com.querydsl.codegen.EntitySerializer")
public class QCat extends EntityPathBase<Cat> {
    // Other fields omitted for brevity

    public final ListPath<Cat, QCat> kittens = this.<Cat, QCat>createList("kittens", Cat.class, QCat.class, PathInits.DIRECT2);

You could for example do:

query().from(cat, cats)
           .innerJoin(cat.kittens, kitten).where(kitten.name.eq("Kitty"))
           .select(cat).fetch();


问:
Add DropDown without refreshing page
Good Evening, </p>

<p>Could one of you suggest a way to add a dropdown box dynamically without refreshing the page? The dropdown box must not be visible at first, it must then become visible later based on a choice made by the user.  However one constraint is it can only be Javascript, Php, and/or html  </p>

答:
Maybe this is a useful example.</p>

```<code><style type="text/css">
.hidden { display:none }
</style>

<script type="text/javascript">
function show(element, value) {
    switch (element.name) {
        case 'select1':
            switch (value) {
                case '0':
                    document.getElementById('select2').style.display = 'none';
                    document.getElementById('select3').style.display = 'none';
                    break;
                case '1':
                    document.getElementById('select2').style.display = 'inline';
                    document.getElementById('select3').style.display = 'none';
                    break;
                case '2':
                    document.getElementById('select2').style.display = 'none';
                    document.getElementById('select3').style.display = 'inline';
                    break;
            }
            break;
    }
}
</script>

<form>
    <p id="select1">
        <label>Select 1:
            <select name="select1" onchange="show(this, this.value)">
                <option value="0">First</option>
                <option value="1">Second</option>
                <option value="2">Third</option>
            </select>
        </label>
    </p>
    <p id="select2" class="hidden">
        <label>Select 2:
            <select name="select2">
                <option>Option</option>
            </select>
        </label>
    </p>
    <p id="select3" class="hidden">
        <label>Select 3:
            <select name="select3">
                <option>Option</option>
            </select>
        </label>
    </p>
</form>
</code>```

Title: Add DropDown without refreshing page

Body:
Good Evening,

Could one of you suggest a way to add a dropdown box dynamically without refreshing the page? The dropdown box must not be visible at first, it must then become visible later based on a choice made by the user.  However one constraint is it can only be Javascript, Php, and/or html

Body:
Maybe this is a useful example.

<style type="text/css">
.hidden { display:none }
</style>

<script type="text/javascript">
function show(element, value) {
    switch (element.name) {
        case 'select1':
            switch (value) {
                case '0':
                    document.getElementById('select2').style.display = 'none';
                    document.getElementById('select3').style.display = 'none';
                    break;
                case '1':
                    document.getElementById('select2').style.display = 'inline';
                    document.getElementById('select3').style.display = 'none';
                    break;
                case '2':
                    document.getElementById('select2').style.display = 'none';
                    document.getElementById('select3').style.display = 'inline';
                    break;
            }
            break;
    }
}
</script>

<form>
    <p id="select1">
        <label>Select 1:
            <select name="select1" onchange="show(this, this.value)">
                <option value="0">First</option>
                <option value="1">Second</option>
                <option value="2">Third</option>
            </select>
        </label>
    </p>
    <p id="select2" class="hidden">
        <label>Select 2:
            <select name="select2">
                <option>Option</option>
            </select>
        </label>
    </p>
    <p id="select3" class="hidden">
        <label>Select 3:
            <select name="select3">
                <option>Option</option>
            </select>
        </label>
    </p>
</form>


问:
idVendor for apple.developer.driverkit.transport.usb
I was reading this informative post
How to set `com.apple.developer.driverkit.transport.usb` entitlement?

I wanted to ask, where do I get this idVendor from? What should be its value ?

答:
This is the Vendor ID of the device your driver will be driving. Apple asks for this when you request DriverKit entitlements, and you are presumably specifying it in your dext's IOKit personality's matching dictionary.

Note that vendor IDs are conventionally written in hexadecimal, but plists (Info.plist and the entitlements file) use decimal notation for numbers, so make sure you convert the value first.


问:
How do I download email attachemnts with IMAP and PHP?
I am trying to retrieve a file that is emailed to me every day as an attachment.  I need to retrieve the attachment to my Linux server.  What is the simplest way to make this happen?

Thanks for any help!

Chris

答: The simplest way for me is to use a library for this task. For example my favorite is Zeta Components - Mail which have a good tutorial.</p>


问:
Django-Tinymce Import Error
I am trying to follow this tutorial on getting tinymce working with django and zinnia. It's not working, so I am attempting to do "Testing" but get this error when I run django-admin.py syncdb. How do I fix this?

```<code>$django-admin.py syncdb
Traceback (most recent call last):
  File "/usr/local/bin/django-admin.py", line 5, in <module>
    pkg_resources.run_script('Django==1.5.1', 'django-admin.py')
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 505, in run_script
    self.require(requires)[0].run_script(script_name, ns)
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 1245, in run_script
    execfile(script_filename, namespace, namespace)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/EGG-INFO/scripts/django-admin.py", line 5, in <module>
    management.execute_from_command_line()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/core/management/__init__.py", line 453, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/core/management/__init__.py", line 263, in fetch_command
    app_name = get_commands()[subcommand]
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/core/management/__init__.py", line 109, in get_commands
    apps = settings.INSTALLED_APPS
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/conf/__init__.py", line 48, in _setup
    self._wrapped = Settings(settings_module)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/conf/__init__.py", line 134, in __init__
    raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'testtinymce.staticfiles_settings' (Is it on sys.path?): No module named staticfiles_settings
</code>```

Thank you.

答:
The latest version of tinymce has a different configuration.
instead of Importing HTMLField like
    from tinymce import HTMLField
but rather
    from tinymce.models import HTMLField</p>

Title: Django-Tinymce Import Error

Body:
I am trying to follow this tutorial on getting tinymce working with django and zinnia. It's not working, so I am attempting to do "Testing" but get this error when I run django-admin.py syncdb. How do I fix this?

$django-admin.py syncdb
Traceback (most recent call last):
  File "/usr/local/bin/django-admin.py", line 5, in <module>
    pkg_resources.run_script('Django==1.5.1', 'django-admin.py')
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 505, in run_script
    self.require(requires)[0].run_script(script_name, ns)
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 1245, in run_script
    execfile(script_filename, namespace, namespace)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/EGG-INFO/scripts/django-admin.py", line 5, in <module>
    management.execute_from_command_line()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/core/management/__init__.py", line 453, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/core/management/__init__.py", line 263, in fetch_command
    app_name = get_commands()[subcommand]
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/core/management/__init__.py", line 109, in get_commands
    apps = settings.INSTALLED_APPS
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/conf/__init__.py", line 48, in _setup
    self._wrapped = Settings(settings_module)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.1-py2.7.egg/django/conf/__init__.py", line 134, in __init__
    raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'testtinymce.staticfiles_settings' (Is it on sys.path?): No module named staticfiles_settings

Thank you.


问:
React exporting context returns Parsing error: Export 'SearchContextConsumer' is not defined
I am trying to create a context in order to pass data to another component without using props drilling, but when I export my consumer I get that Parsing error: Export 'SearchContextConsumer' is not defined
What seems to be the problem and how can I export it successfully?

Here is my code:

```<code>import React, { Component } from "react";
import axios from "axios";

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    SearchContext = React.createContext('context');
    SearchContextConsumer = SearchContext.Consumer;
    data = { searchResults: this.state.searchResults }

    Search = ({ children }) => (
        <SearchContext.Provider value={searchResults}>{children}</SearchContext.Provider>
    )

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (
            <div>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </div>
        );
    }
}

export { SearchContextConsumer }
export default Search;

</code>```

答:
You can't export a property of a class this way.

I think the simplest and cleanest way to do what you have in mind is to create your context outside of your class like this:

```<code>import React, { Component } from "react";
import axios from "axios";

const SearchContext = React.createContext();

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    data = { searchResults: this.state.searchResults }

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (
            <SearchContext.Provider value={searchResults}>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </SearchContext.Provider>
        );
    }
}

export SearchContext.Consumer as SearchContextConsumer
export default Search;
</code>```

and here is how you can do above functionality in Function Component which is more readable and less code:

```<code>import React, { Component } from "react";
import axios from "axios";

const SearchContext = React.createContext();

const Search = () => {
  const [state, setState] = useState({
    searchResults: [],
    isSearched: false
  });

  const getSearchQuery = event => {
    const queryString = document.querySelector(".search-input").value;

    if (event.keyCode === 13) {
      axios
        .post("http://localhost:3001/search", {
          queryString: queryString
        })
        .then(response => {
          setState({ ...state, searchResults: response.data });
        });
      setState({ ...state, isSearched: true });
      window.location.href = "/blog/searchResults";
    }
  };

  return (
    <SearchContext.Provider value={state.searchResults}>
      <input
        type="text"
        className="search-input"
        onKeyDown={e => getSearchQuery(e)}
      />
    </SearchContext.Provider>
  );
};

export default Search;
</code>```

now if you need to use your context data just do this inside provider zone:

```<code>const searchResults = React.useContext(SearchContext);
</code>```

Body:
I am trying to create a context in order to pass data to another component without using props drilling, but when I export my consumer I get that Parsing error: Export 'SearchContextConsumer' is not defined
What seems to be the problem and how can I export it successfully?

Here is my code:

import React, { Component } from "react";
import axios from "axios";

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    SearchContext = React.createContext('context');
    SearchContextConsumer = SearchContext.Consumer;
    data = { searchResults: this.state.searchResults }

    Search = ({ children }) => (
        <SearchContext.Provider value={searchResults}>{children}</SearchContext.Provider>
    )

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (

                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />

        );
    }
}

export { SearchContextConsumer }
export default Search;

Body:
You can't export a property of a class this way.

I think the simplest and cleanest way to do what you have in mind is to create your context outside of your class like this:

import React, { Component } from "react";
import axios from "axios";

const SearchContext = React.createContext();

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    data = { searchResults: this.state.searchResults }

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (
            <SearchContext.Provider value={searchResults}>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </SearchContext.Provider>
        );
    }
}

export SearchContext.Consumer as SearchContextConsumer
export default Search;

and here is how you can do above functionality in Function Component which is more readable and less code:

import React, { Component } from "react";
import axios from "axios";

const SearchContext = React.createContext();

const Search = () => {
  const [state, setState] = useState({
    searchResults: [],
    isSearched: false
  });

  const getSearchQuery = event => {
    const queryString = document.querySelector(".search-input").value;

    if (event.keyCode === 13) {
      axios
        .post("http://localhost:3001/search", {
          queryString: queryString
        })
        .then(response => {
          setState({ ...state, searchResults: response.data });
        });
      setState({ ...state, isSearched: true });
      window.location.href = "/blog/searchResults";
    }
  };

  return (
    <SearchContext.Provider value={state.searchResults}>
      <input
        type="text"
        className="search-input"
        onKeyDown={e => getSearchQuery(e)}
      />
    </SearchContext.Provider>
  );
};

export default Search;

now if you need to use your context data just do this inside provider zone:

const searchResults = React.useContext(SearchContext);


问:
Discord.py on_message() but only for private messages
So, I'm working on a discord bot. And am using the on_message() event, which works both on private messages and on servers. I want this to only work in private messages and am unsure of how to go about this.
If anyone can help me, that would be great.</p>
```<code>import os
import discord
from discord.ext import commands

TOKEN = ''
quotedUsers = []

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.change_presence(activity=discord.Game(name='with myself.'))

@client.event
async def on_message(message):
    await message.author.send("Recieved: " + message.content)

@client.command()
async def search(ctx, *, question):
    await ctx.author.send("Searching: " + question)

client.run(TOKEN)
</code>```

答:
A message guild also doesn't exist in a group DM, so you have to check if the channel you messaging in is a DM. You can use the dm_channel attribute of a user:

@client.event
async def on_message(message):
    if message.channel.id == message.author.dm_channel.id: # dm only
        # do stuff here #
    elif not message.guild: # group dm only
        # do stuff here #
    else: # server text channel
        # do stuff here #
```

Body:
So, I'm working on a discord bot. And am using the on_message() event, which works both on private messages and on servers. I want this to only work in private messages and am unsure of how to go about this.
If anyone can help me, that would be great.

import os
import discord
from discord.ext import commands

TOKEN = ''
quotedUsers = []

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.change_presence(activity=discord.Game(name='with myself.'))

@client.event
async def on_message(message):
    await message.author.send("Recieved: " + message.content)

@client.command()
async def search(ctx, *, question):
    await ctx.author.send("Searching: " + question)

client.run(TOKEN)


问:
change JStree icon with material icons
I can change JStree icon with fontawesome and glyphicon using code like this:

```<code><li data-jstree='{"icon":"fa fa-user"}'>
<li data-jstree='{"icon":"glyphicon glyphicon-print"}'>
</code>```

How to use Material Icons?

I tried

```<code><li data-jstree='{"icon":"material-icons add"}'>
</code>```

But doesn't work

答:
I can do it by including this stylesheet:

https://github.com/Angelmmiguel/material_icons/blob/master/app/assets/stylesheets/material_icons_unicode.css.erb

after I include above file as CSS  I can use code below to use material-icons:

```<code><li data-jstree='{"icon":"material-icons add"}'>
</code>```

Title: change JStree icon with material icons

Body:
I can change JStree icon with fontawesome and glyphicon using code like this:

How to use Material Icons?

I tried

But doesn't work

Body:
I can do it by including this stylesheet:

https://github.com/Angelmmiguel/material_icons/blob/master/app/assets/stylesheets/material_icons_unicode.css.erb

after I include above file as CSS  I can use code below to use material-icons:

<li data-jstree='{"icon":"material-icons add"}'>


问:
PHP Using code as a function, variables not working
I've got this code which works well standalone:

```<code>file_put_contents('dataFile', implode('',
    array_map(function($data) {
    return stristr($data,"NSQ = ") ? "NSQ = school\n" : $data;
    }, file('dateFile'))
));
</code>```

This reads dataFile and finds the entry NSQ = and updates it to be NSQ = school

I'm going to reuse this multple times so changed it into a function:

```<code>function updatesite($site) {
file_put_contents('dataFile', implode('',
    array_map(function($data) {
    return stristr($data,"$site = ") ? "$site = school\n" : $data;
    }, file('dateFile'))
));
}
</code>```

Initially, I got an error that $site didn't exist, so I added global $site; before the return.

That stopped the error, but it doesn't update the file.

Is there any way I can use a variable like this?

答:
You can use use to pass variables to a function callback like this:

```<code>function updatesite($site) {
    file_put_contents('dataFile', implode('',
        array_map(function($data) use ($site) {
            return stristr($data,"$site = ") ? "$site = school\n" : $data;
        }, file('dateFile'))
    ));
}
</code>```

Body:
I've got this code which works well standalone:

file_put_contents('dataFile', implode('',
    array_map(function($data) {
    return stristr($data,"NSQ = ") ? "NSQ = school\n" : $data;
    }, file('dateFile'))
));

This reads dataFile and finds the entry NSQ = and updates it to be NSQ = school

I'm going to reuse this multple times so changed it into a function:

function updatesite($site) {
file_put_contents('dataFile', implode('',
    array_map(function($data) {
    return stristr($data,"$site = ") ? "$site = school\n" : $data;
    }, file('dateFile'))
));
}

Initially, I got an error that $site didn't exist, so I added global $site; before the return.

That stopped the error, but it doesn't update the file.

Is there any way I can use a variable like this?

Body:
You can use use to pass variables to a function callback like this:

function updatesite($site) {
    file_put_contents('dataFile', implode('',
        array_map(function($data) use ($site) {
            return stristr($data,"$site = ") ? "$site = school\n" : $data;
        }, file('dateFile'))
    ));
}


问:
TortoiseGit pulling from all branches not considering remote branch
I am not able to make tortoisegit (win 10) to pull ONLY my remote branch info. It always pull all the remote branch info taking 5-10 mins.

What I tried from tortoise git

Internally tortoise executes

```<code>  git.exe pull --progress -v --no-rebase --depth 1 "origin"
</code>```

rather than below leading to downloading everything info

```<code> git pull --progress -v --no-rebase --depth 1 "origin" "kamet_556_108_py377"
</code>```

I set the tracking branch to point to kamet_556_108_py377 ( Where is "remote tracking branch" in TortoiseGit? )

From Git bash console:

```<code>$  git checkout  -f --recurse-submodule -B kamet_556_108_py377 origin/kamet_556_108_py377
Reset branch 'kamet_556_108_py377'
Branch 'kamet_556_108_py377' set up to track remote branch 'kamet_556_108_py377' from 'origin'.
Your branch is up to date with 'origin/kamet_556_108_py377'.
</code>```

Can anyone point me what am I doing wrong here ?

答:
I do not want to download all the remote info info every time when do TortoiseGit->Pull. Similar issue was reported by another user 4 yrs back [https://gitlab.com/tortoisegit/tortoisegit/-/issues/202]

As per that, I disabled tracking by remote branch as below and now I am able to pull only info regarding my private branch kamet_556_108_py377 under few secs (from  mins)

Body:
I am not able to make tortoisegit (win 10) to pull ONLY my remote branch info. It always pull all the remote branch info taking 5-10 mins.

What I tried from tortoise git

Internally tortoise executes

  git.exe pull --progress -v --no-rebase --depth 1 "origin"

rather than below leading to downloading everything info

 git pull --progress -v --no-rebase --depth 1 "origin" "kamet_556_108_py377"

I set the tracking branch to point to kamet_556_108_py377 ( Where is "remote tracking branch" in TortoiseGit? )

From Git bash console:

$  git checkout  -f --recurse-submodule -B kamet_556_108_py377 origin/kamet_556_108_py377
Reset branch 'kamet_556_108_py377'
Branch 'kamet_556_108_py377' set up to track remote branch 'kamet_556_108_py377' from 'origin'.
Your branch is up to date with 'origin/kamet_556_108_py377'.

Can anyone point me what am I doing wrong here ?


Title: Rewrite the recursive function into tail recursive function

Body:
Problem: Count the number of ways to construct sum n by throwing a dice one or more times. Each throw produces an outcome between 1 and 6.

Solution: I have written a recursive solution for it which outputs correct answer. For large values of n it should hit stack overflow. So I want to avoid it and  rewrite the code using tail recursive approach. Here's my code:

def numWays(n, arr):
  answer = 0
  for item in arr:
    if item <= n:
      if n == item:
        answer += 1
      else:
        answer += numWays(n-item, arr)

  return answer

li = [i for i in range(1,7)]
print(numWays(5, li)) #example n=5

I've seen example of writing factorial function as tail recursive on web but that was easy. Not able to apply that accumulator trick to store the required answer as an additional argument in the function call. Are there any other tricks which work in general?

This could be rewritten as iterative function also but I am looking for ways in general to convert recursive functions to tail-recursive. The given problem, code, and Python is just for an example. Nothing specific about those.

Body:
Here's a simple solution, no recursion, no nothing, O(N):

#!/usr/bin/env python

DICE = 6    # how many sides our dice has

rolls = [1]
for i in range(1,800) :
    rolls.append(sum(rolls[-min(i,DICE):]))

print rolls[:16]  # print results for the first 16 (zero-based!!)
print rolls[610]  # print result for 610 steps

Result:

[1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840, 7617, 15109]
14527490260516100855695859704819627818108010882741117227956927412305738742399171256642436462028811566617818991926058940988565927870172608545709804976244851391054850231415387973537361

Easily can calculate the number of rolls for N=50000 or 500000.


问:
Referencing an attribute for a simple tag and Struts 2.x
I am writing a simple tag which contains 4 attributes like so:

```<code><%@ taglib prefix="s" uri="/struts-tags"%>
<%@ attribute name="menuName" description="Name of Major Menu" required="true" %>
<%@ attribute name="menuSize" description="Number of Items In Menu" required="true" type="java.lang.Integer" %>
<%@ attribute name="menuImage" description="Icon for Image" required="true" %>
<%@ attribute name="menuNumber" description="Order of Positioning" required="true" %>
</code>```

There is a point within a Struts 2 tag that I need to make reference to one of these attributes like so:

```<code><s:set name="it" value="%{#application['tools'][${menuName}]}" />
</code>```

So you see I am doing a lookup in the OGNL expression based upon what the menu name which was passed in.  From all the examples I see, EL is the common way of referencing the attribute menuName, but in Struts 2.x EL is disabled for security reasons.

Is there a way to reference the attribute I need to reference.  I really do not want to consider any solution which involves me going to previous versions of jstl or struts.

答:
```<code><s:set name="menuName" value="%{#attr['menuName']}" />
<s:set name="it" value="%{#application['tools'][#menuName]}" />
</code>```

Never knew about the #attr before, how neat

Body:
I am writing a simple tag which contains 4 attributes like so:

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ attribute name="menuName" description="Name of Major Menu" required="true" %>
<%@ attribute name="menuSize" description="Number of Items In Menu" required="true" type="java.lang.Integer" %>
<%@ attribute name="menuImage" description="Icon for Image" required="true" %>
<%@ attribute name="menuNumber" description="Order of Positioning" required="true" %>

There is a point within a Struts 2 tag that I need to make reference to one of these attributes like so:

<s:set name="it" value="%{#application['tools'][${menuName}]}" />

So you see I am doing a lookup in the OGNL expression based upon what the menu name which was passed in.  From all the examples I see, EL is the common way of referencing the attribute menuName, but in Struts 2.x EL is disabled for security reasons.

Is there a way to reference the attribute I need to reference.  I really do not want to consider any solution which involves me going to previous versions of jstl or struts.

Body:
<s:set name="menuName" value="%{#attr['menuName']}" />
<s:set name="it" value="%{#application['tools'][#menuName]}" />

Never knew about the #attr before, how neat


问:
jest error: const warnedKeys: {[string]: boolean} = {};
If I run yarn test, which runs jest, I get the following error:

```<code>C:\react-native-project\node_modules\react-native\Libraries\Utilities\warnOnce.js:15
    const warnedKeys: {[string]: boolean} = {};
</code>```

But that only happens if I follow the directions of the react-native-testing-library:

Then automatically to add it to your jest tests by using setupFilesAfterEnv option in the
  jest.config.js file:

If I remove the file I will not get that error and I can get simple tests to run. When I remove the file, the test runs but AsyncStorage is not recognized so the tests still don't run. I have AsyncStorage. It's installed and the app works, but I want to add component tests. I also noticed the file, jest.config.js, is conspicuously missing from the testing project itself. Is there any documentation or working example? I would rather not do a diff of my project and the testing project. Is there a more well-documented or reliable testing framework/module available?

答: I'm able to get working tests by following the documentation of the React Native Testing Library with the npm package name of @testing-library/react-native not to be confused with the React Native Testing Library with the npm package name of react-native-testing-library. Both packages allow testing components and are recommended by React-Native documentation but this one works when following the instructions. It also has instructions "to define a custom render method that includes things like global context providers, data stores, etc" so that testing components with AsyncStorage and such shouldn't be a problem.

Body:
If I run yarn test, which runs jest, I get the following error:

C:\react-native-project\node_modules\react-native\Libraries\Utilities\warnOnce.js:15
    const warnedKeys: {[string]: boolean} = {};

But that only happens if I follow the directions of the react-native-testing-library:

Then automatically to add it to your jest tests by using setupFilesAfterEnv option in the
  jest.config.js file:

If I remove the file I will not get that error and I can get simple tests to run. When I remove the file, the test runs but AsyncStorage is not recognized so the tests still don't run. I have AsyncStorage. It's installed and the app works, but I want to add component tests. I also noticed the file, jest.config.js, is conspicuously missing from the testing project itself. Is there any documentation or working example? I would rather not do a diff of my project and the testing project. Is there a more well-documented or reliable testing framework/module available?


问:
How to prevent white text from CSS file from appearing in rendered React app?
I am trying to render a button in React that changes text and color when you click on it.

I got it to work, but whenever I render the app, the title from the head of the index.html file and the text from the App.module.css file appear on the page (in white text). I have searched for a solution, but I cannot seem to find one.

Btn.js

```<code>import styles from './App.module.css';

const Btn = ({toggleIt, toggle}) => {
  return(
    <>
     <button onClick={toggleIt} className={toggle ? styles.btntrue : styles.btnfalse}>
        {toggle ? "true" : "false"}
      </button>
    </>
  );
}

export default Btn;
</code>```

App.module.css

```<code>* {
  color: white;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
}

.btntrue {
  background-color: green
  ;
}

.btnfalse {
  background-color: red
  ;
}
</code>```

App.js

```<code>import Btn from "./btn"

function App() {
  const [toggle, setToggle] = useState(false)

  const toggleIt = () => {
    setToggle(!toggle)
  }

  return (
  <React.Fragment>
    <Btn
      toggleIt = {toggleIt}
      toggle = {toggle}
    />
  </React.Fragment>

  );
}

export default App;
</code>```

Index.js (for completeness sake)

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

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

Index.html

```<code><!DOCTYPE html>
<html lang="en">

  <head>
    <title>Button</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="Web site created using create-react-app" />
  </head>

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

  </body>

</html>
</code>```

How can I remove this text from the screen or is it always there and you have to style around it?

Error message one

Error message two

Body:
I am trying to render a button in React that changes text and color when you click on it.

I got it to work, but whenever I render the app, the title from the head of the index.html file and the text from the App.module.css file appear on the page (in white text). I have searched for a solution, but I cannot seem to find one.

Btn.js

import styles from './App.module.css';

const Btn = ({toggleIt, toggle}) => {
  return(
    <>
     <button onClick={toggleIt} className={toggle ? styles.btntrue : styles.btnfalse}>
        {toggle ? "true" : "false"}
      </button>
    </>
  );
}

export default Btn;

App.module.css

* {
  color: white;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
}

.btntrue {
  background-color: green
  ;
}

.btnfalse {
  background-color: red
  ;
}

App.js

import Btn from "./btn"

function App() {
  const [toggle, setToggle] = useState(false)

  const toggleIt = () => {
    setToggle(!toggle)
  }

  return (
  <React.Fragment>
    <Btn
      toggleIt = {toggleIt}
      toggle = {toggle}
    />
  </React.Fragment>

  );
}

export default App;

Index.js (for completeness sake)

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

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

Index.html

<!DOCTYPE html>

    <title>Button</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="Web site created using create-react-app" />

    You need to enable JavaScript to run this app.

How can I remove this text from the screen or is it always there and you have to style around it?

Error message one

Error message two

Body:
Your CSS file is declaring all elements to be visible with white text, including normally-invisible ones like <style> or <title>:

* { /* Make ALL elements... */
  display: flex; /* ...displayed visibly, with "flex" display type... */
  color: white; /* ...and white text */
}

Normally, things like <style> have display: none by default to make them hidden, but here you explicitely overwrite it by display: flex.

You should instead apply these styles only to the elements that need it, instead of * (all elements). Look into scoped CSS in React to see how to apply CSS rules only to elements inside a certain component.

The issue with your existing approach was that CSS scoping in React works mainly by appending unique suffixes to class names (so your btntrue class may become btntrue_a732uw or something like that, making sure that no two btntrue class names of different components will clash), however if you don't use a class name for a rule (such as you do with *), it also can't be scoped! You can avoid that by using .allflex * for example, instead of just *, and then applying the allflex class name to your component's root element.


问:
regex check if text between two strings contains a certain word
I have the following text:

Best Content Marketing Tips to Make Your Website Standout from the Rest

I need to find out with regex if text between the words "Best" and "Rest" contains word "marketing":

My formula is as follows: (?<=Best|)(marketing?)(?=Rest).

This formula works only if I want to find a word exactly before the "Rest", which in this case is "the ".

How do I make it to search if any word between two specified strings matches my Keyword?

答:
Perform a case-insensitive search for a regex pattern inside a string,
with the pattern having the word 'Best', then any number of any characters,
then a specified keyword (e.g. 'marketing'), then any number of any characters again, and finally the word 'Rest':

```<code>import re

text = "Best Content Marketing Tips to Make Your Website Standout from the Rest"

Keyword = "marketing"  # Customize your search-word here

pattern = re.compile(r"Best.*({}).*Rest".format(Keyword), re.I)
print("Found match in text: \n", pattern.search(text))

# See if your keyword was matched inside the searched text:
print("\nFound following keyword in text:\n", pattern.search(text).group(1))
</code>```

Output:

```<code>Found match in text:
 <re.Match object; span=(0, 71), match='Best Content Marketing Tips to Make Your Website >

Found following keyword in text:
 Marketing

</code>```

Body:
Perform a case-insensitive search for a regex pattern inside a string,
with the pattern having the word 'Best', then any number of any characters,
then a specified keyword (e.g. 'marketing'), then any number of any characters again, and finally the word 'Rest':

import re

text = "Best Content Marketing Tips to Make Your Website Standout from the Rest"

Keyword = "marketing"  # Customize your search-word here

pattern = re.compile(r"Best.*({}).*Rest".format(Keyword), re.I)
print("Found match in text: \n", pattern.search(text))

# See if your keyword was matched inside the searched text:
print("\nFound following keyword in text:\n", pattern.search(text).group(1))

Output:

Found match in text:
 <re.Match object; span=(0, 71), match='Best Content Marketing Tips to Make Your Website >

Found following keyword in text:
 Marketing


问:
Render another root path with own routes
I am trying to figure render a complete seperate admin path with its own routes.

Is it possible to render say admin page that is with and existing project.

At the moment I have the following code it is working very well.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './client/App.js';
import Admin from './admin/admin.js';

var pathname = window.location.pathname;

if (pathname.substring(0, 6) == '/admin') {
  ReactDOM.render(<Admin />, document.getElementById('root'));
} else {
  ReactDOM.render(<App />, document.getElementById('root'));
}
</code>```

答: I'm struggling to understand what you want to do exactly. You already have everything you need, Admin and App are components and therefore small projects I would say. However, you shouldn't do it that way and instead use react-router it avoids you to check the window location pathname by yourself and will save you a lof of time and headache.

Body:
I am trying to figure render a complete seperate admin path with its own routes.

Is it possible to render say admin page that is with and existing project.

At the moment I have the following code it is working very well.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './client/App.js';
import Admin from './admin/admin.js';

var pathname = window.location.pathname;

if (pathname.substring(0, 6) == '/admin') {
  ReactDOM.render(<Admin />, document.getElementById('root'));
} else {
  ReactDOM.render(<App />, document.getElementById('root'));
}