问:
Oracle SQL - Count only one of specified value
I do hope someone can help me with this.

I am doing two count functions on on of my columns, both specified by where the column has a specific text (see below code). On my count for meeting (WHERE EVENT_TYPE = 'meeting_start'), I have found that this can pop up more than once within the same meeting. I need to only count this once per meeting event id and cannot find a way to do this.

```<code>select I.CRM_INSTANCE_NAME,
       C.CUSTOMER_NAME,
       U.USER_NAME,
       ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0') AS USER_ACTIVATION_DATE,
       ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0') AS LAST_ACTIVITY_DATE,
       COUNT(E.EVENT_TYPE) AS MEETING,
       COUNT(F.EVENT_TYPE) AS FINALISED

       FROM SBX_USERS U
        LEFT JOIN SBX_CUSTOMERS C on U.CUSTOMER_ID = C.CUSTOMER_ID
        LEFT JOIN SBX_CRM_INSTANCES I on C.CRM_INSTANCE_ID = I.CRM_INSTANCE_ID
        LEFT JOIN SBX_MEETING M on U.USER_ID = M.USER_ID
        LEFT JOIN SBX_EVENTS E ON SOURCE_ID  = M.MEETING_ID
        LEFT JOIN (SELECT * FROM SBX_EVENTS WHERE EVENT_TYPE = 'meeting_start' AND EVENT_CREATION_DATE >=add_months(sysdate, -12)) E on E.SOURCE_ID = M.MEETING_ID
        LEFT JOIN (SELECT * FROM SBX_EVENTS WHERE EVENT_TYPE = 'finalize'AND EVENT_CREATION_DATE >=add_months(sysdate, -12)) F on F.SOURCE_ID = M.MEETING_ID

where U.ENABLED_FLAG IN ('Y','E')

group by  I.CRM_INSTANCE_NAME, C.CUSTOMER_NAME, U.USER_NAME, ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0'), ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0')
order by  I.CRM_INSTANCE_NAME;
</code>```

Above is the code I am using at that moment, thanks in advance for your help.

Regards

Dr

答:
In essence, I think that you want COUNT(DISTINCT ...).

But also, your query is not valid SQL: you have two aliases called E:  the logic that joins sbx_events is problematic. I suspect that you actually want one join on that table (with a join condition on the date), and conditional aggregation in the COUNT(DISTINCT).

That would be:

```<code>select
    i.crm_instance_name,
    c.customer_name,
    u.user_name,
    ltrim(to_char(u.created_date ,'mm-yyyy'),'0') as user_activation_date,
    ltrim(to_char(u.last_updated_date ,'dd-mm-yyyy'),'0') as last_activity_date,
    count(distinct case when event_type = 'meeting_start'  then m.meeting_id end) as meeting,
    count(distinct case when event_type = 'finalize'  then m.meeting_id end) as finalized
from sbx_users u
left join sbx_customers c
    on u.customer_id = c.customer_id
left join sbx_crm_instances i
    on c.crm_instance_id = i.crm_instance_id
left join sbx_meeting m
    on u.user_id = m.user_id
left join sbx_events e
    on source_id  = m.meeting_id
    and  e.event_creation_date >= add_months(sysdate, -12))
where u.enabled_flag in ('y','e')
group by
    i.crm_instance_name,
    c.customer_name,
    u.user_name,
    ltrim(to_char(u.created_date ,'mm-yyyy'),'0'),
    ltrim(to_char(u.last_updated_date ,'dd-mm-yyyy'),'0')
order by  i.crm_instance_name;
</code>```

Body:
I do hope someone can help me with this.

I am doing two count functions on on of my columns, both specified by where the column has a specific text (see below code). On my count for meeting (WHERE EVENT_TYPE = 'meeting_start'), I have found that this can pop up more than once within the same meeting. I need to only count this once per meeting event id and cannot find a way to do this.

select I.CRM_INSTANCE_NAME,
       C.CUSTOMER_NAME,
       U.USER_NAME,
       ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0') AS USER_ACTIVATION_DATE,
       ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0') AS LAST_ACTIVITY_DATE,
       COUNT(E.EVENT_TYPE) AS MEETING,
       COUNT(F.EVENT_TYPE) AS FINALISED

       FROM SBX_USERS U
        LEFT JOIN SBX_CUSTOMERS C on U.CUSTOMER_ID = C.CUSTOMER_ID
        LEFT JOIN SBX_CRM_INSTANCES I on C.CRM_INSTANCE_ID = I.CRM_INSTANCE_ID
        LEFT JOIN SBX_MEETING M on U.USER_ID = M.USER_ID
        LEFT JOIN SBX_EVENTS E ON SOURCE_ID  = M.MEETING_ID
        LEFT JOIN (SELECT * FROM SBX_EVENTS WHERE EVENT_TYPE = 'meeting_start' AND EVENT_CREATION_DATE >=add_months(sysdate, -12)) E on E.SOURCE_ID = M.MEETING_ID
        LEFT JOIN (SELECT * FROM SBX_EVENTS WHERE EVENT_TYPE = 'finalize'AND EVENT_CREATION_DATE >=add_months(sysdate, -12)) F on F.SOURCE_ID = M.MEETING_ID

where U.ENABLED_FLAG IN ('Y','E')

group by  I.CRM_INSTANCE_NAME, C.CUSTOMER_NAME, U.USER_NAME, ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0'), ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0')
order by  I.CRM_INSTANCE_NAME;

Above is the code I am using at that moment, thanks in advance for your help.

Regards

Dr

Body:
In essence, I think that you want COUNT(DISTINCT ...).

But also, your query is not valid SQL: you have two aliases called E:  the logic that joins sbx_events is problematic. I suspect that you actually want one join on that table (with a join condition on the date), and conditional aggregation in the COUNT(DISTINCT).

That would be:

select
    i.crm_instance_name,
    c.customer_name,
    u.user_name,
    ltrim(to_char(u.created_date ,'mm-yyyy'),'0') as user_activation_date,
    ltrim(to_char(u.last_updated_date ,'dd-mm-yyyy'),'0') as last_activity_date,
    count(distinct case when event_type = 'meeting_start'  then m.meeting_id end) as meeting,
    count(distinct case when event_type = 'finalize'  then m.meeting_id end) as finalized
from sbx_users u
left join sbx_customers c
    on u.customer_id = c.customer_id
left join sbx_crm_instances i
    on c.crm_instance_id = i.crm_instance_id
left join sbx_meeting m
    on u.user_id = m.user_id
left join sbx_events e
    on source_id  = m.meeting_id
    and  e.event_creation_date >= add_months(sysdate, -12))
where u.enabled_flag in ('y','e')
group by
    i.crm_instance_name,
    c.customer_name,
    u.user_name,
    ltrim(to_char(u.created_date ,'mm-yyyy'),'0'),
    ltrim(to_char(u.last_updated_date ,'dd-mm-yyyy'),'0')
order by  i.crm_instance_name;


来源: stackexchange

问:
Spark [Scala] Timestamp field being converted into string even after explicit casting while doing "filter"
I have a dataframe, say df1, which I am trying to filter based on a date range.

Example:

```<code>| id | name | disconnect_dt_time  |
|----|------|---------------------|
| 1  | "a"  | 2020-05-19 00:00:00 |
| 2  | "b"  | 2020-05-20 00:00:00 |

val df = spark.table("df1")
               .filter(col("disconnect_dt_time").cast("timestamp").between(analysisStartDate , analysisEndDate) )
</code>```

I am getting the below issue:

Reason: [ cannot resolve '((((CAST(CAST(df1.disconnect_dt_time AS
  TIMESTAMP) AS STRING) >= '20200520T00:00:00+0000') AND
  (CAST(CAST(df1.disconnect_date_datetime AS
  TIMESTAMP) AS STRING) <= '20200530T00:00:00+0000'))

What is the reason for this double casting? CAST(CAST(df1.disconnect_dt_time AS TIMESTAMP) AS STRING)? How can this be fixed?

答:
Try this-

 val data =
      """
        |id | name | disconnect_dt_time
        |1  | "a"  | 2020-05-10 00:00:00
        |2  | "b"  | 2020-05-20 00:00:00
      """.stripMargin

    val stringDS = data.split(System.lineSeparator())
      .map(_.split("\\|").map(_.replaceAll("""^[ \t]+|[ \t]+$""", "")).mkString(","))
      .toSeq.toDS()
    val df = spark.read
      .option("sep", ",")
      .option("inferSchema", "true")
      .option("header", "true")
      .csv(stringDS)
    df.show(false)
    df.printSchema()

    /**
      * +---+----+-------------------+
      * |id |name|disconnect_dt_time |
      * +---+----+-------------------+
      * |1  |a   |2020-05-10 00:00:00|
      * |2  |b   |2020-05-20 00:00:00|
      * +---+----+-------------------+
      *
      * root
      * |-- id: integer (nullable = true)
      * |-- name: string (nullable = true)
      * |-- disconnect_dt_time: timestamp (nullable = true)
      */
    df.createOrReplaceTempView("df1")

    val analysisStartDate = "20200515T00:00:00+0000"
    val analysisEndDate = "20200530T00:00:00+0000"
    val fmt = "yyyyMMdd'T'HH:mm:ssZ"
    val processedDF = spark.table("df1")
      .filter(col("disconnect_dt_time").cast("timestamp")
        .between(to_timestamp(lit(analysisStartDate), fmt) , to_timestamp(lit(analysisEndDate), fmt)) )
    processedDF.show(false)

    /**
      * +---+----+-------------------+
      * |id |name|disconnect_dt_time |
      * +---+----+-------------------+
      * |2  |b   |2020-05-20 00:00:00|
      * +---+----+-------------------+
      */
```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe, say df1, which I am trying to filter based on a date range.

Example:

| id | name | disconnect_dt_time  |
|----|------|---------------------|
| 1  | "a"  | 2020-05-19 00:00:00 |
| 2  | "b"  | 2020-05-20 00:00:00 |

val df = spark.table("df1")
               .filter(col("disconnect_dt_time").cast("timestamp").between(analysisStartDate , analysisEndDate) )

I am getting the below issue:

Reason: [ cannot resolve '((((CAST(CAST(df1.disconnect_dt_time AS
  TIMESTAMP) AS STRING) >= '20200520T00:00:00+0000') AND
  (CAST(CAST(df1.disconnect_date_datetime AS
  TIMESTAMP) AS STRING) <= '20200530T00:00:00+0000'))

What is the reason for this double casting? CAST(CAST(df1.disconnect_dt_time AS TIMESTAMP) AS STRING)? How can this be fixed?


问:
Getting length of
 when using Bootstrap 4 tab-content
I am a bit stuck on this. I am trying to get the length of a list using Bootstrap 4's tab-content. Since the tab is not active on page load, the length is 0. When I open the tab, it is still 0.

I added the html that gets printed as well as the ajax call to get the data.

// print applicant status
if (applicantStatus == 'true') {
  $('#aStatus').html('Applicant');

  // video module count
  var totalModCount = $("#vidList").find("li").length;
  console.log(totalModCount); // 0 Supposed to be 9
  $('#totalCount').html(totalModCount)

  // form total count
  var totalFormCount = $("#vidList").find("li").length;
  console.log(totalFormCount); // 0 Supposed to be 4
  $('#formTotalCount').html(totalFormCount);
}
else {
  $('#aStatus').html('Employee');
};

var listOfTypes = "";
$.each(parsedData, function (index, item) {

  var dateOfCompletion = moment(item.DateCompleted).format('MM/DD/YYYY');
  lastAttempt = moment(item.DateOfExam).format('MM/DD/YYYY');
  isValid = item.Valid;
  isOrientation = item.IsOrientation;
  isInservice = item.IsInservice;

  if (applicantStatus == "true") {
    if (isOrientation) {
      if (isValid) {
        if (item.IsComplete == true) {
          listOfTypes += "
";
          listOfTypes += item.TypeName + "";
          listOfTypes += "

Completed on: " + dateOfCompletion + "

";

        }
        else {
          listOfTypes += "
";
          listOfTypes += item.TypeName + "";
          listOfTypes += "

Time Duration: " + item.Duration + "

";
        }
      }
      else {
        listOfTypes += "
";
        listOfTypes += item.TypeName + "";
      }
    }
  }
});
```

<pre class="lang-html prettyprint-override"><code><div class='tab-content'>
  <div id="videoList" class="tab-pane fade">
    <ul class='list-group' id='vidList'>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
    </ul>
  </div>
  <div id="formsList" class="tab-pane fade">
    <ul class='list-group' id='fList'>
      <li class="list-group-item formItem"></li>
      <li class="list-group-item formItem"></li>
      <li class="list-group-item formItem"></li>
      <li class="list-group-item formItem"></li>
    </ul>
  </div>
</div>
</code>```

答:
If the call is asynchronous, you need to check after you have loaded the tabs. So take the below code and its respective function into the callback function of the async call and check.

```<code>var totalModCount = $("#vidList").find("li").length;
</code>```

Until then it's going to be empty.

Title: Getting length of <li> when using Bootstrap 4 tab-content

Body:
If the call is asynchronous, you need to check after you have loaded the tabs. So take the below code and its respective function into the callback function of the async call and check.

var totalModCount = $("#vidList").find("li").length;

Until then it's going to be empty.


问:
get data from MarketWatch
Using BeautifulSoup I am trying to scrape MarketWatch

```<code>from bs4 import BeautifulSoup
import requests
import pandas

url = "https://www.marketwatch.com/investing/stock/khc/profile"
# Make a GET request to fetch the raw HTML content
html_content = requests.get(url).text

soup = BeautifulSoup(html_content, "lxml")
</code>```

Now I would like to extract the "P/E Current" and the "Price to Sales Ratio" that in the html are in the class

```<code>[...]
<div class="sixwide addgutter">

    <div class="block threewide addgutter">

        <h2>Valuation</h2>
                <div class="section">
            <p class="column">P/E Current</p>
            <p class="data lastcolumn">19.27</p>
        </div>
                <div class="section">
            <p class="column">P/E Ratio (with extraordinary items)</p>
            <p class="data lastcolumn">19.55</p>
        </div>
                <div class="section">
            <p class="column">P/E Ratio (without extraordinary items)</p>
            <p class="data lastcolumn">20.00</p>
        </div>
                <div class="section">
            <p class="column">Price to Sales Ratio</p>
            <p class="data lastcolumn">1.55</p>
        </div>
                <div class="section">
            <p class="column">Price to Book Ratio</p>
            <p class="data lastcolumn">0.75</p>
        </div>
        [...]
</code>```

How can I get them?

I use the command

```<code>section = soup.findAll('div', {'class' : 'section'})
</code>```

but then I don't know how to go ahead to get the values I am interested in, can you help?

答:
You can do the following

find all sections

loop through the sections and find its p elements

if the p contains your search text, get its next sibling with the value.

```<code>url = "https://www.marketwatch.com/investing/stock/khc/profile"
html_content = requests.get(url).text

soup = BeautifulSoup(html_content, "lxml")
sections = soup.findAll('div', attrs={'class' : 'section'})
for section in sections :
    ps = section.find('p')
    if "P/E Current" in ps.getText() or "Price to Sales Ratio" in ps.getText():
    val = ps.nextSibling.nextSibling
    print(f"{ps.getText()}: {val.getText()}")

OUT: P/E Current: 19.27
     Price to Sales Ratio: 1.55
</code>```

Title: get data from MarketWatch

Body:
Using BeautifulSoup I am trying to scrape MarketWatch

from bs4 import BeautifulSoup
import requests
import pandas

url = "https://www.marketwatch.com/investing/stock/khc/profile"
# Make a GET request to fetch the raw HTML content
html_content = requests.get(url).text

soup = BeautifulSoup(html_content, "lxml")

Now I would like to extract the "P/E Current" and the "Price to Sales Ratio" that in the html are in the class

[...]

Valuation

P/E Current

19.27

P/E Ratio (with extraordinary items)

19.55

P/E Ratio (without extraordinary items)

20.00

Price to Sales Ratio

1.55

Price to Book Ratio

0.75

        [...]

How can I get them?

I use the command

section = soup.findAll('div', {'class' : 'section'})

but then I don't know how to go ahead to get the values I am interested in, can you help?

Body:
You can do the following

find all sections

loop through the sections and find its p elements

if the p contains your search text, get its next sibling with the value.

url = "https://www.marketwatch.com/investing/stock/khc/profile"
html_content = requests.get(url).text

soup = BeautifulSoup(html_content, "lxml")
sections = soup.findAll('div', attrs={'class' : 'section'})
for section in sections :
    ps = section.find('p')
    if "P/E Current" in ps.getText() or "Price to Sales Ratio" in ps.getText():
    val = ps.nextSibling.nextSibling
    print(f"{ps.getText()}: {val.getText()}")

OUT: P/E Current: 19.27
     Price to Sales Ratio: 1.55


问:
How to resize window using WinAPI
I'm want to resize a window using WinAPI. I use a WinAPI function:

```<code>SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
</code>```

The window is resized, but its content is not redrawn. If I resize this window using the mouse, the content redraws. How to resize window using WinAPI with content redrawing?

答:
Write this code in window procedure:

Code:

```<code>case WM_SIZE:
    {
        HWND groupControl;
        RECT rcClient;//screen size

        GetClientRect(hwnd, &rcClient);

        groupControl = GetDlgItem(hwnd,Id);//get the id of control
        SetWindowPos(groupControl, NULL, rcClient.right-50,
         rcClient.bottom-50, 20, 20,
          SWP_NOZORDER);//set a coordinate of control and
       height and width.
    }
</code>```

Title: How to resize window using WinAPI

Body:
I'm want to resize a window using WinAPI. I use a WinAPI function:

SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);

The window is resized, but its content is not redrawn. If I resize this window using the mouse, the content redraws. How to resize window using WinAPI with content redrawing?

Body:
Write this code in window procedure:

Code:

case WM_SIZE:
    {
        HWND groupControl;
        RECT rcClient;//screen size

        GetClientRect(hwnd, &rcClient);

        groupControl = GetDlgItem(hwnd,Id);//get the id of control
        SetWindowPos(groupControl, NULL, rcClient.right-50,
         rcClient.bottom-50, 20, 20,
          SWP_NOZORDER);//set a coordinate of control and
       height and width.
    }


问:
SQL Server paging using limit and offset with non-unique ordering column
I would like to implement paging using SQL Server limit and offset as shown below. My question is, will SQL Server guerantee the correct data page when data is ordered by non-unique column?

```<code>SELECT * FROM TableName
ORDER BY NonUniqueColumn
OFFSET 10 ROWS
FETCH NEXT 20 ROWS ONLY
OPTION (recompile)

SELECT * FROM TableName
ORDER BY NonUniqueColumn
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY
OPTION (recompile)
</code>```

These two selects overlap. Will the second select (second page) contain the last ten rows from the first select?

答:
will SQL Server guerantee the correct data page when data is ordered by non-unique column?

No. Add the primary key columns to the ORDER BY to guarantee a stable ordering.  EG

```<code>SELECT * FROM TableName
ORDER BY NonUniqueColumn, Id
OFFSET 10 ROWS
FETCH NEXT 20 ROWS ONLY
OPTION (recompile)
</code>```

Body:
I would like to implement paging using SQL Server limit and offset as shown below. My question is, will SQL Server guerantee the correct data page when data is ordered by non-unique column?

SELECT * FROM TableName
ORDER BY NonUniqueColumn
OFFSET 10 ROWS
FETCH NEXT 20 ROWS ONLY
OPTION (recompile)

SELECT * FROM TableName
ORDER BY NonUniqueColumn
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY
OPTION (recompile)

These two selects overlap. Will the second select (second page) contain the last ten rows from the first select?

Body:
will SQL Server guerantee the correct data page when data is ordered by non-unique column?

No. Add the primary key columns to the ORDER BY to guarantee a stable ordering.  EG

SELECT * FROM TableName
ORDER BY NonUniqueColumn, Id
OFFSET 10 ROWS
FETCH NEXT 20 ROWS ONLY
OPTION (recompile)


问:
How can I eliminate spacing between inline elements in CSS?
I have a div with a bunch of image tags inside, here is an example:

```<code><div style="margin: 0; padding: 0; border: 0;">
    <a href="/view/foo1"><img src="foo1.jpg" alt="Foo1" /></a>
    <a href="/view/foo2"><img src="foo2.jpg" alt="Foo2" /></a>
    <a href="/view/foo3"><img src="foo3.jpg" alt="Foo3" /></a>
</div>
</code>```

Because there is whitespace between the tags, browsers will display some whitespace between the images (Chrome decides on 4px). How can I tell the browser to show NO whitespace whatsoever between the images, without placing the > and < directly next to each other? I know letter-spacing applies in addition to what the browser decides to use, so that's useless even with a negative value. Basically I'm going for something like Twitter has at the bottom of their home page. I looked at their code and they're using an unordered list. I could just do that but I'd like the technical explanation for why there appears to be no way to eliminate the white space from between these images.

答:
If you are serving your pages with Apache then you can use the Google PageSpeed Module. This has options that you can use to collapse whitespace:

http://code.google.com/speed/page-speed/docs/filter-whitespace-collapse.html

You do not have to use the more 'dangerous' options of PageSpeed.

Also see the answers in this question for how to remove whitespace in CSS:

Ignore whitespace in HTML

ContentLicense: CC BY-SA 3.0

Body:
I have a div with a bunch of image tags inside, here is an example:

Because there is whitespace between the tags, browsers will display some whitespace between the images (Chrome decides on 4px). How can I tell the browser to show NO whitespace whatsoever between the images, without placing the > and < directly next to each other? I know letter-spacing applies in addition to what the browser decides to use, so that's useless even with a negative value. Basically I'm going for something like Twitter has at the bottom of their home page. I looked at their code and they're using an unordered list. I could just do that but I'd like the technical explanation for why there appears to be no way to eliminate the white space from between these images.


问:
How to catch html compile errors from invalid attributes by binding in AngularJS
I'm quite new to AngularJS.
So I have an SVG which I need to modify from the controller:

```<code><svg class="rotate" viewbox="0 0 250 250">
   <path transform="translate(125, 125)" d="{{user.timerAnim}}"/>
</svg>
</code>```

user.timerAnim is populated from the controller in a timeout.
This works, but it throws exceptions to the console, because initially the browser reads the d attribute as invalid, after which AngularJS binds to it and starts working normally.

I had a similar problem before with img tag's src attribute, which had a solution by using ng-src

How do I catch these errors? Is this not a good way to animate an SVG in AngularJS?

答:
instead of catching an error, that is possibile by a function and getting the d value from it you can achieve this problem with an ng-if like this</p>

```<code><svg class="rotate" viewbox="0 0 250 250" ng-if="user && user.timerAnim && user.timerAnim != null">
       <path transform="translate(125, 125)" d="{{user.timerAnim}}"/>
    </svg>
</code>```

Body:
I'm quite new to AngularJS.
So I have an SVG which I need to modify from the controller:

<svg class="rotate" viewbox="0 0 250 250">
   <path transform="translate(125, 125)" d="{{user.timerAnim}}"/>
</svg>

user.timerAnim is populated from the controller in a timeout.
This works, but it throws exceptions to the console, because initially the browser reads the d attribute as invalid, after which AngularJS binds to it and starts working normally.

I had a similar problem before with img tag's src attribute, which had a solution by using ng-src

How do I catch these errors? Is this not a good way to animate an SVG in AngularJS?

Body:
instead of catching an error, that is possibile by a function and getting the d value from it you can achieve this problem with an ng-if like this

<svg class="rotate" viewbox="0 0 250 250" ng-if="user && user.timerAnim && user.timerAnim != null">
       <path transform="translate(125, 125)" d="{{user.timerAnim}}"/>
    </svg>


问:
How do I use cookies in express session - connect.sid will soon be rejected
So in my app.js file I have this: app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false}));

This works fine but comes up with a warning:

Cookie “connect.sid” will be soon rejected because it has the
  “sameSite” attribute set to “none” or an invalid value, without the
  “secure” attribute. To learn more about the “sameSite“ attribute, read
  https://developer.mozilla.org/docs/Web/HTTP/Cookies

Then it will randomly stop working. If I change session to this: app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false, sameSite: true, cookie: {secure: true}}));it becomes undefined.

I am trying to save 2 different id's: req.session.qrID and req.session.visitID;

It is used in a number of post requests. What can I do to make this work?

答:
I've just googled this warning i saw in the console and got here LOL.
It's actually related to express session cookie cross site policy that is set, more info here under cookie.sameSite
http://expressjs.com/en/resources/middleware/session.html

I got rid of mine by setting it to strict but you can also set it to none if you want

```<code>app.use(
session({
    secret: process.env.SESSION_SECRET!,
    resave: false,
    saveUninitialized: false,
    cookie: { sameSite: 'strict' },
  }),
);
</code>```

Body:
I've just googled this warning i saw in the console and got here LOL.
It's actually related to express session cookie cross site policy that is set, more info here under cookie.sameSite
http://expressjs.com/en/resources/middleware/session.html

I got rid of mine by setting it to strict but you can also set it to none if you want

app.use(
session({
    secret: process.env.SESSION_SECRET!,
    resave: false,
    saveUninitialized: false,
    cookie: { sameSite: 'strict' },
  }),
);


问:
IE11 JAWS accessibility issue with role alert
role alert is read by JAWS 2020.2001.70 in chrome, firefox but its not reading in Microsoft IE11 and Edge.

The same is also working with mac voiceover in chrome and firefox.

We need to write "show" in the text input and "Role is working" will be automatically read due to role=alert (without tab out)

$(".container > input").keyup(function(){
  if(event.target.value === "show"){
    $(".dl").removeClass("dl_hide");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dl_hide{
  display : none;
}</code>```

  <input type="text" name="your_name" value="" />

   Role is working

```

答:
Firstly, the live region should be present in the DOM at page load. (Not set to display: none.) Now there are exceptions to this as some screen reader/browser combinations do support dynamic loading of live regions. However, as you've noticed with IE, it does not.

Secondly, aria-live regions are only supposed to be read out loud when there is an update to the live region's content.

Try this approach instead:

```<code>   <div class="container">
        <input type="text" name="your_name" value="" />
        <div class="dl" role="alert"></div>
    </div>

 $(".container > input").keyup(function () {
    if (event.target.value === "show") {
        $("div.dl").text("Role is working");
    }
});
</code>```

Body:
role alert is read by JAWS 2020.2001.70 in chrome, firefox but its not reading in Microsoft IE11 and Edge.

The same is also working with mac voiceover in chrome and firefox.

We need to write "show" in the text input and "Role is working" will be automatically read due to role=alert (without tab out)

$(".container > input").keyup(function(){
  if(event.target.value === "show"){
    $(".dl").removeClass("dl_hide");
  }
});

.dl_hide{
  display : none;
}

  <input type="text" name="your_name" value="" />

   Role is working

Body:
Firstly, the live region should be present in the DOM at page load. (Not set to display: none.) Now there are exceptions to this as some screen reader/browser combinations do support dynamic loading of live regions. However, as you've noticed with IE, it does not.

Secondly, aria-live regions are only supposed to be read out loud when there is an update to the live region's content.

Try this approach instead:

   <div class="container">
        <input type="text" name="your_name" value="" />
        <div class="dl" role="alert"></div>
    </div>

 $(".container > input").keyup(function () {
    if (event.target.value === "show") {
        $("div.dl").text("Role is working");
    }
});


问:
pkg-config glib-2.0 error on Mac OS X
I've got some C code which won't compile.

The error message when I run "make" is:

```<code>gcc -Wall -Wno-pointer-sign -g `pkg-config --cflags glib-2.0 gconf-2.0`
 \      -c main.c Package glib-2.0 was not found in the pkg-config search
path. Perhaps you should add the directory containing `glib-2.0.pc' to
the PKG_CONFIG_PATH environment variable No package 'glib-2.0' found
</code>```

Doing a quick search on the Mac using locate I can't see any glib-2.0 files so I'm wondering if I have to install it. And, if so, what's the best way of doing so?

答:
Answer for internet searching this,

In linux

sudo apt-get install libgtk2.0-dev

Title: pkg-config glib-2.0 error on Mac OS X

Body:
I've got some C code which won't compile.

The error message when I run "make" is:

gcc -Wall -Wno-pointer-sign -g `pkg-config --cflags glib-2.0 gconf-2.0`
 \      -c main.c Package glib-2.0 was not found in the pkg-config search
path. Perhaps you should add the directory containing `glib-2.0.pc' to
the PKG_CONFIG_PATH environment variable No package 'glib-2.0' found

Doing a quick search on the Mac using locate I can't see any glib-2.0 files so I'm wondering if I have to install it. And, if so, what's the best way of doing so?


问:
Is ASMX WebService or WCF or aspx pages are async by default?
I involved my self within a bet, our feud is about - Async WebServices and the other stuff i mentioned above.

I am thinking logically web service by default is sync, the other said that it is not correct.
Who is right or wrong can any one explain it to me?

Thanks in advance.

答:
All of them are by default synchronous but you can write all of them asynchronously and you can call all of them asynchronously. You should always differ between synchronous/asynchronous call and between synchronous/asynchronous execution.

Calls

Synchronous - client calls the service/page and hangs on until the service/page returns the response.

Asynchronous - client calls the service/page and can continue in work. Client is usually notified by some event (or it can poll the result) that response has arrived. In ASPX this is typical callback or AJAX call.

Execution:

Synchronous - service/page receives the call and process it. Every external processing (file access, calling other services, calling database) is done synchronously and the service/page block the executing thread for the whole duration of the request processing.

Asynchronous - service/page receives the call, prepares external processing and executes it asynchronously. Processing thread is returned back to thread pool and can server other requests in the meanwhile. Once external processing ends service/page execution is again scheduled to receive a thread from thread pool and it finishes execution and returns response. This is usually only need on high traffic pages/services with intensive external communication.

These two types of asynchronous processing are completely independent. You can have asynchronous calls to synchronous services and any other combination.


问:
PostgreSQL: Finding students that have failed in more than 1 subject in their class (marks < 50)
I have a school table with 6 students each in class 1 and class 2, where each student has 5 subjects.

The table looks like this -

```<code>student_id      Standard       subject_id       marks
1               1              1                 30
2               1              1                 45
3               1              1                 45
4               1              1                 55
5               1              1                 80
6               1              1                 20
1               1              2                 40
2               1              2                 75
3               1              2                 25
4               1              2                 40
</code>```

Standard is the class of the student.

My question is I need to calculate the number of students that have failed in more than 1 subject in their class (marks < 50)

So far my failed attempt:

```<code>select count(*) from
(select student_id, marks < 50 as fail_value from school
group by 1,2
having count(subject_id) > 1
) as alias
where fail_value = 'true'
</code>```

For reference, the expected result for the above table should look like this:

```<code>count_student_id
      2
</code>```

答:
The derived table (the subquery) will return each student_id having more than one marks < 50 class. Count the number of rows returned.

```<code>select count(*)
from
(
  select student_id
  from school
  where marks < 50
  group by student_id
  having count(subject_id) > 1
) as dt
</code>```

Body:
I have a school table with 6 students each in class 1 and class 2, where each student has 5 subjects.

The table looks like this -

student_id      Standard       subject_id       marks
1               1              1                 30
2               1              1                 45
3               1              1                 45
4               1              1                 55
5               1              1                 80
6               1              1                 20
1               1              2                 40
2               1              2                 75
3               1              2                 25
4               1              2                 40

Standard is the class of the student.

My question is I need to calculate the number of students that have failed in more than 1 subject in their class (marks < 50)

So far my failed attempt:

select count(*) from
(select student_id, marks < 50 as fail_value from school
group by 1,2
having count(subject_id) > 1
) as alias
where fail_value = 'true'

For reference, the expected result for the above table should look like this:

count_student_id
      2

Body:
The derived table (the subquery) will return each student_id having more than one marks < 50 class. Count the number of rows returned.

select count(*)
from
(
  select student_id
  from school
  where marks < 50
  group by student_id
  having count(subject_id) > 1
) as dt


问:
How to Render MarkDown inside textarea or inputTextArea using Blazor
How to display markup string inside textarea or inputTextArea in order to use its scroll for larger text

Error message is:Cannot convert markupstring to string

```<code>@if (HTMLContent != null)
{
    <InputTextArea @bind-Value="@((MarkupString) HTMLContent)">

    </InputTextArea>
    <textarea @bind="@( HTMLContent)">
            @((MarkupString) HTMLContent)
    </textarea>

}

@code {
    [Parameter] public string MarkdownContent { get; set; }
    private string HTMLContent;
    protected override void OnParametersSet()
    {
        if (!string.IsNullOrEmpty(MarkdownContent))
        {
            HTMLContent = Markdown.ToHtml(MarkdownContent);
        }
        else
        {
            HTMLContent = null;
        }
    }
}

</code>```

答:
I hope, you are already using MarkDig nuget package for this task. Below code will work. Check it here.

Parent Component

<Counter MarkdownContent="@parentHtmlContent"></Counter>

@code{
    private string parentHtmlContent = $"

Hi, This is Rahul from parent...
" +
    $"" +
    $"" +
    $"
I am currently working for Blazor projects...

";
}
```

<p><strong>Child Component</strong></p>

<pre class="lang-html prettyprint-override"><code><textarea @bind="@ToHtml"></textarea>

@if (HTMLContent != null)
{
    <textarea @bind="@HTMLContent"></textarea>
}

@code {

    string markString2 = $"<h2><p>Hi, This is Rahul...</p></h2>";

    [Parameter] public string MarkdownContent { get; set; }

    private string HTMLContent;

    public string ToHtml
    {
        get
        {
            return Markdig.Markdown.ToHtml(markString2);
        }
        set
        {
            markString2 = value;
        }
    }

    protected override void OnParametersSet()
    {
        if (!string.IsNullOrEmpty(MarkdownContent))
        {
            HTMLContent = Markdig.Markdown.ToHtml(MarkdownContent);
        }
        else
        {
            HTMLContent = null;
        }
    }
}
</code>```

Hope, it will help and it is what you want! Thanks

Body:
How to display markup string inside textarea or inputTextArea in order to use its scroll for larger text

Error message is:Cannot convert markupstring to string

@if (HTMLContent != null)
{
    <InputTextArea @bind-Value="@((MarkupString) HTMLContent)">

    </InputTextArea>
    <textarea @bind="@( HTMLContent)">
            @((MarkupString) HTMLContent)
    </textarea>

}

@code {
    [Parameter] public string MarkdownContent { get; set; }
    private string HTMLContent;
    protected override void OnParametersSet()
    {
        if (!string.IsNullOrEmpty(MarkdownContent))
        {
            HTMLContent = Markdown.ToHtml(MarkdownContent);
        }
        else
        {
            HTMLContent = null;
        }
    }
}

Body:
I hope, you are already using MarkDig nuget package for this task. Below code will work. Check it here.

Parent Component

<Counter MarkdownContent="@parentHtmlContent"></Counter>

@code{
    private string parentHtmlContent = $"<h2><p>Hi, This is Rahul from parent...</p>" +
    $"" +
    $"" +
    $"<p>I am currently working for Blazor projects...</p></h2>";
}

Child Component

<textarea @bind="@ToHtml"></textarea>

@if (HTMLContent != null)
{
    <textarea @bind="@HTMLContent"></textarea>
}

@code {

    string markString2 = $"<h2><p>Hi, This is Rahul...</p></h2>";

    [Parameter] public string MarkdownContent { get; set; }

    private string HTMLContent;

    public string ToHtml
    {
        get
        {
            return Markdig.Markdown.ToHtml(markString2);
        }
        set
        {
            markString2 = value;
        }
    }

    protected override void OnParametersSet()
    {
        if (!string.IsNullOrEmpty(MarkdownContent))
        {
            HTMLContent = Markdig.Markdown.ToHtml(MarkdownContent);
        }
        else
        {
            HTMLContent = null;
        }
    }
}

Hope, it will help and it is what you want! Thanks


问:
User defined script timed out. Timeout is set to 30.0 s
Hi I an integrating my python code for time series forecasting with tableau using tabpy. While executing the code as calculated field it giving this erro: "User defined script timed out. Timeout is set to 30.0 s.". I have increased timeout in default.config already. Please suggest some sulution.</p>

答:
It looks like the value of TABPY_EVALUATE_TIMEOUT is hard coded somewhere in the python code used for tabpy server.

check in the tabpy\tabpy_server\app\app.py file, if you find out any hard coded value there just change the number to your required value or else check in other python files in the folder for the hard coded value and change it.

Incase you didn't find that path check in the log file of the tabpy, you will get to know that path.


问:
Insert NULL into SQL when string is empty
trying to insert NULL when there wasn't selected anything in my combobox but when I do this:

```<code>prikaz.Parameters.AddWithValue("@odjezd", cb_odjezd.Text == string.Empty ?
                                               null : cb_odjezd.Text);
</code>```

I receive following exception:

The parameterized query expects the parameter @ odjezd

May someone help me solve this please?

答:
Try my replied solution from this post
my reply

Actually it is a type confusion problem which should be an compiler
  time problem.  But cause in runtime when nullable string is passed to
  AddWithValue(string, object).

If you want string, cast DBNull.Value to string by microsoft c#
  DBNull library build-in method DBNull.Value.ToString() equivalently
  string.Empty.

If you want a generic type cast the string (object)str.

Body:
trying to insert NULL when there wasn't selected anything in my combobox but when I do this:

prikaz.Parameters.AddWithValue("@odjezd", cb_odjezd.Text == string.Empty ?
                                               null : cb_odjezd.Text);

I receive following exception:

The parameterized query expects the parameter @ odjezd

May someone help me solve this please?


问:
Why does my script not find inactive GameObject when it should?
I have a script that should toggle active on my GameObject but when it disables it, it no longer finds the object.

Script:

```<code>GameObject cheet = GameObject.Find("base");

if (isOpen == true)
{
    cheet.SetActive(true);
}
else
{
    cheet.SetActive(false);
}
</code>```

答:
GameObject.Find only returns active GameObjects, so I would recommend storing a reference to cheet in Start() or Awake(). As long as Cheet exists, this will ensure you have a reference and you only have to do it once.

```<code>using UnityEngine;

public class YourClass : MonoBehaviour
{
    private GameObject cheet;
    private bool isOpen; // Temp isOpen variable

    void Start()
    {
        // Store a reference to the GameObject
        cheet = GameObject.Find("base");
    }

    void Example1()
    {
        // set active based on varable isOpen
        cheet?.SetActive(isOpen);
    }

    void Example2()
    {
        // Could not find cheet (null)
        if(cheet == null)
            return;

        // set active based on varable isOpen
        cheet.SetActive(isOpen);
    }
}
</code>```

Body:
I have a script that should toggle active on my GameObject but when it disables it, it no longer finds the object.

Script:

GameObject cheet = GameObject.Find("base");

if (isOpen == true)
{
    cheet.SetActive(true);
}
else
{
    cheet.SetActive(false);
}

Body:
GameObject.Find only returns active GameObjects, so I would recommend storing a reference to cheet in Start() or Awake(). As long as Cheet exists, this will ensure you have a reference and you only have to do it once.

using UnityEngine;

public class YourClass : MonoBehaviour
{
    private GameObject cheet;
    private bool isOpen; // Temp isOpen variable

    void Start()
    {
        // Store a reference to the GameObject
        cheet = GameObject.Find("base");
    }

    void Example1()
    {
        // set active based on varable isOpen
        cheet?.SetActive(isOpen);
    }

    void Example2()
    {
        // Could not find cheet (null)
        if(cheet == null)
            return;

        // set active based on varable isOpen
        cheet.SetActive(isOpen);
    }
}


问:
How to serialize and deserialize complex nested json Unity?
I have the following json

```<code>{
  "android_play_store_link": "xyz",
  "ios_app_store_link": "",
  "sticker_packs": [
    {
      "identifier": "1",
      "name": "abc",
      "publisher": "Jane Doe",
      "tray_image_file": "xyz.png",
      "image_data_version":"1",
      "avoid_cache":false,
      "publisher_email":"",
      "publisher_website": "",
      "privacy_policy_website": "",
      "license_agreement_website": "",
      "stickers": [
        {
          "image_file": "abc.webp",
          "emojis": ["☕",""]
        },
        {
          "image_file": "cdf.webp",
          "emojis": ["",""]
        },
        {
          "image_file": "efg.webp",
          "emojis": ["☕",""]
        }

      ]
    }
  ]
}
</code>```

I have no acquaintance with json until now, How can i deserialize this ?

I know how to do the basic read and write code from persistent data path of unity. But how do i process this json ?

My main goal is as the player wins a level, a new key and value would be added to the "stickers" attribute, Also after some levels I want to add changes to the sticker packs attribute later.

Plus how will i modify the value of image data version in a specific sticker pack item ?

Thanks in advance

答:
you can use Newtonsoft.Json library to deserialize and serialize. Find below the respective C# class.

```<code>public class Sticker
{
    public string image_file { get; set; }
    public IList<string> emojis { get; set; }
}

public class StickerPack
{
    public string identifier { get; set; }
    public string name { get; set; }
    public string publisher { get; set; }
    public string tray_image_file { get; set; }
    public string image_data_version { get; set; }
    public bool avoid_cache { get; set; }
    public string publisher_email { get; set; }
    public string publisher_website { get; set; }
    public string privacy_policy_website { get; set; }
    public string license_agreement_website { get; set; }
    public IList<Sticker> stickers { get; set; }
}

public class Root
{
    public string android_play_store_link { get; set; }
    public string ios_app_store_link { get; set; }
    public IList<StickerPack> sticker_packs { get; set; }
}
</code>```

Code to Deserialize:

```<code>Root root = JsonConvert.DeserializeObject<Root>(json);
</code>```

Body:
I have the following json

{
  "android_play_store_link": "xyz",
  "ios_app_store_link": "",
  "sticker_packs": [
    {
      "identifier": "1",
      "name": "abc",
      "publisher": "Jane Doe",
      "tray_image_file": "xyz.png",
      "image_data_version":"1",
      "avoid_cache":false,
      "publisher_email":"",
      "publisher_website": "",
      "privacy_policy_website": "",
      "license_agreement_website": "",
      "stickers": [
        {
          "image_file": "abc.webp",
          "emojis": ["☕",""]
        },
        {
          "image_file": "cdf.webp",
          "emojis": ["",""]
        },
        {
          "image_file": "efg.webp",
          "emojis": ["☕",""]
        }

      ]
    }
  ]
}

I have no acquaintance with json until now, How can i deserialize this ?

I know how to do the basic read and write code from persistent data path of unity. But how do i process this json ?

My main goal is as the player wins a level, a new key and value would be added to the "stickers" attribute, Also after some levels I want to add changes to the sticker packs attribute later.

Plus how will i modify the value of image data version in a specific sticker pack item ?

Thanks in advance

Body:
you can use Newtonsoft.Json library to deserialize and serialize. Find below the respective C# class.

public class Sticker
{
    public string image_file { get; set; }
    public IList<string> emojis { get; set; }
}

public class StickerPack
{
    public string identifier { get; set; }
    public string name { get; set; }
    public string publisher { get; set; }
    public string tray_image_file { get; set; }
    public string image_data_version { get; set; }
    public bool avoid_cache { get; set; }
    public string publisher_email { get; set; }
    public string publisher_website { get; set; }
    public string privacy_policy_website { get; set; }
    public string license_agreement_website { get; set; }
    public IList<Sticker> stickers { get; set; }
}

public class Root
{
    public string android_play_store_link { get; set; }
    public string ios_app_store_link { get; set; }
    public IList<StickerPack> sticker_packs { get; set; }
}

Code to Deserialize:

Root root = JsonConvert.DeserializeObject<Root>(json);


问:
Update Core Data when back button clicked of NavigationView in SwiftUI
User can delete some Core Data in NavigationLink. How to save it when back button clicked and return to NavigationView?</p>

答:
You can do it in the onAppear method of the previous View in the NavigationalStack.

struct ContentView: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    var body: some View {
        Text("")
            .onAppear {
                do {
                    try self.managedObjectContext.save()
                } catch {
                    // handle the Core Data error
                }
        }
    }
}
```


问:
gradlew clean deployNodes - QUASAR WARNING: Quasar Java Agent isn't running
When I run "gradlew clean deployNodes" or "gradlew deployNodes", I get a warning on Quasar library:
QUASAR WARNING: Quasar Java Agent isn't running. If you're using another instrumentation method you can ignore this message; otherwise, please refer to the Getting
 Started section in the Quasar documentation.

How can i fix this warning ?

I upgraded Corda to 4.1

答:
you'll want to double-check the intellij settings.

Navigate to Build, Execution, Deployment -> Build Tools -> Gradle ->
  Runner (or search for runner) Windows: this is in "Settings" MacOS:
  this is in "Preferences" Set "Delegate IDE build/run actions to
  gradle" to true Set "Run test using:" to "Gradle Test Runner" If you
  would prefer to use the built in IntelliJ JUnit test runner, you can
  run gradlew installQuasar which will copy your quasar JAR file to the
  lib directory. You will then need to specify -javaagent:lib/quasar.jar
  and set the run directory to the project root directory for each test.

As mentioned in the comments from manish, make sure to try cleaning the gradle cache as well: ./gradlew clean build deployNodes.

Joel has a good answer for a similar quasar issue on this StackOverflow question: Error when running Corda flow tests from IntelliJ


问:
How to append jquery div to html correctly
I've got the input and button in div:

```<code><div>
  <input id='input_id_0' value='name'>
  <button type="button" id="remove_id_0"></button>
</div>
</code>```

I'd like to copy the input and the button, increase their id, wrap them in the div and attach after the previous one. So the result should be:

```<code><div>
  <input id='input_id_0' value='name'>
  <button type="button" id="remove_id_0"></button>
</div>
<div>
  <input id='input_id_1' value='name'>
  <button type="button" id="remove_id_1"></button>
</div>
</code>```

I wrote the code:

```<code>    cloneCount = 0;
    cloneCount += 1;
    var div = document.createElement('div');
    var previousInput = document.getElementById('input_id_' + (cloneCount-1))
    var newInput = $(previousInput)
         .clone(true)
         .attr('id', 'input_id_' + cloneCount)
    previousInput.append(newInput)

    var previousRemoveBtn = document.getElementById('remove_id_' + (cloneCount-1))
    var newRemoveBtn = $(previousRemoveBtn)
         .clone(true)
         .attr('id', 'remove_id_' + cloneCount)

   div.append(newInput)
   div.append(newRemoveBtn)

   $(previousInput).parent().after(div)
</code>```

but that code results in text object[Object] object[Object] being appended to my original input. JSFiddle:
https://jsfiddle.net/Malvinka87/z8t1sxcf/1/

Could you explain to me, please, why that is happening and how to fix it?

答:
Since you're using jquery, you don't need to use document.getElementById or document.createElement like that. All of them can be done using jquery:

var input = $('input').clone();
var input_id = input.prop('id');

input_id = input_id.substr(input_id.length - 1, 1);

var button = $('button').clone();
var button_id = button.prop('id');

button_id = button_id.substr(button_id.length - 1, 1);

input.prop('id', 'input_id_' + ++input_id);
button.prop('id', 'remove_id_' + ++button_id);

var div = $('
').append(input).append(button);

div.insertAfter('div');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input id='input_id_0' value='name'>
  <button type="button" id="remove_id_0">btn</button>
</div></code>```

About the id, you can try to get the lastest character from the id string, then increasing it as a number before appending to the new element.

Body:
I've got the input and button in div:

  <input id='input_id_0' value='name'>
  <button type="button" id="remove_id_0"></button>

I'd like to copy the input and the button, increase their id, wrap them in the div and attach after the previous one. So the result should be:

  <input id='input_id_0' value='name'>
  <button type="button" id="remove_id_0"></button>

  <input id='input_id_1' value='name'>
  <button type="button" id="remove_id_1"></button>

I wrote the code:

    cloneCount = 0;
    cloneCount += 1;
    var div = document.createElement('div');
    var previousInput = document.getElementById('input_id_' + (cloneCount-1))
    var newInput = $(previousInput)
         .clone(true)
         .attr('id', 'input_id_' + cloneCount)
    previousInput.append(newInput)

    var previousRemoveBtn = document.getElementById('remove_id_' + (cloneCount-1))
    var newRemoveBtn = $(previousRemoveBtn)
         .clone(true)
         .attr('id', 'remove_id_' + cloneCount)

   div.append(newInput)
   div.append(newRemoveBtn)

   $(previousInput).parent().after(div)

but that code results in text object[Object] object[Object] being appended to my original input. JSFiddle:
https://jsfiddle.net/Malvinka87/z8t1sxcf/1/

Could you explain to me, please, why that is happening and how to fix it?

Body:
Since you're using jquery, you don't need to use document.getElementById or document.createElement like that. All of them can be done using jquery:

var input = $('input').clone();
var input_id = input.prop('id');

input_id = input_id.substr(input_id.length - 1, 1);

var button = $('button').clone();
var button_id = button.prop('id');

button_id = button_id.substr(button_id.length - 1, 1);

input.prop('id', 'input_id_' + ++input_id);
button.prop('id', 'remove_id_' + ++button_id);

var div = $('<div>').append(input).append(button);

div.insertAfter('div');

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input id='input_id_0' value='name'>
  <button type="button" id="remove_id_0">btn</button>
</div>

About the id, you can try to get the lastest character from the id string, then increasing it as a number before appending to the new element.


问:
Bottom icons destroyed after use PDFViewerScaffold
I have Implemented a screen with app bar and two icons like following picture

After I add the PDFViewerScaffold then all the icons and app bar not display only the pdf file displays

This my code

```<code>return Scaffold(
  appBar: AppBar(
    title: Text('Preview'),
    backgroundColor: Colors.lightBlue,
  ),
  body: Stack(
    children: <Widget>[
      Positioned(
        bottom: 10,
        left: 50,
        child: IconButton(
          icon: Icon(Icons.description),
          iconSize: 30,
          color: Colors.blue,
          onPressed: () {}),
      ),
      Positioned(
        bottom: 10,
        right: 50,
        child: IconButton(
          icon: Icon(Icons.share),
          iconSize: 30,
          color: Colors.blue,
          onPressed: () {}),
      ),
      Positioned(
        child: PDFViewerScaffold(path:widget.pdfPath))
    ],
  ),
);
</code>```

How can I display all the icons, appbar and pdf document in one screen ?

答:
You are using this plugin, which uses PDFViewerScaffold to view the pdf.

When we go inside this class we find that it calls a method to view the pdf in fullscreen and add its own AppBar. You can't change that behavior, the only solution is to use another plugin.

This is another plugin that can view pdf file inside your scaffold.

Body:
I have Implemented a screen with app bar and two icons like following picture

After I add the PDFViewerScaffold then all the icons and app bar not display only the pdf file displays

This my code

return Scaffold(
  appBar: AppBar(
    title: Text('Preview'),
    backgroundColor: Colors.lightBlue,
  ),
  body: Stack(
    children: <Widget>[
      Positioned(
        bottom: 10,
        left: 50,
        child: IconButton(
          icon: Icon(Icons.description),
          iconSize: 30,
          color: Colors.blue,
          onPressed: () {}),
      ),
      Positioned(
        bottom: 10,
        right: 50,
        child: IconButton(
          icon: Icon(Icons.share),
          iconSize: 30,
          color: Colors.blue,
          onPressed: () {}),
      ),
      Positioned(
        child: PDFViewerScaffold(path:widget.pdfPath))
    ],
  ),
);

How can I display all the icons, appbar and pdf document in one screen ?


问:
WPF Commands in Control templates -> "CommandConverter cannot convert from > System.String."
I have a custom control template from Telerik and Ive added a (split)button to it.
How to I bind a command handler to it? I have tried to add a public static command in a public class
to use bindings like x:static ns:Class.Command and all sorts of variation (like below) and most of the SO-hits.

```<code><Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:RadSplitButton}}, Path=ShowSearchCommand}" Margin="2" />
</code>```

and

```<code><Button Content="Click me" Command="{x:Static vm:MainWindowViewModel.ShowSearchCommand}" CommandParameter="one"/>
</code>```

They all ends up in the error message

NotSupportedException: CommandConverter cannot convert from
  System.String.

Ive tried defining the commands (see below) in the viewmodel and in a class pf its own (Im using Prism (therefore the Delegate commands, but its doesnt have to be Delegate commands, as long as it works)

```<code>  //public static RoutedUICommand ShowSearchCommand = new RoutedUICommand("ShowSearchCommand", "ShowSearchCommand", typeof(TabbedWindowCommands));

//public static DelegateCommand ShowSearchCommand = new DelegateCommand();
</code>```

答:
Since ShowSearchCommand is not a property of the RadSplitButton itself but of its DataContext, you should include DataContext in the binding path:

```<code><Button Command="{Binding RelativeSource={RelativeSource FindAncestor,
    AncestorType={x:Type telerik:RadSplitButton}}, Path=DataContext.ShowSearchCommand}" Margin="2" />
</code>```

You might also want to change the AncestorType to Window depending on where and how you set the DataContext.

Also note that you can only bind to public properties which means that ShowSearchCommand must be a property and not a field:

```<code>public DelegateCommand ShowSearchCommand { get; }
</code>```

Body:
I have a custom control template from Telerik and Ive added a (split)button to it.
How to I bind a command handler to it? I have tried to add a public static command in a public class
to use bindings like x:static ns:Class.Command and all sorts of variation (like below) and most of the SO-hits.

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:RadSplitButton}}, Path=ShowSearchCommand}" Margin="2" />

and

<Button Content="Click me" Command="{x:Static vm:MainWindowViewModel.ShowSearchCommand}" CommandParameter="one"/>

They all ends up in the error message

NotSupportedException: CommandConverter cannot convert from
  System.String.

Ive tried defining the commands (see below) in the viewmodel and in a class pf its own (Im using Prism (therefore the Delegate commands, but its doesnt have to be Delegate commands, as long as it works)

  //public static RoutedUICommand ShowSearchCommand = new RoutedUICommand("ShowSearchCommand", "ShowSearchCommand", typeof(TabbedWindowCommands));

//public static DelegateCommand ShowSearchCommand = new DelegateCommand();

Body:
Since ShowSearchCommand is not a property of the RadSplitButton itself but of its DataContext, you should include DataContext in the binding path:

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor,
    AncestorType={x:Type telerik:RadSplitButton}}, Path=DataContext.ShowSearchCommand}" Margin="2" />

You might also want to change the AncestorType to Window depending on where and how you set the DataContext.

Also note that you can only bind to public properties which means that ShowSearchCommand must be a property and not a field:

public DelegateCommand ShowSearchCommand { get; }


问:
Opencv MPEG7 descriptors
I am working on the system that compares images. MPEG-7 standard provides some descriptors which can be used for that e.g: Dominant Color, Color Layout, Edge Histogramm, Color Coherence Vectors.
Do you know where i can get a source code for some of these methods?

Thx!

答:
For Future readers, there's a CPP library that claims to be easy to use here.
https://github.com/mubastan/mpeg7fex

This has been tested on OpenCV 3, so this is at par the latest.

ContentLicense: CC BY-SA 2.5

Title: Opencv MPEG7 descriptors


问:
Azure Cosmos DB Custom Conflict Resolution -- conflictingItems
I'm working on a stored procedure for custom conflict resolution. One of the parameter -- conflictingItems is confusing me.

The documentation given here says,

conflictingItems: Array of the committed version of all items in the container that are conflicting with incomingItem on ID or any other unique index properties.

If I upsert an entity with a different ID, shouldn't it just create a new entity?
Can someone provide a scenario where this conflictingItems will be used?

答: Conflict resolution is used for Cosmos account with multi-master is enabled to handle scenarios where items with the same id or that violate unique indexes occur in multiple regions simultaneously. If you are not configured for multi-master then you do not need to do conflict resolution.</p>


问:
Using Blazor server side
Please I have an ASP.NET Core Web API project that I need to develop a front-end UI to consume it, taking advantage of the Single Page Application (SPA) and component model of Blazor, I am thinking of using Blazor Server app, but my application is going to be an enterprise app with at least 20,000 concurrent users or more in the future and my concern is obviously the SignalR connection.

Can Blazor server side handle it?
Thank you for your kind response.

答:
I would look into Blazor WebAssembly instead.

https://learn.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-3.1#blazor-webassembly

If you would still like to continue with Blazor Server you can read more below.

https://learn.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-3.1#blazor-server

Each circuit uses approximately 250 KB of memory for a minimal Hello
  World-style app. The size of a circuit depends on the app's code and
  the state maintenance requirements associated with each component. We
  recommend that you measure resource demands during development for
  your app and infrastructure, but the following baseline can be a
  starting point in planning your deployment target: If you expect your
  app to support 5,000 concurrent users, consider budgeting at least 1.3
  GB of server memory to the app (or ~273 KB per user).

https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/blazor/server?view=aspnetcore-3.1

Here is a good comparison and also a test done on a Standard D3 v2 instance on Azure (4vCPU & 14GB memory) with over 20,000 concurrent active users

Note specifically:

The major findings which came out of these experiments were that
  memory and latency are the main bottlenecks of Blazor Server
  applications. If latency got above 200ms then performance took a hit
  and scale was limited by the available memory on the box.

https://stackoverflow.blog/2020/02/26/whats-behind-the-hype-about-blazor/

Title: Using Blazor server side


问:
Unicode in vb.net
How to use Unicode available in vb6 in vb.net?

Is there any equivalent of vb6 Unicode in vb.net??

答: All strings in .NET (and hence in VB.NET) are unicode. .NET also has libraries to output strings in different formats (see the System.Text.Encoding class and related classes). What exactly are you trying to do with unicode?</p>

OwnerDisplayName: renu

LastEditorDisplayName: JaredPar

Title: Unicode in vb.net

OwnerDisplayName: Chris Hynes


问:
Interval Arithmetic Library: boost::numeric::interval in C++
I searched Stack Exchange and the web in general, including the boost instructions page but i still have some problems so i hope someone with more knowledge can help me out.

I need to compute unions and intersections of closed, open and half open intervals ideally of type double or float. In my search i found the boost library mentioned in the title.

Their hull function is not a true union (they state that on the instruction page), but there also is no clear replacement for it and the hull is just not enough as a union replacement. This combined with it only being able to work with closed intervals makes it a rather sub-par choice but i couldnt find anything else. (If you know of any library that can do what i need, please tell me :)

In terms of this library i have encountered a few problems that i cant seem to solve on my own or find any explanation online for.

By default it throws an exception and aborts if a function returns an empty interval, for example using their intersection function for two intervals with no intersection (as shown in the code below), there seems to be a way to configure the policy class to return a replacement value and basically work normally with NaN and empty intervals but i couldnt make this work so far, due to my limited knowledge with external libraries like this.

Below i listed some simple code example im currently stuck at, because i cant figure out how to use or change the policy class to work with empty intervals.

I read the instruction, checker and policy page up and down but my knowledge doesnt seem to be enough to make this work. So i appreciate any help you can provide.

```<code>typedef boost::numeric::interval<double> I;
double inf = numeric_limits<double>::infinity();

I a(2,5);
cout << "a[" << boost::numeric::lower(a) << ", " << boost::numeric::upper(a) << "]\n";
I b(3,9);
cout << "b[" << boost::numeric::lower(b) << ", " << boost::numeric::upper(b) << "]\n";
I c(6,7);
cout << "b[" << boost::numeric::lower(c) << ", " << boost::numeric::upper(c) << "]\n";

cout << "Union a | b: " << "[" << boost::numeric::lower(boost::numeric::intersect(a, b)) << ", " << boost::numeric::upper(boost::numeric::intersect(a, b)) << "]\n";
// correctly lists [3,6] as intersection
cout << "Union a | c: " << "[" << boost::numeric::lower(boost::numeric::intersect(a, c)) << ", " << boost::numeric::upper(boost::numeric::intersect(a, c)) << "]\n";
// throws error due to empty interval being returned and not having lower or upper
</code>```

答:
Sounds like you might be after a library that is not geared to numeric computation. Boost has ICL (Interval container Library) as well.

It has interval sets/maps, which work with discrete or continuous, bounded or unbounded intervals.

It has various combining behaviours (joining adjacent intervals, splitting intervals on boundaries, etc. including custom combiners).

It has various collection/aggregating strategies for co-domains when mapping (e.g. quantifiers when the mapped values are numeric, or collectors when the map values are sets).

Here's a simple starter. (Note I did not replicate your exact input to show the various open/closed and default interval types).

Note also that output serialization seems to be a breeze in comparison.

This is only just grazing the surface so

per-use the documentation

see various examples to be found on this site

Live On Coliru

```<code>#include <boost/icl/interval.hpp>
#include <boost/icl/interval_set.hpp>
#include <iostream>
namespace icl = boost::icl;

using S = icl::interval_set<double>;
using I = S::interval_type;
constexpr inline auto inf = std::numeric_limits<I::domain_type>::infinity();

int main() {
    I const
        a = I::closed(2,5),
        b(3,9),
        c = I::left_open(6,7);

#define INSPECT(expr) std::cout << #expr << ": " << (expr) << "\n";
    INSPECT(a);
    INSPECT(b);
    INSPECT(c);

    INSPECT(hull(a,b));
    INSPECT(S{a} | b);
    INSPECT(S{a} & b);
    INSPECT(S{a} & c);

    INSPECT(S{a} | b | c);
    // potentially more efficient:
    INSPECT([=] { S s; for (auto i:{a,b,c}) s.insert(i); return s;}());

    INSPECT(S{a} - (S{b} | c));
    INSPECT(S{a} & (S{b} | c));
}
</code>```

Prints

```<code>a: [2,5]
b: [3,9)
c: (6,7]
hull(a,b): [2,9)
S{a} | b: {[2,9)}
S{a} & b: {[3,5]}
S{a} & c: {}
S{a} | b | c: {[2,9)}
[=] { S s; for (auto i:{a,b,c}) s.insert(i); return s;}(): {[2,9)}
S{a} - (S{b} | c): {[2,3)}
S{a} & (S{b} | c): {[3,5]}
</code>```

Body:
I searched Stack Exchange and the web in general, including the boost instructions page but i still have some problems so i hope someone with more knowledge can help me out.

I need to compute unions and intersections of closed, open and half open intervals ideally of type double or float. In my search i found the boost library mentioned in the title.

Their hull function is not a true union (they state that on the instruction page), but there also is no clear replacement for it and the hull is just not enough as a union replacement. This combined with it only being able to work with closed intervals makes it a rather sub-par choice but i couldnt find anything else. (If you know of any library that can do what i need, please tell me :)

In terms of this library i have encountered a few problems that i cant seem to solve on my own or find any explanation online for.

By default it throws an exception and aborts if a function returns an empty interval, for example using their intersection function for two intervals with no intersection (as shown in the code below), there seems to be a way to configure the policy class to return a replacement value and basically work normally with NaN and empty intervals but i couldnt make this work so far, due to my limited knowledge with external libraries like this.

Below i listed some simple code example im currently stuck at, because i cant figure out how to use or change the policy class to work with empty intervals.

I read the instruction, checker and policy page up and down but my knowledge doesnt seem to be enough to make this work. So i appreciate any help you can provide.

typedef boost::numeric::interval<double> I;
double inf = numeric_limits<double>::infinity();

I a(2,5);
cout << "a[" << boost::numeric::lower(a) << ", " << boost::numeric::upper(a) << "]\n";
I b(3,9);
cout << "b[" << boost::numeric::lower(b) << ", " << boost::numeric::upper(b) << "]\n";
I c(6,7);
cout << "b[" << boost::numeric::lower(c) << ", " << boost::numeric::upper(c) << "]\n";

cout << "Union a | b: " << "[" << boost::numeric::lower(boost::numeric::intersect(a, b)) << ", " << boost::numeric::upper(boost::numeric::intersect(a, b)) << "]\n";
// correctly lists [3,6] as intersection
cout << "Union a | c: " << "[" << boost::numeric::lower(boost::numeric::intersect(a, c)) << ", " << boost::numeric::upper(boost::numeric::intersect(a, c)) << "]\n";
// throws error due to empty interval being returned and not having lower or upper

Body:
Sounds like you might be after a library that is not geared to numeric computation. Boost has ICL (Interval container Library) as well.

It has interval sets/maps, which work with discrete or continuous, bounded or unbounded intervals.

It has various combining behaviours (joining adjacent intervals, splitting intervals on boundaries, etc. including custom combiners).

It has various collection/aggregating strategies for co-domains when mapping (e.g. quantifiers when the mapped values are numeric, or collectors when the map values are sets).

Here's a simple starter. (Note I did not replicate your exact input to show the various open/closed and default interval types).

Note also that output serialization seems to be a breeze in comparison.

This is only just grazing the surface so

per-use the documentation

see various examples to be found on this site

Live On Coliru

#include <boost/icl/interval.hpp>
#include <boost/icl/interval_set.hpp>
#include <iostream>
namespace icl = boost::icl;

using S = icl::interval_set<double>;
using I = S::interval_type;
constexpr inline auto inf = std::numeric_limits<I::domain_type>::infinity();

int main() {
    I const
        a = I::closed(2,5),
        b(3,9),
        c = I::left_open(6,7);

#define INSPECT(expr) std::cout << #expr << ": " << (expr) << "\n";
    INSPECT(a);
    INSPECT(b);
    INSPECT(c);

    INSPECT(hull(a,b));
    INSPECT(S{a} | b);
    INSPECT(S{a} & b);
    INSPECT(S{a} & c);

    INSPECT(S{a} | b | c);
    // potentially more efficient:
    INSPECT([=] { S s; for (auto i:{a,b,c}) s.insert(i); return s;}());

    INSPECT(S{a} - (S{b} | c));
    INSPECT(S{a} & (S{b} | c));
}

Prints

a: [2,5]
b: [3,9)
c: (6,7]
hull(a,b): [2,9)
S{a} | b: {[2,9)}
S{a} & b: {[3,5]}
S{a} & c: {}
S{a} | b | c: {[2,9)}
[=] { S s; for (auto i:{a,b,c}) s.insert(i); return s;}(): {[2,9)}
S{a} - (S{b} | c): {[2,3)}
S{a} & (S{b} | c): {[3,5]}


问:
How does negative margin works?
From this article(https://www.quirksmode.org/blog/archives/2020/02/negative_margin.html) I know that negative margin-right influences any element to the right of the element where it's written but not an element itself.

In the book, "Meloni J. - PHP, MySQL & JavaScript All in One (6th Edition) (Sams Teach Yourself) - 2018" there is an example where I don't see any element to the right. But it still works and it pulls the element somehow. Can somebody explain me how does it work? Why it influences the element where it's written?

body {
  margin: 0;
  padding: 0;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  right: 200px;
  margin-left: -100%;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  margin-right: -125px; /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="content_area">CONTENT</div>
  <div id="left_side">LEFT SIDE</div>
  <div id="right_side">RIGHT SIDE</div>
</div></code>```

答:
Remove some of the properties to better understand what is happening initially

body {
  margin: 0;
  padding: 0;
  width:800px;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
  border:1px solid red;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  /*right: 200px;
  margin-left: -100%;*/
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  /*margin-right: -125px;*/ /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  /*width: 100%;*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="content_area">CONTENT</div>
  <div id="left_side">LEFT SIDE</div>
  <div id="right_side">RIGHT SIDE</div>
</div></code>```

We have 3 float elements side by side. One with auto width and two with explicit width. The total width will define the width of the wrapper W.

Now if we add width:100% to #content_area it will take 100% of W push the other to the next row:

body {
  margin: 0;
  padding: 0;
  width:800px;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
  border:1px solid red;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  /*right: 200px;
  margin-left: -100%;*/
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  /*margin-right: -125px;*/ /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="content_area">CONTENT</div>
  <div id="left_side">LEFT SIDE</div>
  <div id="right_side">RIGHT SIDE</div>
</div></code>```

Now if you add margin-left:-100% to the left element it means shift this element by -W thus it will overlap the #content_area element

body {
  margin: 0;
  padding: 0;
  width:800px;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
  border:1px solid red;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  /*right: 200px;*/
  margin-left: -100%;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  /*margin-right: -125px;*/ /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="content_area">CONTENT</div>
  <div id="left_side">LEFT SIDE</div>
  <div id="right_side">RIGHT SIDE</div>
</div></code>```

Then we shift it using right equal to its width to remove the overlap and make it on the top of the right padding:

body {
  margin: 0;
  padding: 0;
  width:800px;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
  border:1px solid red;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  right: 200px;
  margin-left: -100%;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  /*margin-right: -125px;*/ /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="content_area">CONTENT</div>
  <div id="left_side">LEFT SIDE</div>
  <div id="right_side">RIGHT SIDE</div>
</div></code>```

For the right element it's almost the same trick but the negative margin-right which is equal to the width will negate the width effect making the element taking 0 space on the layout so it will move back to the first row and will overlap the padding area on the right.

Here is an illustration of the right element alone to better understand:

body {
  margin: 0;
  padding: 0;
}

#wrapper {
  float: left;
  border:2px solid green;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  margin-right: -125px;
  animation:change 5s linear infinite alternate;
 }
@keyframes change{
  from {
    margin-right:0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="right_side">RIGHT SIDE</div>
</div></code>```

Notice how the width of wrapper become 0 when width+margin of the right element is 0

And if we add another element inside you will see the jump to the first row:

body {
  margin: 0;
  padding: 0;
}

#wrapper {
  float: left;
  border:2px solid green;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  margin-right: -125px;
  animation:change 5s linear infinite alternate;
 }
@keyframes change{
  0% {
    margin-right:0;
  }
  90% {
    margin-right:-125px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div style="float:left;width:100%">aaa</div>
  <div id="right_side">RIGHT SIDE</div>
</div></code>```

And if you add padding-right we make the right element overlap that padding when it jumps to the first row

body {
  margin: 0;
  padding: 0;
}

#wrapper {
  float: left;
  border:2px solid green;
  padding-right:125px;
  background:linear-gradient(yellow,yellow) right/125px no-repeat; /* to illustrate the padding */
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  margin-right: -125px;
  animation:change 5s linear infinite alternate;
 }
@keyframes change{
  0% {
    margin-right:0;
  }
  90% {
    margin-right:-125px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div style="float:left;width:100%">aaa</div>
  <div id="right_side">RIGHT SIDE</div>
</div></code>```

Title: How does negative margin works?

Body:
From this article(https://www.quirksmode.org/blog/archives/2020/02/negative_margin.html) I know that negative margin-right influences any element to the right of the element where it's written but not an element itself.

In the book, "Meloni J. - PHP, MySQL & JavaScript All in One (6th Edition) (Sams Teach Yourself) - 2018" there is an example where I don't see any element to the right. But it still works and it pulls the element somehow. Can somebody explain me how does it work? Why it influences the element where it's written?

body {
  margin: 0;
  padding: 0;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  right: 200px;
  margin-left: -100%;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  margin-right: -125px; /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  width: 100%;
}

CONTENT

LEFT SIDE

RIGHT SIDE

Body:
Remove some of the properties to better understand what is happening initially

body {
  margin: 0;
  padding: 0;
  width:800px;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
  border:1px solid red;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  /*right: 200px;
  margin-left: -100%;*/
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  /*margin-right: -125px;*/ /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  /*width: 100%;*/
}

<div id="wrapper">
  <div id="content_area">CONTENT</div>
  <div id="left_side">LEFT SIDE</div>
  <div id="right_side">RIGHT SIDE</div>
</div>

We have 3 float elements side by side. One with auto width and two with explicit width. The total width will define the width of the wrapper W.

Now if we add width:100% to #content_area it will take 100% of W push the other to the next row:

body {
  margin: 0;
  padding: 0;
  width:800px;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
  border:1px solid red;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  /*right: 200px;
  margin-left: -100%;*/
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  /*margin-right: -125px;*/ /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  width: 100%;
}

<div id="wrapper">
  <div id="content_area">CONTENT</div>
  <div id="left_side">LEFT SIDE</div>
  <div id="right_side">RIGHT SIDE</div>
</div>

Now if you add margin-left:-100% to the left element it means shift this element by -W thus it will overlap the #content_area element

body {
  margin: 0;
  padding: 0;
  width:800px;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
  border:1px solid red;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  /*right: 200px;*/
  margin-left: -100%;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  /*margin-right: -125px;*/ /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  width: 100%;
}

<div id="wrapper">
  <div id="content_area">CONTENT</div>
  <div id="left_side">LEFT SIDE</div>
  <div id="right_side">RIGHT SIDE</div>
</div>

Then we shift it using right equal to its width to remove the overlap and make it on the top of the right padding:

body {
  margin: 0;
  padding: 0;
  width:800px;
}

#wrapper {
  float: left;
  padding-left: 200px;
  padding-right: 125px;
  border:1px solid red;
}

#left_side {
  position: relative;
  float: left;
  width: 200px;
  background-color: #52f471;
  right: 200px;
  margin-left: -100%;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  /*margin-right: -125px;*/ /*  THIS MARGIN-RIGHT */
}

#content_area {
  position: relative;
  float: left;
  background-color: #FFFFFF;
  width: 100%;
}

<div id="wrapper">
  <div id="content_area">CONTENT</div>
  <div id="left_side">LEFT SIDE</div>
  <div id="right_side">RIGHT SIDE</div>
</div>

For the right element it's almost the same trick but the negative margin-right which is equal to the width will negate the width effect making the element taking 0 space on the layout so it will move back to the first row and will overlap the padding area on the right.

Here is an illustration of the right element alone to better understand:

body {
  margin: 0;
  padding: 0;
}

#wrapper {
  float: left;
  border:2px solid green;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  margin-right: -125px;
  animation:change 5s linear infinite alternate;
 }
@keyframes change{
  from {
    margin-right:0;
  }
}

<div id="wrapper">
  <div id="right_side">RIGHT SIDE</div>
</div>

Notice how the width of wrapper become 0 when width+margin of the right element is 0

And if we add another element inside you will see the jump to the first row:

body {
  margin: 0;
  padding: 0;
}

#wrapper {
  float: left;
  border:2px solid green;
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  margin-right: -125px;
  animation:change 5s linear infinite alternate;
 }
@keyframes change{
  0% {
    margin-right:0;
  }
  90% {
    margin-right:-125px;
  }
}

<div id="wrapper">
  <div style="float:left;width:100%">aaa</div>
  <div id="right_side">RIGHT SIDE</div>
</div>

And if you add padding-right we make the right element overlap that padding when it jumps to the first row

body {
  margin: 0;
  padding: 0;
}

#wrapper {
  float: left;
  border:2px solid green;
  padding-right:125px;
  background:linear-gradient(yellow,yellow) right/125px no-repeat; /* to illustrate the padding */
}

#right_side {
  position: relative;
  float: left;
  width: 125px;
  background-color: #f452d5;
  margin-right: -125px;
  animation:change 5s linear infinite alternate;
 }
@keyframes change{
  0% {
    margin-right:0;
  }
  90% {
    margin-right:-125px;
  }
}

<div id="wrapper">
  <div style="float:left;width:100%">aaa</div>
  <div id="right_side">RIGHT SIDE</div>
</div>


问:
504 gateway time-out server didn't respond in time issue
I've looked throughout this site to see if I could find a solution but haven't found one.

I have a problem with a 504 gateway time-out server message that keeps popping up.
I was able to successfully setup my MySQL database to capture data from my webpage, with dbconnect.php, using my localhost/index.html.  However, when I try to access it via my Virtualbox(running windows 7/10) I keep getting a 504 gateway time-out server didn't respond in time, message.  I changed my $host name from localhost to supporthtech.hopto.org(I'm using NOIP).  I also increased my max_input_time and max_execution_time from 120 to 3000.  That doesn't seem to help.  On my VM, I'm using a proxy server to mimic someone from outside my network trying to login to my website.

Like I've said at the beginning.  MySQL database is able to successfully collect information when I setup my website locally(using localhost/index.html).
Any ideas would be greatly appreciated.  Thanks!

答:
I would expect you to run the web server from the same host as your database is running on, so you should continue to connect from the web page to "localhost" - regardless of how your browser is connecting to the web page, the connection between the database and the web server continues to be local. So regardless of where in the world or which virtual machine you're using, your browser should connect to the web server which you're running on the same host as the database server. There's no need to change the host string for your PHP script for the database connection if you're accessing from another host, since to the web server the database host hasn't changed. This is one of the great things about networking, if you connect to the web server it doesn't matter what is going on behind the scenes on the network because, to the web browser, all it has to do is talk to the web server; the details under the web server can be as complex or simple as your topology requires.

That seems to be the most likely cause of your trouble, so I suggest changing the connection host back to localhost and accessing your web server itself remotely. If that causes you trouble, then there's something else wrong with your web server configuration (or ISP, or port forwarding on your router, etc) that you can ask another question about.


问:
Codility NailingPlanks
Tried to understand the solution for Codility NailingPlanks.

Link for the Problem:
https://app.codility.com/programmers/lessons/14-binary_search_algorithm/nailing_planks/

You are given two non-empty arrays A and B consisting of N integers.
  These arrays represent N planks. More precisely, A[K] is the start and
  B[K] the end of the K−th plank.

Next, you are given a non-empty array C consisting of M integers. This
  array represents M nails. More precisely, C[I] is the position where
  you can hammer in the I−th nail.

We say that a plank (A[K], B[K]) is nailed if there exists a nail C[I]
  such that A[K] ≤ C[I] ≤ B[K].

The goal is to find the minimum number of nails that must be used
  until all the planks are nailed. In other words, you should find a
  value J such that all planks will be nailed after using only the first
  J nails. More precisely, for every plank (A[K], B[K]) such that 0 ≤ K
  < N, there should exist a nail C[I] such that I < J and A[K] ≤ C[I] ≤
  B[K].

Link for the solution:
https://github.com/ZRonchy/Codility/blob/master/Lesson12/NailingPlanks.java

```<code>import java.util.Arrays;

class Solution {
    public int solution(int[] A, int[] B, int[] C) {
        // the main algorithm is that getting the minimal index of nails which
        // is needed to nail every plank by using the binary search
        int N = A.length;
        int M = C.length;
        // two dimension array to save the original index of array C
        int[][] sortedNail = new int[M][2];
        for (int i = 0; i < M; i++) {
            sortedNail[i][0] = C[i];
            sortedNail[i][1] = i;
        }
        // use the lambda expression to sort two dimension array
        Arrays.sort(sortedNail, (int x[], int y[]) -> x[0] - y[0]);
        int result = 0;
        for (int i = 0; i < N; i++) {//find the earlist position that can nail each plank, and the max value for all planks is the result
            result = getMinIndex(A[i], B[i], sortedNail, result);
            if (result == -1)
                return -1;
        }
        return result + 1;
    }
    // for each plank , we can use binary search to get the minimal index of the
    // sorted array of nails, and we should check the candidate nails to get the
    // minimal index of the original array of nails.
    public int getMinIndex(int startPlank, int endPlank, int[][] nail, int preIndex) {
        int min = 0;
        int max = nail.length - 1;
        int minIndex = -1;
        while (min <= max) {
            int mid = (min + max) / 2;
            if (nail[mid][0] < startPlank)
                min = mid + 1;
            else if (nail[mid][0] > endPlank)
                max = mid - 1;
            else {
                max = mid - 1;
                minIndex = mid;
            }
        }
        if (minIndex == -1)
            return -1;
        int minIndexOrigin = nail[minIndex][1];
        //find the smallest original position of nail that can nail the plank
        for (int i = minIndex; i < nail.length; i++) {
            if (nail[i][0] > endPlank)
                break;
            minIndexOrigin = Math.min(minIndexOrigin, nail[i][1]);
            // we need the maximal index of nails to nail every plank, so the
            // smaller index can be omitted    ****
            if (minIndexOrigin <= preIndex) // ****
                return preIndex;            // ****
        }
        return minIndexOrigin;
    }
}
</code>```

I don't understand Line 99-102, marked with ****, of the solution.

My question is:

If minIndexOrigin <= preIndex , then it will use preIndex,
but how if the preIndex doesn't nail the current plank ?

Is there a bit mistake with the solution ?

答:
The case that is handled in those lines is when you find that there is an index that nails the current plank, which index is less (or equal) to the lowest index we need to be able to nail another (previously analysed) plank. In that case, we don't need to look further for the current plank, since we know that:

we can nail the plank

we can use an index that is not greater than an index we really need to use for another plank.

Since we are only interested in the greatest index among the least indexes we need for the different planks (i.e. the index for the "worst" plank), we know that the index we just found now is not important any more: if we already know that we will be using all the nails up to at least preIndex, we know that one nail among that set will nail the current plank. We can just exit the loop and return a "dummy" index that will not influence the result.

Note what the effect is in the calling loop:

```<code>result = getMinIndex(A[i], B[i], sortedNail, result);
</code>```

After this assignment, result will be equal to what result was before the call: this plank (A[i], B[i]) can be nailed with an earlier nail, but we don't really care which nail that is, as we need to know the worst case, which is up to now reflected by result, and all nails up to that index are already in the set of nails that will be hammered.

You can compare it with alpha-beta pruning.

Title: Codility NailingPlanks

Body:
Tried to understand the solution for Codility NailingPlanks.

Link for the Problem:
https://app.codility.com/programmers/lessons/14-binary_search_algorithm/nailing_planks/

You are given two non-empty arrays A and B consisting of N integers.
  These arrays represent N planks. More precisely, A[K] is the start and
  B[K] the end of the K−th plank.

Next, you are given a non-empty array C consisting of M integers. This
  array represents M nails. More precisely, C[I] is the position where
  you can hammer in the I−th nail.

We say that a plank (A[K], B[K]) is nailed if there exists a nail C[I]
  such that A[K] ≤ C[I] ≤ B[K].

The goal is to find the minimum number of nails that must be used
  until all the planks are nailed. In other words, you should find a
  value J such that all planks will be nailed after using only the first
  J nails. More precisely, for every plank (A[K], B[K]) such that 0 ≤ K
  < N, there should exist a nail C[I] such that I < J and A[K] ≤ C[I] ≤
  B[K].

Link for the solution:
https://github.com/ZRonchy/Codility/blob/master/Lesson12/NailingPlanks.java

import java.util.Arrays;

class Solution {
    public int solution(int[] A, int[] B, int[] C) {
        // the main algorithm is that getting the minimal index of nails which
        // is needed to nail every plank by using the binary search
        int N = A.length;
        int M = C.length;
        // two dimension array to save the original index of array C
        int[][] sortedNail = new int[M][2];
        for (int i = 0; i < M; i++) {
            sortedNail[i][0] = C[i];
            sortedNail[i][1] = i;
        }
        // use the lambda expression to sort two dimension array
        Arrays.sort(sortedNail, (int x[], int y[]) -> x[0] - y[0]);
        int result = 0;
        for (int i = 0; i < N; i++) {//find the earlist position that can nail each plank, and the max value for all planks is the result
            result = getMinIndex(A[i], B[i], sortedNail, result);
            if (result == -1)
                return -1;
        }
        return result + 1;
    }
    // for each plank , we can use binary search to get the minimal index of the
    // sorted array of nails, and we should check the candidate nails to get the
    // minimal index of the original array of nails.
    public int getMinIndex(int startPlank, int endPlank, int[][] nail, int preIndex) {
        int min = 0;
        int max = nail.length - 1;
        int minIndex = -1;
        while (min <= max) {
            int mid = (min + max) / 2;
            if (nail[mid][0] < startPlank)
                min = mid + 1;
            else if (nail[mid][0] > endPlank)
                max = mid - 1;
            else {
                max = mid - 1;
                minIndex = mid;
            }
        }
        if (minIndex == -1)
            return -1;
        int minIndexOrigin = nail[minIndex][1];
        //find the smallest original position of nail that can nail the plank
        for (int i = minIndex; i < nail.length; i++) {
            if (nail[i][0] > endPlank)
                break;
            minIndexOrigin = Math.min(minIndexOrigin, nail[i][1]);
            // we need the maximal index of nails to nail every plank, so the
            // smaller index can be omitted    ****
            if (minIndexOrigin <= preIndex) // ****
                return preIndex;            // ****
        }
        return minIndexOrigin;
    }
}

I don't understand Line 99-102, marked with ****, of the solution.

My question is:

If minIndexOrigin <= preIndex , then it will use preIndex,
but how if the preIndex doesn't nail the current plank ?

Is there a bit mistake with the solution ?

Body:
The case that is handled in those lines is when you find that there is an index that nails the current plank, which index is less (or equal) to the lowest index we need to be able to nail another (previously analysed) plank. In that case, we don't need to look further for the current plank, since we know that:

we can nail the plank

we can use an index that is not greater than an index we really need to use for another plank.

Since we are only interested in the greatest index among the least indexes we need for the different planks (i.e. the index for the "worst" plank), we know that the index we just found now is not important any more: if we already know that we will be using all the nails up to at least preIndex, we know that one nail among that set will nail the current plank. We can just exit the loop and return a "dummy" index that will not influence the result.

Note what the effect is in the calling loop:

result = getMinIndex(A[i], B[i], sortedNail, result);

After this assignment, result will be equal to what result was before the call: this plank (A[i], B[i]) can be nailed with an earlier nail, but we don't really care which nail that is, as we need to know the worst case, which is up to now reflected by result, and all nails up to that index are already in the set of nails that will be hammered.

You can compare it with alpha-beta pruning.