问:
How to add margin to SVG Circle's stroke for a simple donut
I'm trying to build a very simple donut chart.

Here's the working code :

const countries = [
{'percent': 2,colour: 'red'},
{'percent': 28,colour: 'blue'},
{'percent': 36,colour: 'yellow'},
{'percent': 34,colour: 'orange'}
];

const donutData = countries.map((country, index) => {
  return {
    stroke: country.colour,
    dashoffset: 25 - countries.slice(0, index).reduce((a, b) => a + b.percent, 0),
    dashArray: [country.percent, 100 - country.percent]
  }
});
const div = document.createElement('div');
div.innerHTML = '<svg id="donut" width="100%" height="100%" viewBox="3 3 36 36"></svg>';
document.body.appendChild(div);
document.querySelector('#donut').innerHTML= donutData.reduce((a, item) => {
  return a +
    `<circle
   cx="21"
    cy="21"
    fill="transparent"
    r="15.91549430918954"
    stroke-width="2.3"
    stroke="${item.stroke}"
    stroke-dasharray="${item.dashArray[0]} ${item.dashArray[1]}"
    stroke-dashoffset="${item.dashoffset}"></circle>
`;
}, '')```

https://jsfiddle.net/miladhi/1dxnkjht/1/

Above works fine, but try adding stroke-linecap="round" to the <circle> and it goes pare shaped, the strokes are on top of each other.

As you can see here https://jsfiddle.net/miladhi/x8w4kgdv/.

I can understand the problem, but don't know how to add a little bit of margin between the strokes to avoid the ugly stacking.

I appreciate any suggestion.

答:
This is how you can do it with paths and markers. The trick is to use a marker start / marker end combo. The seeming overlap of the previous line is actually stuck onto the current line as a marker start.

<svg width="600px" height="400px">
  <defs>
    <marker id="round-cap-blue" viewBox="0 0 1 1"
        markerWidth="1" markerHeight="1"
        orient="auto" refX="0.5" refY="0.5">
      <circle cx="0.5" cy="0.5" r="0.5" fill="blue"/>
    </marker>

        <marker id="round-cap-red" viewBox="0 0 1 1"
        markerWidth="1" markerHeight="1"
        orient="auto" refX="0.5" refY="0.5">
      <circle cx="0.5" cy="0.5" r="0.5" fill="red"/>
    </marker>

            <marker id="round-cap-green" viewBox="0 0 1 1"
        markerWidth="1" markerHeight="1"
        orient="auto" refX="0.5" refY="0.5">
      <circle cx="0.5" cy="0.5" r="0.5" fill="green"/>
    </marker>

    </defs>

  <g transform="translate(100,0)">

  <path fill="none" stroke="blue" stroke-width="30" d="M 150 150
           A 100 100 0 0 0 50 50" marker-end="url(#round-cap-blue)"/>

   <path fill="none" stroke="red" stroke-width="30" d="M 50 250
           A 100 100 0 0 0 150 150" marker-end="url(#round-cap-red)"/>

   <path fill="none" stroke="green" stroke-width="30" d="M 50 50
           A 100 100 0 0 0 50 250" marker-start="url(#round-cap-blue)" marker-end="url(#round-cap-green)"/>

  </g>

</svg>```

Body:
I'm trying to build a very simple donut chart.

Here's the working code :

const countries = [
{'percent': 2,colour: 'red'},
{'percent': 28,colour: 'blue'},
{'percent': 36,colour: 'yellow'},
{'percent': 34,colour: 'orange'}
];

const donutData = countries.map((country, index) => {
  return {
    stroke: country.colour,
    dashoffset: 25 - countries.slice(0, index).reduce((a, b) => a + b.percent, 0),
    dashArray: [country.percent, 100 - country.percent]
  }
});
const div = document.createElement('div');
div.innerHTML = '<svg id="donut" width="100%" height="100%" viewBox="3 3 36 36"></svg>';
document.body.appendChild(div);
document.querySelector('#donut').innerHTML= donutData.reduce((a, item) => {
  return a +
    `<circle
   cx="21"
    cy="21"
    fill="transparent"
    r="15.91549430918954"
    stroke-width="2.3"
    stroke="${item.stroke}"
    stroke-dasharray="${item.dashArray[0]} ${item.dashArray[1]}"
    stroke-dashoffset="${item.dashoffset}"></circle>
`;
}, '')

https://jsfiddle.net/miladhi/1dxnkjht/1/

Above works fine, but try adding stroke-linecap="round" to the <circle> and it goes pare shaped, the strokes are on top of each other.

As you can see here https://jsfiddle.net/miladhi/x8w4kgdv/.

I can understand the problem, but don't know how to add a little bit of margin between the strokes to avoid the ugly stacking.

I appreciate any suggestion.


来源: stackexchange

问:
R split string into elements, sort and recombine
The basic problem I'm trying to solve has been done for a single character vector and a character vector within a data frame. I'm trying to do it for a data table because I have a lot of columns that are a single string with multiple elements so I'd like to do this in memory without making copies. In the code below I tried to follow the approach taken at this link.

```<code>test <- data.table(col1 = c("cow, pig, horse"), col2 = c("fish, aardvark, moose"))
test2 <- data.table(col1 = c("orange, pig, frog"), col2 = c("whale, aardvark, elk"))
test <- rbind(test, test2)
cols <- c("col1", "col2")

test[, (cols) := (lapply(.SD, function(x) {
  paste(sort(trimws(strsplit(x, ',')[[1]])), collapse=',')
  })), .SDcols = cols]
</code>```

What I end up with is the first row, sorted, in both rows. Help, please, and with a bit of explanation of what I'm doing wrong.

答:
We need a second *apply to loop through elements of x.

```<code>test[, (cols) := (lapply(.SD, function(x) {
   #browser()
   sapply(x, function(y) paste(sort(trimws(strsplit(y, ',')[[1]])), collapse=','))
})), .SDcols = cols]

> test
              col1                col2
1:   cow,horse,pig aardvark,fish,moose
2: frog,orange,pig  aardvark,elk,whale
</code>```

strsplit(x, ',')[[1]] used the first element from each column, as you can see below

```<code>Browse[1]> strsplit(x, ',')
[[1]]
[1] "cow"    " pig"   " horse"

[[2]]
[1] "orange" " pig"   " frog"

Browse[1]> strsplit(x, ',')[[1]]
[1] "cow"    " pig"   " horse"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The basic problem I'm trying to solve has been done for a single character vector and a character vector within a data frame. I'm trying to do it for a data table because I have a lot of columns that are a single string with multiple elements so I'd like to do this in memory without making copies. In the code below I tried to follow the approach taken at this link.

test <- data.table(col1 = c("cow, pig, horse"), col2 = c("fish, aardvark, moose"))
test2 <- data.table(col1 = c("orange, pig, frog"), col2 = c("whale, aardvark, elk"))
test <- rbind(test, test2)
cols <- c("col1", "col2")

test[, (cols) := (lapply(.SD, function(x) {
  paste(sort(trimws(strsplit(x, ',')[[1]])), collapse=',')
  })), .SDcols = cols]

What I end up with is the first row, sorted, in both rows. Help, please, and with a bit of explanation of what I'm doing wrong.

Body:
We need a second *apply to loop through elements of x.

test[, (cols) := (lapply(.SD, function(x) {
   #browser()
   sapply(x, function(y) paste(sort(trimws(strsplit(y, ',')[[1]])), collapse=','))
})), .SDcols = cols]

> test
              col1                col2
1:   cow,horse,pig aardvark,fish,moose
2: frog,orange,pig  aardvark,elk,whale

strsplit(x, ',')[[1]] used the first element from each column, as you can see below

Browse[1]> strsplit(x, ',')
[[1]]
[1] "cow"    " pig"   " horse"

[[2]]
[1] "orange" " pig"   " frog"

Browse[1]> strsplit(x, ',')[[1]]
[1] "cow"    " pig"   " horse"


问:
How to use Google Cloud Firestore local emulator for python and for testing purpose
I tried to find out how to use firestore local emulator for python and for testing purpose. But I can not find out how-to document.

Could somebody help me?

答:
Using the firebase_admin python module, follow the standard setup documented in the Cloud Firestore Docs

This will involve calling initialize_app with a credentials context and then creating a traditional Firestore Client with firestore.client()

For example:

from firebase_admin import credentials, firestore, initialize_app

firebase_credentials_file_path = ...
cred = credentials.Certificate(firebase_credentials_file_path)
initialize_app(cred)
db = firestore.client()
```

<p>Next, you will need to install and run the Firestore Emulator, which will host the a local Firestore instance over <code>localhost:8080</code>.</p>

<pre class="lang-sh prettyprint-override"><code>npx firebase setup:emulators:firestore
npx firebase --token $FIREBASE_TOKEN emulators:start --only firestore --project $PROJECT_KEY
</code>```

Finally, inject a redirect in the already instantiated firestore.client instance to interact with the local emulator host/port using an insecure GRPC channel:

import grpc
from google.cloud.firestore_v1.gapic import firestore_client
from google.cloud.firestore_v1.gapic.transports import firestore_grpc_transport

channel = grpc.insecure_channel("localhost:8080")
transport = firestore_grpc_transport.FirestoreGrpcTransport(channel=channel)
db._firestore_api_internal = firestore_client.FirestoreClient(transport=transport)
```

Now, your db object will interact with the local emulator without any problems.

Acknowledgements to John Carter for figuring this out on the gcloud internal api

Body:
Using the firebase_admin python module, follow the standard setup documented in the Cloud Firestore Docs

This will involve calling initialize_app with a credentials context and then creating a traditional Firestore Client with firestore.client()

For example:

from firebase_admin import credentials, firestore, initialize_app

firebase_credentials_file_path = ...
cred = credentials.Certificate(firebase_credentials_file_path)
initialize_app(cred)
db = firestore.client()

Next, you will need to install and run the Firestore Emulator, which will host the a local Firestore instance over localhost:8080.

npx firebase setup:emulators:firestore
npx firebase --token $FIREBASE_TOKEN emulators:start --only firestore --project $PROJECT_KEY

Finally, inject a redirect in the already instantiated firestore.client instance to interact with the local emulator host/port using an insecure GRPC channel:

import grpc
from google.cloud.firestore_v1.gapic import firestore_client
from google.cloud.firestore_v1.gapic.transports import firestore_grpc_transport

channel = grpc.insecure_channel("localhost:8080")
transport = firestore_grpc_transport.FirestoreGrpcTransport(channel=channel)
db._firestore_api_internal = firestore_client.FirestoreClient(transport=transport)

Now, your db object will interact with the local emulator without any problems.

Acknowledgements to John Carter for figuring this out on the gcloud internal api


问:
Make Two columns out of one XML XSLT to HTML
I have XML coming from a source that I can't change. They send it as a list but the lists can also have embedded lists. Here is an example keeping it short:

```<code><LinkList>
  <ListHeader>A</ListHeader>
  <ArticleLink chunkiid="13121">A Test 1</ArticleLink>
  <ArticleLink chunkiid="13122">A Test 2</ArticleLink>
  <ArticleLink chunkiid="13123">A Test 3</ArticleLink>
  <LinkList>
    <ListHeader>
      <ArticleLink chunkiid="13124">A Inner List</ArticleLink>
    </ListHeader>
    <ArticleLink chunkiid="13125">A Inner Test 1</ArticleLink>
    <ArticleLink chunkiid="13126">A Inner Test 2</ArticleLink>
  </LinkList>
  <ArticleLink chunkiid="13127">A Test 4</ArticleLink>
  <ArticleLink chunkiid="13128">A Test 5</ArticleLink>
</LinkList>
</code>```

Keep in mind it is much bigger in real life. I want to split this into two columns using XSLT or CSS or JQuery. The current output if I leave it one column looks like this:

```<code><b>A</b>
<ul>
    <li><a href="Article.aspx?id=13121">A Test 1</a></li>
    <li><a href="Article.aspx?id=13122">A Test 2</a></li>
    <li><a href="Article.aspx?id=13123">A Test 3</a></li>
    <li>
        <b><a href="Article.aspx?id=13124">A Inner List</a></b>
        <ul>
            <li><a href="Article.aspx?id=13125">A Inner Test 1</a></li>
            <li><a href="Article.aspx?id=13126">A Inner Test 1</a></li>
        </ul>
    </li>
    <li><a href="Article.aspx?id=13127">A Test 4</a></li>
    <li><a href="Article.aspx?id=13128">A Test 5</a></li>
</ul>
</code>```

I have been able to split it using XSLT but I can only do it on the bottom list so if there are inner lists it sometimes make one side or the other longer. I am doing a count in to a variable and then applying a template like this in XSLT:

```<code><xsl:template match="LinkList">
  <xsl:if test="ListHeader = $CurrentAlphaIndex">
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates select="ListHeader"/>
    <xsl:variable name="OneSideCount">
      <xsl:value-of select="ceiling((count(child::*) - 1) div 2)" />
    </xsl:variable>
    <div class="col-50">
      <div class="layout-inner-2">
        <ul>
          <xsl:apply-templates select="*[not(self::ListHeader) and (position() - 1) <= $OneSideCount]">
            <xsl:sort select="."/>
          </xsl:apply-templates>
        </ul>
      </div>
    </div>
    <div class="col-50">
      <div class="layout-inner-2">
        <ul>
          <xsl:apply-templates select="*[not(self::ListHeader) and (position() - 1) > $OneSideCount]">
            <xsl:sort select="."/>
          </xsl:apply-templates>
        </ul>
      </div>
    </div>
    <div class="spacer"> </div>
  </xsl:if>
</xsl:template>
</code>```

I left out some of the templates as I didn't want this to long. I figure this shows how I am breaking it up right now but from my example you can see the right side is longer because of the inner list.

Is there any way to leave it a single list and break it up into two columns using CSS or JQuery? If not is there a way I can count all links in the XML and split it up using a position() that also includes children nodes?

Update
What I mean by two columns is having half the records on one side of the page and half on the other. Sorry the XSLT is using div tags only because that is the standard on this site set by the client and their designer.

答:
Without extension functions just for fun:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="CurrentAlphaIndex" select="'A'"/>
    <xsl:param name="pColumns" select="2"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="LinkList">
        <xsl:if test="ListHeader = $CurrentAlphaIndex">
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="ListHeader"/>
            <xsl:variable name="vArticleLinks"
                 select="descendant-or-self::LinkList/ArticleLink"/>
            <xsl:variable name="OneSideCount"
                 select="ceiling(count($vArticleLinks) div $pColumns)"/>
            <xsl:apply-templates
                 select="$vArticleLinks[position() mod $OneSideCount = 1]"
                 mode="partition">
                <xsl:with-param name="OneSideCount"
                                select="$OneSideCount"/>
                <xsl:with-param name="pArticleLinks"
                                select="$vArticleLinks"/>
            </xsl:apply-templates>
            <div class="spacer">&nbsp;</div>
        </xsl:if>
    </xsl:template>
    <xsl:template match="ArticleLink" mode="partition">
        <xsl:param name="pArticleLinks" select="/.."/>
        <xsl:param name="OneSideCount" select="0"/>
        <xsl:variable name="vOffSet"
                      select="(position() - 1) * $OneSideCount"/>
        <div class="col-50">
            <div class="layout-inner-2">
                <ul>
                    <xsl:apply-templates select="$pArticleLinks"
                                         mode="filter">
                        <xsl:with-param name="OneSideCount"
                             select="$OneSideCount"/>
                        <xsl:with-param name="pOffSet"
                             select="(position() - 1) * $OneSideCount"/>
                        <xsl:sort/>
                    </xsl:apply-templates>
                </ul>
            </div>
        </div>
    </xsl:template>
    <xsl:template match="ArticleLink" mode="filter">
        <xsl:param name="pOffSet" select="0"/>
        <xsl:param name="OneSideCount" select="0"/>
        <xsl:if test="position() > $pOffSet
                         and
                      $pOffSet + $OneSideCount >= position()">
            <xsl:apply-templates select="."/>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
</code>```

Output:

```<code><ListHeader>A</ListHeader>
<div class="col-50">
    <div class="layout-inner-2">
        <ul>
            <ArticleLink chunkiid="13125">A Inner Test 1</ArticleLink>
            <ArticleLink chunkiid="13126">A Inner Test 2</ArticleLink>
            <ArticleLink chunkiid="13121">A Test 1</ArticleLink>
            <ArticleLink chunkiid="13122">A Test 2</ArticleLink>
        </ul>
    </div>
</div>
<div class="col-50">
    <div class="layout-inner-2">
        <ul>
            <ArticleLink chunkiid="13123">A Test 3</ArticleLink>
            <ArticleLink chunkiid="13127">A Test 4</ArticleLink>
            <ArticleLink chunkiid="13128">A Test 5</ArticleLink>
        </ul>
    </div>
</div>
<div class="spacer">&nbsp;</div>
</code>```

With extensions (better performance):

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com:xslt"
 exclude-result-prefixes="msxsl">
    <xsl:param name="CurrentAlphaIndex" select="'A'"/>
    <xsl:param name="pColumns" select="2"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="LinkList">
        <xsl:if test="ListHeader = $CurrentAlphaIndex">
            <xsl:apply-templates select="@*|ListHeader"/>
            <xsl:variable name="vrftArticleLinks">
                <xsl:for-each
                 select="descendant-or-self::LinkList/ArticleLink">
                    <xsl:sort/>
                    <xsl:copy-of select="."/>
                </xsl:for-each>
            </xsl:variable>
            <xsl:variable name="vArticleLinks"
                 select="msxsl:node-set($vrftArticleLinks)/*"/>
            <xsl:variable name="OneSideCount"
                 select="ceiling(count($vArticleLinks) div $pColumns)"/>
            <xsl:for-each
                 select="$vArticleLinks[position() mod $OneSideCount = 1]">
                <div class="col-50">
                    <div class="layout-inner-2">
                        <ul>
                            <xsl:apply-templates
                             select=".|following-sibling::*[
                                          $OneSideCount > position()
                                       ]"/>
                        </ul>
                    </div>
                </div>
            </xsl:for-each>
            <div class="spacer">&nbsp;</div>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have XML coming from a source that I can't change. They send it as a list but the lists can also have embedded lists. Here is an example keeping it short:

<LinkList>
  <ListHeader>A</ListHeader>
  <ArticleLink chunkiid="13121">A Test 1</ArticleLink>
  <ArticleLink chunkiid="13122">A Test 2</ArticleLink>
  <ArticleLink chunkiid="13123">A Test 3</ArticleLink>
  <LinkList>
    <ListHeader>
      <ArticleLink chunkiid="13124">A Inner List</ArticleLink>
    </ListHeader>
    <ArticleLink chunkiid="13125">A Inner Test 1</ArticleLink>
    <ArticleLink chunkiid="13126">A Inner Test 2</ArticleLink>
  </LinkList>
  <ArticleLink chunkiid="13127">A Test 4</ArticleLink>
  <ArticleLink chunkiid="13128">A Test 5</ArticleLink>
</LinkList>

Keep in mind it is much bigger in real life. I want to split this into two columns using XSLT or CSS or JQuery. The current output if I leave it one column looks like this:

A

A Test 1

A Test 2

A Test 3

        A Inner List

A Inner Test 1

A Inner Test 1

A Test 4

A Test 5

I have been able to split it using XSLT but I can only do it on the bottom list so if there are inner lists it sometimes make one side or the other longer. I am doing a count in to a variable and then applying a template like this in XSLT:

<xsl:template match="LinkList">
  <xsl:if test="ListHeader = $CurrentAlphaIndex">
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates select="ListHeader"/>
    <xsl:variable name="OneSideCount">
      <xsl:value-of select="ceiling((count(child::*) - 1) div 2)" />
    </xsl:variable>

          <xsl:apply-templates select="*[not(self::ListHeader) and (position() - 1) <= $OneSideCount]">
            <xsl:sort select="."/>
          </xsl:apply-templates>

          <xsl:apply-templates select="*[not(self::ListHeader) and (position() - 1) > $OneSideCount]">
            <xsl:sort select="."/>
          </xsl:apply-templates>

&nbsp;

  </xsl:if>
</xsl:template>

I left out some of the templates as I didn't want this to long. I figure this shows how I am breaking it up right now but from my example you can see the right side is longer because of the inner list.

Is there any way to leave it a single list and break it up into two columns using CSS or JQuery? If not is there a way I can count all links in the XML and split it up using a position() that also includes children nodes?

Update
What I mean by two columns is having half the records on one side of the page and half on the other. Sorry the XSLT is using div tags only because that is the standard on this site set by the client and their designer.

Body:
Without extension functions just for fun:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="CurrentAlphaIndex" select="'A'"/>
    <xsl:param name="pColumns" select="2"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="LinkList">
        <xsl:if test="ListHeader = $CurrentAlphaIndex">
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="ListHeader"/>
            <xsl:variable name="vArticleLinks"
                 select="descendant-or-self::LinkList/ArticleLink"/>
            <xsl:variable name="OneSideCount"
                 select="ceiling(count($vArticleLinks) div $pColumns)"/>
            <xsl:apply-templates
                 select="$vArticleLinks[position() mod $OneSideCount = 1]"
                 mode="partition">
                <xsl:with-param name="OneSideCount"
                                select="$OneSideCount"/>
                <xsl:with-param name="pArticleLinks"
                                select="$vArticleLinks"/>
            </xsl:apply-templates>
            <div class="spacer">&amp;nbsp;</div>
        </xsl:if>
    </xsl:template>
    <xsl:template match="ArticleLink" mode="partition">
        <xsl:param name="pArticleLinks" select="/.."/>
        <xsl:param name="OneSideCount" select="0"/>
        <xsl:variable name="vOffSet"
                      select="(position() - 1) * $OneSideCount"/>
        <div class="col-50">
            <div class="layout-inner-2">
                <ul>
                    <xsl:apply-templates select="$pArticleLinks"
                                         mode="filter">
                        <xsl:with-param name="OneSideCount"
                             select="$OneSideCount"/>
                        <xsl:with-param name="pOffSet"
                             select="(position() - 1) * $OneSideCount"/>
                        <xsl:sort/>
                    </xsl:apply-templates>
                </ul>
            </div>
        </div>
    </xsl:template>
    <xsl:template match="ArticleLink" mode="filter">
        <xsl:param name="pOffSet" select="0"/>
        <xsl:param name="OneSideCount" select="0"/>
        <xsl:if test="position() > $pOffSet
                         and
                      $pOffSet + $OneSideCount >= position()">
            <xsl:apply-templates select="."/>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Output:

<ListHeader>A</ListHeader>
<div class="col-50">
    <div class="layout-inner-2">
        <ul>
            <ArticleLink chunkiid="13125">A Inner Test 1</ArticleLink>
            <ArticleLink chunkiid="13126">A Inner Test 2</ArticleLink>
            <ArticleLink chunkiid="13121">A Test 1</ArticleLink>
            <ArticleLink chunkiid="13122">A Test 2</ArticleLink>
        </ul>
    </div>
</div>
<div class="col-50">
    <div class="layout-inner-2">
        <ul>
            <ArticleLink chunkiid="13123">A Test 3</ArticleLink>
            <ArticleLink chunkiid="13127">A Test 4</ArticleLink>
            <ArticleLink chunkiid="13128">A Test 5</ArticleLink>
        </ul>
    </div>
</div>
<div class="spacer">&amp;nbsp;</div>

With extensions (better performance):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com:xslt"
 exclude-result-prefixes="msxsl">
    <xsl:param name="CurrentAlphaIndex" select="'A'"/>
    <xsl:param name="pColumns" select="2"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="LinkList">
        <xsl:if test="ListHeader = $CurrentAlphaIndex">
            <xsl:apply-templates select="@*|ListHeader"/>
            <xsl:variable name="vrftArticleLinks">
                <xsl:for-each
                 select="descendant-or-self::LinkList/ArticleLink">
                    <xsl:sort/>
                    <xsl:copy-of select="."/>
                </xsl:for-each>
            </xsl:variable>
            <xsl:variable name="vArticleLinks"
                 select="msxsl:node-set($vrftArticleLinks)/*"/>
            <xsl:variable name="OneSideCount"
                 select="ceiling(count($vArticleLinks) div $pColumns)"/>
            <xsl:for-each
                 select="$vArticleLinks[position() mod $OneSideCount = 1]">
                <div class="col-50">
                    <div class="layout-inner-2">
                        <ul>
                            <xsl:apply-templates
                             select=".|following-sibling::*[
                                          $OneSideCount > position()
                                       ]"/>
                        </ul>
                    </div>
                </div>
            </xsl:for-each>
            <div class="spacer">&amp;nbsp;</div>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>


问:
Local time in Azure Data Explorer / Kusto timechart
Timechart x-axis time is printed in UTC-2h, while it should be printed in UTC. Other chars, such us Columnchart, work fine (time is shown in UTC).
Is this an issue?
Is it possible to format time in charts? For instance, printing x-axis time in local time...

Timechart column in Azure Data Explorer is stored in UTC (Local time -2h in my location).
When printing a columnchart, time in X-axis is printed in UTC (local time -2h) -> OK
columnchart output
When printing a timechart, time in x-axis is printed in UTC-2h (local time-4)-> KO
timechartoutput

Azure Data Explorer query:

```<code>let min_t = toscalar (<tablename>  | summarize min(Timestamp));
let max_t = toscalar (<tablename>  | summarize max(Timestamp));
<tablename>
| make-series sum(TrxCount) on Timestamp in range(min_t, max_t, 30m )
| render columnchart
</code>```

答:
This is indeed a bug.

It happens specifically after make-series so doing something like

<tablename> | summarize sum(TrxCount) by bin(Timestamp, 30m) | render timechart

should work (although it won't fill empty data like make-series does.

Body:
Timechart x-axis time is printed in UTC-2h, while it should be printed in UTC. Other chars, such us Columnchart, work fine (time is shown in UTC).
Is this an issue?
Is it possible to format time in charts? For instance, printing x-axis time in local time...

Timechart column in Azure Data Explorer is stored in UTC (Local time -2h in my location).
When printing a columnchart, time in X-axis is printed in UTC (local time -2h) -> OK
columnchart output
When printing a timechart, time in x-axis is printed in UTC-2h (local time-4)-> KO
timechartoutput

Azure Data Explorer query:

let min_t = toscalar (<tablename>  | summarize min(Timestamp));
let max_t = toscalar (<tablename>  | summarize max(Timestamp));
<tablename>
| make-series sum(TrxCount) on Timestamp in range(min_t, max_t, 30m )
| render columnchart


问:
Blank Plot Output when using "geom_xspline" in ggalt package
When trying to use geom_xspline from ggalt in conjunction with ggarrange from ggpubr, the output is blank and no other plot can be made before clearing with dev.off().

In my use-case I wanted the geom_xspline to replace some exisitng geom_line in my ggplot object. Is anyone aware of issues using geoms added from other R packages?

Here is some code to compare, nothing of interest really, just to give a reproducible example:

Initial Working Code w/o geom_xspline

library(ggplot2)
library(ggpubr)
myplot = ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_line()
ggarrange(myplot, myplot) # Works and outputs fine
```

<p><strong>Code that fails with <code>ggalt</code> package</strong></p>

<pre class="lang-r prettyprint-override"><code>library(ggalt)
library(ggplot2)
library(ggpubr)
myplot = ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_xspline()
ggarrange(myplot, myplot) # Output becomes blank and freezes the plot panel
</code>```

Alternative Method
Instead of using ggarrange I tried the function grid_arrange_shared_legend from this link, which uses grid and gridExtra. However, I am still curious as to why ggarrange does not work.

Here is my session info:

R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ggpubr_0.1.8  magrittr_1.5  ggplot2_3.0.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.18       pillar_1.3.0       compiler_3.5.1     RColorBrewer_1.1-2 plyr_1.8.4         bindr_0.1.1
 [7] tools_3.5.1        extrafont_0.17     tibble_1.4.2       gtable_0.2.0       pkgconfig_2.0.1    rlang_0.2.1
[13] rstudioapi_0.7     yaml_2.2.0         bindrcpp_0.2.2     Rttf2pt1_1.3.7     withr_2.1.2        dplyr_0.7.6
[19] maps_3.3.0         grid_3.5.1         ggalt_0.4.0        tidyselect_0.2.4   cowplot_0.9.3      glue_1.3.0
[25] R6_2.2.2           purrr_0.2.5        extrafontdb_1.0    scales_1.0.0       MASS_7.3-50        assertthat_0.2.0
[31] proj4_1.0-8        colorspace_1.3-2   labeling_0.3       KernSmooth_2.23-15 ash_1.0-15         lazyeval_0.2.1
[37] munsell_0.5.0      crayon_1.3.4
```

Quick addition, if I convert the object to a ggplotGrob(), it will work with ggarrange, but it will fail when I attempt to use common.legend = T.

答:
Well I am not sure why ggpubr::ggarrange causes failure of Plots pannel when used with ggalt::geom_xspline but I can tell you that plots are still getting created but just now shown on the plot pannel.

So it seems that using those together causes failure in the graphing device and it is only happening for ggalt::geom_xspline and not all the geoms in ggalt. That is a bug so you are on the right track posting to GitHub.

You can check that by running the code below:

library(ggalt)
library(ggplot2)
library(ggpubr)

myplot = ggplot(data = mtcars, aes(x = wt, y = mpg)) +
  geom_xspline()
myplot
```

<p><img src="https://i.imgur.com/3EkPPt4.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>g <- ggarrange(myplot, myplot) # Output becomes blank and freezes the plot panel
g

jpeg('rplot.jpg')
g
dev.off()
#> pdf
#>   3
</code>```

Created on 2019-05-30 by the reprex package (v0.3.0)

And this is the saved plot:

Body:
When trying to use geom_xspline from ggalt in conjunction with ggarrange from ggpubr, the output is blank and no other plot can be made before clearing with dev.off().

In my use-case I wanted the geom_xspline to replace some exisitng geom_line in my ggplot object. Is anyone aware of issues using geoms added from other R packages?

Here is some code to compare, nothing of interest really, just to give a reproducible example:

Initial Working Code w/o geom_xspline

library(ggplot2)
library(ggpubr)
myplot = ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_line()
ggarrange(myplot, myplot) # Works and outputs fine

Code that fails with ggalt package

library(ggalt)
library(ggplot2)
library(ggpubr)
myplot = ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_xspline()
ggarrange(myplot, myplot) # Output becomes blank and freezes the plot panel

Alternative Method
Instead of using ggarrange I tried the function grid_arrange_shared_legend from this link, which uses grid and gridExtra. However, I am still curious as to why ggarrange does not work.

Here is my session info:

R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ggpubr_0.1.8  magrittr_1.5  ggplot2_3.0.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.18       pillar_1.3.0       compiler_3.5.1     RColorBrewer_1.1-2 plyr_1.8.4         bindr_0.1.1
 [7] tools_3.5.1        extrafont_0.17     tibble_1.4.2       gtable_0.2.0       pkgconfig_2.0.1    rlang_0.2.1
[13] rstudioapi_0.7     yaml_2.2.0         bindrcpp_0.2.2     Rttf2pt1_1.3.7     withr_2.1.2        dplyr_0.7.6
[19] maps_3.3.0         grid_3.5.1         ggalt_0.4.0        tidyselect_0.2.4   cowplot_0.9.3      glue_1.3.0
[25] R6_2.2.2           purrr_0.2.5        extrafontdb_1.0    scales_1.0.0       MASS_7.3-50        assertthat_0.2.0
[31] proj4_1.0-8        colorspace_1.3-2   labeling_0.3       KernSmooth_2.23-15 ash_1.0-15         lazyeval_0.2.1
[37] munsell_0.5.0      crayon_1.3.4

Quick addition, if I convert the object to a ggplotGrob(), it will work with ggarrange, but it will fail when I attempt to use common.legend = T.

Body:
Well I am not sure why ggpubr::ggarrange causes failure of Plots pannel when used with ggalt::geom_xspline but I can tell you that plots are still getting created but just now shown on the plot pannel.

So it seems that using those together causes failure in the graphing device and it is only happening for ggalt::geom_xspline and not all the geoms in ggalt. That is a bug so you are on the right track posting to GitHub.

You can check that by running the code below:

library(ggalt)
library(ggplot2)
library(ggpubr)

myplot = ggplot(data = mtcars, aes(x = wt, y = mpg)) +
  geom_xspline()
myplot

g <- ggarrange(myplot, myplot) # Output becomes blank and freezes the plot panel
g

jpeg('rplot.jpg')
g
dev.off()
#> pdf
#>   3

Created on 2019-05-30 by the reprex package (v0.3.0)

And this is the saved plot:


问:
NetSuite python TBA Authentication
I am new to this area of using SOAP for NetSuite calls. Hence, I might be thinking completely incorrectly on how to solve the problem. Here is what I am trying to solve:
- Language: Python+ Zeep
- I want to move my application from email pass to Token based authentication.

In Python I am able to generate all the parameters for TokenPassport.
Here is where I am confused: I looked up some code on stack and noticed that folks were using client.service.login() method to login. This method takes the passport and not the tokenpassport obj.
Is there a separate method that takes tokenpassport obj for login?, Or do I need to generate(hardcode) an XML with the parameters and is this passed in header as data?

Thanks
T

答:
Here is how I generate the TokenPassport.</p>

```<code>    def _generateTimestamp(self):
        return str(int(time()))

    def _generateNonce(self, length=20):
        """Generate pseudorandom number
        """
        return ''.join([str(random.randint(0, 9)) for i in range(length)])

    def _getSignatureMessage(self, nonce, timestamp):
        return '&'.join(
            (
                self._setting['ACCOUNT'],
                self._setting['CONSUMER_KEY'],
                self._setting['TOKEN_ID'],
                nonce,
                timestamp,
            )
        )

    def _getSignatureKey(self):
        return '&'.join((self._setting['CONSUMER_SECRET'], self._setting['TOKEN_SECRET']))

    def _getSignatureValue(self, nonce, timestamp):
        key = self._getSignatureKey()
        message = self._getSignatureMessage(nonce, timestamp)
        hashed = hmac.new(
            key=key.encode('utf-8'),
            msg=message.encode('utf-8'),
            digestmod=hashlib.sha256
        ).digest()
        return base64.b64encode(hashed).decode()

    @property
    def tokenPassport(self):
        TokenPassport = self.getDataType("ns0:TokenPassport")
        TokenPassportSignature = self.getDataType("ns0:TokenPassportSignature")

        nonce = self._generateNonce()
        timestamp = self._generateTimestamp()
        tokenPassportSignature = TokenPassportSignature(
            self._getSignatureValue(nonce, timestamp),
            algorithm='HMAC-SHA256'
        )

        return TokenPassport(
            account=self._setting['ACCOUNT'],
            consumerKey=self._setting['CONSUMER_KEY'],
            token=self._setting['TOKEN_ID'],
            nonce=nonce,
            timestamp=timestamp,
            signature=tokenPassportSignature
        )
</code>```

Title: NetSuite python TBA Authentication

Body:
Here is how I generate the TokenPassport.

    def _generateTimestamp(self):
        return str(int(time()))

    def _generateNonce(self, length=20):
        """Generate pseudorandom number
        """
        return ''.join([str(random.randint(0, 9)) for i in range(length)])

    def _getSignatureMessage(self, nonce, timestamp):
        return '&'.join(
            (
                self._setting['ACCOUNT'],
                self._setting['CONSUMER_KEY'],
                self._setting['TOKEN_ID'],
                nonce,
                timestamp,
            )
        )

    def _getSignatureKey(self):
        return '&'.join((self._setting['CONSUMER_SECRET'], self._setting['TOKEN_SECRET']))

    def _getSignatureValue(self, nonce, timestamp):
        key = self._getSignatureKey()
        message = self._getSignatureMessage(nonce, timestamp)
        hashed = hmac.new(
            key=key.encode('utf-8'),
            msg=message.encode('utf-8'),
            digestmod=hashlib.sha256
        ).digest()
        return base64.b64encode(hashed).decode()

    @property
    def tokenPassport(self):
        TokenPassport = self.getDataType("ns0:TokenPassport")
        TokenPassportSignature = self.getDataType("ns0:TokenPassportSignature")

        nonce = self._generateNonce()
        timestamp = self._generateTimestamp()
        tokenPassportSignature = TokenPassportSignature(
            self._getSignatureValue(nonce, timestamp),
            algorithm='HMAC-SHA256'
        )

        return TokenPassport(
            account=self._setting['ACCOUNT'],
            consumerKey=self._setting['CONSUMER_KEY'],
            token=self._setting['TOKEN_ID'],
            nonce=nonce,
            timestamp=timestamp,
            signature=tokenPassportSignature
        )


问:
Variant named 'debug-x86' but only variants named '' were found
After upgrading to Android Studio 3.5 Canary 1 (but keeping the Android Gradle Plugin version at an older version 3.4.1), I started getting this error:

```<code>ERROR: Variant named 'debug-x86' but only variants named '' were found.
</code>```

The "Build Variants" window is empty, stuck at "Loading" state. Sync, refresh C++ project, build, etc. don't work.

答:
Fixed by:
   1. Upgrading to Android Studio 3.6 Canary 3, and
   2. Invalidate Caches and Restart.</p>

Body:
After upgrading to Android Studio 3.5 Canary 1 (but keeping the Android Gradle Plugin version at an older version 3.4.1), I started getting this error:

ERROR: Variant named 'debug-x86' but only variants named '' were found.

The "Build Variants" window is empty, stuck at "Loading" state. Sync, refresh C++ project, build, etc. don't work.


问:
How to set dynamic default parameters for py.test?
I have a framework which working under py.test. py.test can generate beauty reports with params --html and --junitxml. But clients that using my framework not always type this params to command line where they using py.test. I want make py.test to generate reports always when the py.test used with my framework. And i want to put this reports with log folder. So i need to generate path for report in runtime. Can i do this by fixtures? Or maybe by the plugin API?</p>

答:
Putting this in conftest.py will suffice:

def pytest_configure(config):
    if config.option.xmlpath is None:
        config.option.xmlpath = get_custom_xml_path() # implement this
```

The accepted answer is probably a bit more complicated than necessary for most people for a few reasons:

The decorator doesn't help. It doesn't matter when this executes.

There is no need make a custom LogXML since you can just set the property here and it will be used.

slaveinput is specific to a pytest plugin xdist. I don't think there is any need to check for that, especially if you don't use xdist.

Body:
Putting this in conftest.py will suffice:

def pytest_configure(config):
    if config.option.xmlpath is None:
        config.option.xmlpath = get_custom_xml_path() # implement this

The accepted answer is probably a bit more complicated than necessary for most people for a few reasons:

The decorator doesn't help. It doesn't matter when this executes.

There is no need make a custom LogXML since you can just set the property here and it will be used.

slaveinput is specific to a pytest plugin xdist. I don't think there is any need to check for that, especially if you don't use xdist.


问:
Where can i find NuGet.Clients documentation?
I'm trying to add Nuget package management to my newly developed IDE.
The github repository seems to have UI components here
but i can't find any resources for how to use it.

the only documentation i can find doesn't say anything about UI components

答:
The Nuget-Client-SDK doc states:

The API is evolving and not yet documented, but examples are available
  on Dave Glick's blog.

So it appears that the blog post that you mentioned is the extent of documentation currently available for that library.


问:
Understanding of Netty internals
In my understanding of Netty's, incoming message passed to eventLoop(only one eventLoop, one thread). Next, EventLoop doesn't process it, but pass it to ExecutorService(it holds multiple threads in pool) for execution.

All this happens with the help of NIO. EventLoop waits for incoming messages and pass it by selectors, keys, channels etc.

Am I right?

Netty 4 is used

答:
As far as i know Netty uses the EvenLoopGroups for handeling incoming and outgoing data as well as incoming connections.
That shouln't be so interesting when you start using Netty as the way the data goes through different classes. When a message is inbound the first interfacce you can intercept it is the decoder (ByteToMessageDecoder) where your encrypted ByteBuf is available. Then its making its way through the handler (ChannelInboundHandler).

Title: Understanding of Netty internals


问:
Convert ISO string to specific date format
I need to display date in a certain format in application. I have input of '2009-04-01' as string and I want this format April 1, 2009 using Javascript.</p>

答:
Create a Date object:

```<code>const date = new Date('2009-04-01');
</code>```

Format the Date using toLocaleString:

```<code>date.toLocaleString('en-us', { month: 'long', day: 'numeric', year: 'numeric' });
</code>```

Body:
Create a Date object:

const date = new Date('2009-04-01');

Format the Date using toLocaleString:

date.toLocaleString('en-us', { month: 'long', day: 'numeric', year: 'numeric' });


问:
Adding input box values to existing object based on checkbox
I have a table of data that is rendered via an api call. It displays 4 values from the initial object. I mainly care about the name value as this is what's important later in a post request.

Each row in the table has a checkbox. When the checkbox is selected (true) the name associated with that checkbox is added to an object called selectedFields, as an object. For example If I select the checkbox with name id it creates an object store like:

```<code>  "selectedFields": {
    "id" : {}
  }
</code>```

This works fine and well. However, I've added 3 input boxes that are associated with each name. The inputs are lengthType, size, maxArrayElements, which are of course user selectable.
What I'm having trouble with is adding these values back to the object so it looks like:

```<code>  "selectedFields": {
    "id": {
       lengthType: Variable,
       size: 1,
       maxArrayElements: 1
    },
    "price": {
       lengthType: Fixed,
       size: 10,
       maxArrayElements: 1
    }
  }
</code>```

How can I add these 3 values back to the name object that was created so it looks like the above example?

I don't want to post a wall of code, so I'm posting the checkbox function that handles creating the selectedFields object with the appropriate selected names. I suspect that the input values should get added here somehow, but I'm not sure.

```<code> checkbox = ({ name, isChecked }) => {
//handle check box of each fieldName
const obj = this.state.fieldNames.find(field => field.name === name);
if (isChecked === true) {
  //checked conditional
  this.setState(
    {
      selectedFields: {
        ...this.state.selectedFields,
        [name]: {
          ...obj
        }
      }
    },
    () => {
      console.log(
        "callback in  isChecked if conditional",
        this.state.selectedFields
      );
    }
  );
} else {
  const newSelectedFields = this.state.selectedFields;
  delete newSelectedFields[name];
  this.setState(
    {
      selectedFields: newSelectedFields
    },
    () => {
      console.log(
        `box unchecked, deleted from object --->`,
        this.state.selectedFields
      );
    }
  );
}
</code>```

};

You will have to make the first dropdown selection to view the data.

CodeSandbox link here

答:
Answer

You need to change a few things because nothing is stating where to assign the new state outside of the root state object.

Handlers in your Index.js:

Your handlers for the change events aren't looking for the name of the object to determine if it exists or not. If you want to add it to the specified child object you better be sure it's there.

We adjust the handlers to take an object name and setState with object.assign on that specific object if it exists:

note: since lengthType doesn't have a name property we simply provide it with a string. e.currentTarget will provide the option span, not the root Dropdown element, so even supplying a name property to that component wouldn't allow us to use e.currentTarget.name - you may want to consult the Semantic UI documentation if you would prefer something different. I gave it a quick scan but didn't want to deep dive it.

```<code>  handleChange = (e, obj_name) => {
    if (this.state.selectedFields[obj_name]) {
      let selectedFields = Object.assign({}, this.state.selectedFields);
      selectedFields[obj_name] = Object.assign(
        this.state.selectedFields[obj_name],
        { [e.target.name]: e.target.value }
      );
      this.setState({ selectedFields });
    }
  };

  onLengthTypeChange = (e, obj_name) => {
    if (this.state.selectedFields[obj_name]) {
      let selectedFields = Object.assign({}, this.state.selectedFields);
      selectedFields[obj_name] = Object.assign(
        this.state.selectedFields[obj_name],
        { lengthType: e.currentTarget.textContent }
      );
      this.setState({ selectedFields });
    }
  };
</code>```

The above, of course, won't work if you don't adjust your onChange events on your components so that, in addition to your event object, they also send your object name.

Handlers in your Component file:

Note: It was odd because in your Index.js file you seemed to half do this with lengthType but you weren't passing over additional data. You can't simply pass parameters into a handler - to get it to work you need to pass an anonymous function to the onChange properties that will take the event and pass it on to the handler functions with your object name:

```<code>      <Table.Cell>
        <Dropdown
          placeholder="Pick a length Type:"
          clearable
          selection
          search
          fluid
          noResultsMessage="Please search again"
          label="lengthType"
          multiple={false}
          options={lengthTypeOptions}
          header="Choose a Length Type"
          onChange={e => onLengthTypeChange(e, name)}
          value={lengthType}
          required
        />
      </Table.Cell>
      <Table.Cell>
        <Input
          onChange={e => handleChange(e, name)}
          value={this.state.size}
          type="number"
          name="size"
          min="1"
          placeholder="1"
          required
        />
      </Table.Cell>
      <Table.Cell>
        <Input
          onChange={e => handleChange(e, name)}
          value={this.state.maxArrayElements}
          type="number"
          name="maxArrayElements"
          placeholder="1"
          min="1"
          max="100"
          required
        />
      </Table.Cell>
</code>```

Once these things are adjusted, the code will update the specified properties on the child objects after the corresponding checkbox is selected.

Final Note:

I did not adjust it to save the previous state if you uncheck and then check the box. It wasn't specified in your question and I don't want to make assumptions.

Code Sandbox:

The adjusted code sandbox: https://codesandbox.io/s/createqueryschema-table-rewrite-bwvo4?fontsize=14

Additional Recommendations:

In your initial state your selectedFields is declared as an Array and then it is promptly turned into an Object when any checkbox is selected. I would suggest not doing this. Changing data types on a property during the course of running an application is very much asking for trouble.

When a checkbox is loaded  you provide a checkbox function from your Index.js file. This is simply called box in your component. I would suggest keeping the names of properties and state equivalent when passing down from parent to child. It is much, much, much easier for someone else to come in and maintain if they have to - not to mention easier to retain your own sanity.

The above checkbox function takes props from child and passes them up to the parent. This would be the place to pass your collected data into a cache on the parent, into local/session storage, or whatever you want to do with your data. You could instead write code to the effect of: if the checkbox is selected when an input handler is called do a save - but I would say that it would probably be best on render since the screen is constantly updating anyway and you have the checkbox function readily passing props currently. This is preference, so it's your call

Good luck! Hope this helped!

Body:
I have a table of data that is rendered via an api call. It displays 4 values from the initial object. I mainly care about the name value as this is what's important later in a post request.

Each row in the table has a checkbox. When the checkbox is selected (true) the name associated with that checkbox is added to an object called selectedFields, as an object. For example If I select the checkbox with name id it creates an object store like:

  "selectedFields": {
    "id" : {}
  }

This works fine and well. However, I've added 3 input boxes that are associated with each name. The inputs are lengthType, size, maxArrayElements, which are of course user selectable.
What I'm having trouble with is adding these values back to the object so it looks like:

  "selectedFields": {
    "id": {
       lengthType: Variable,
       size: 1,
       maxArrayElements: 1
    },
    "price": {
       lengthType: Fixed,
       size: 10,
       maxArrayElements: 1
    }
  }

How can I add these 3 values back to the name object that was created so it looks like the above example?

I don't want to post a wall of code, so I'm posting the checkbox function that handles creating the selectedFields object with the appropriate selected names. I suspect that the input values should get added here somehow, but I'm not sure.

 checkbox = ({ name, isChecked }) => {
//handle check box of each fieldName
const obj = this.state.fieldNames.find(field => field.name === name);
if (isChecked === true) {
  //checked conditional
  this.setState(
    {
      selectedFields: {
        ...this.state.selectedFields,
        [name]: {
          ...obj
        }
      }
    },
    () => {
      console.log(
        "callback in  isChecked if conditional",
        this.state.selectedFields
      );
    }
  );
} else {
  const newSelectedFields = this.state.selectedFields;
  delete newSelectedFields[name];
  this.setState(
    {
      selectedFields: newSelectedFields
    },
    () => {
      console.log(
        `box unchecked, deleted from object --->`,
        this.state.selectedFields
      );
    }
  );
}

};

You will have to make the first dropdown selection to view the data.

CodeSandbox link here

Body:
Answer

You need to change a few things because nothing is stating where to assign the new state outside of the root state object.

Handlers in your Index.js:

Your handlers for the change events aren't looking for the name of the object to determine if it exists or not. If you want to add it to the specified child object you better be sure it's there.

We adjust the handlers to take an object name and setState with object.assign on that specific object if it exists:

note: since lengthType doesn't have a name property we simply provide it with a string. e.currentTarget will provide the option span, not the root Dropdown element, so even supplying a name property to that component wouldn't allow us to use e.currentTarget.name - you may want to consult the Semantic UI documentation if you would prefer something different. I gave it a quick scan but didn't want to deep dive it.

  handleChange = (e, obj_name) => {
    if (this.state.selectedFields[obj_name]) {
      let selectedFields = Object.assign({}, this.state.selectedFields);
      selectedFields[obj_name] = Object.assign(
        this.state.selectedFields[obj_name],
        { [e.target.name]: e.target.value }
      );
      this.setState({ selectedFields });
    }
  };

  onLengthTypeChange = (e, obj_name) => {
    if (this.state.selectedFields[obj_name]) {
      let selectedFields = Object.assign({}, this.state.selectedFields);
      selectedFields[obj_name] = Object.assign(
        this.state.selectedFields[obj_name],
        { lengthType: e.currentTarget.textContent }
      );
      this.setState({ selectedFields });
    }
  };

The above, of course, won't work if you don't adjust your onChange events on your components so that, in addition to your event object, they also send your object name.

Handlers in your Component file:

Note: It was odd because in your Index.js file you seemed to half do this with lengthType but you weren't passing over additional data. You can't simply pass parameters into a handler - to get it to work you need to pass an anonymous function to the onChange properties that will take the event and pass it on to the handler functions with your object name:

      <Table.Cell>
        <Dropdown
          placeholder="Pick a length Type:"
          clearable
          selection
          search
          fluid
          noResultsMessage="Please search again"
          label="lengthType"
          multiple={false}
          options={lengthTypeOptions}
          header="Choose a Length Type"
          onChange={e => onLengthTypeChange(e, name)}
          value={lengthType}
          required
        />
      </Table.Cell>
      <Table.Cell>
        <Input
          onChange={e => handleChange(e, name)}
          value={this.state.size}
          type="number"
          name="size"
          min="1"
          placeholder="1"
          required
        />
      </Table.Cell>
      <Table.Cell>
        <Input
          onChange={e => handleChange(e, name)}
          value={this.state.maxArrayElements}
          type="number"
          name="maxArrayElements"
          placeholder="1"
          min="1"
          max="100"
          required
        />
      </Table.Cell>

Once these things are adjusted, the code will update the specified properties on the child objects after the corresponding checkbox is selected.

Final Note:

I did not adjust it to save the previous state if you uncheck and then check the box. It wasn't specified in your question and I don't want to make assumptions.

Code Sandbox:

The adjusted code sandbox: https://codesandbox.io/s/createqueryschema-table-rewrite-bwvo4?fontsize=14

Additional Recommendations:

In your initial state your selectedFields is declared as an Array and then it is promptly turned into an Object when any checkbox is selected. I would suggest not doing this. Changing data types on a property during the course of running an application is very much asking for trouble.

When a checkbox is loaded  you provide a checkbox function from your Index.js file. This is simply called box in your component. I would suggest keeping the names of properties and state equivalent when passing down from parent to child. It is much, much, much easier for someone else to come in and maintain if they have to - not to mention easier to retain your own sanity.

The above checkbox function takes props from child and passes them up to the parent. This would be the place to pass your collected data into a cache on the parent, into local/session storage, or whatever you want to do with your data. You could instead write code to the effect of: if the checkbox is selected when an input handler is called do a save - but I would say that it would probably be best on render since the screen is constantly updating anyway and you have the checkbox function readily passing props currently. This is preference, so it's your call

Good luck! Hope this helped!


问:
How can I allow multiple activities to share the same inflated "included" view?
I see this question here, and it makes me wonder if what I'm asking isn't really possible:

How to share a view across various activities

Basically, I have a common footer view that I'm inflating (including) in all of my views. However, it uses the same repetitive code to do that. My thought was to create a parent activity class to do this, but it doesn't seem correct to have one activity render the view of another. So should I just create a utility class of some sort, or is there a better way?

答:
If I understand your question, another way of having multiple Activities use the same View instance is by doing something like creating your own Application class (it's seriously easy).

MyApplication extends Application ...

@Override
public void onCreate(), onConfigurationChanged(), onLowMemory(), onTerminate(), getIstance().

As there is only a single intance of "Application" that is statically available it makes it a good place to store and share various objects that need to be passed around.


问:
Foreach-loop crashes when an object of another class is made
I'm making a game for a school project and I've run into a problem. The teacher requires that I use polymorphism in the code so basically, I have two classes, X and Y and they inherit from the abstract base class K.

I have a list for K objects so that objects of X and Y can be put in the list.
So the problem is that I want to run through the list with a foreach loop but only check the X objects.

```<code>foreach ( X object in list)...
</code>```

The game crashes as soon as an X object is created and I don't understand why!

```<code>foreach (GoldCoin gc in powerUps.ToList())
{
    if (gc.IsAlive)
    {
        player.speedY = 3;
    }
    else
    {
        powerUps.Remove(gc);
    }
</code>```

The error message said

System.InvalidCastException: 'Couldn't convert an object of the class X to the class Y.'

答:
From your pseudocode, it seems that you are forcing every object in the list to be an object of type X. But if the list contains also objects of type Y then you cannot assign that object to an instance of X

Suppose your class are:

```<code>class K
{
    public int value {get;set;}

}

class X : K
{
    public string Name { get; set; }
}
class Y : K
{
    public decimal money { get; set; }
}

void Main()
{
    List<K> elements = new List<K>();
    elements.Add(new X { Name = "Steve" });
    elements.Add(new Y {money = 100});

    // This cannot work, the second element is a Y and doesn't have a Name property
    // foreach(X obj in elements)
    //     Console.WriteLine(obj.Name);

    // This works because only elements of type X are retrieved by the enumeration
    foreach(X obj in elements.OfType<X>())
       Console.WriteLine(obj.Name);
}
</code>```

Body:
I'm making a game for a school project and I've run into a problem. The teacher requires that I use polymorphism in the code so basically, I have two classes, X and Y and they inherit from the abstract base class K.

I have a list for K objects so that objects of X and Y can be put in the list.
So the problem is that I want to run through the list with a foreach loop but only check the X objects.

foreach ( X object in list)...

The game crashes as soon as an X object is created and I don't understand why!

foreach (GoldCoin gc in powerUps.ToList())
{
    if (gc.IsAlive)
    {
        player.speedY = 3;
    }
    else
    {
        powerUps.Remove(gc);
    }

The error message said

System.InvalidCastException: 'Couldn't convert an object of the class X to the class Y.'

Body:
From your pseudocode, it seems that you are forcing every object in the list to be an object of type X. But if the list contains also objects of type Y then you cannot assign that object to an instance of X

Suppose your class are:

class K
{
    public int value {get;set;}

}

class X : K
{
    public string Name { get; set; }
}
class Y : K
{
    public decimal money { get; set; }
}

void Main()
{
    List<K> elements = new List<K>();
    elements.Add(new X { Name = "Steve" });
    elements.Add(new Y {money = 100});

    // This cannot work, the second element is a Y and doesn't have a Name property
    // foreach(X obj in elements)
    //     Console.WriteLine(obj.Name);

    // This works because only elements of type X are retrieved by the enumeration
    foreach(X obj in elements.OfType<X>())
       Console.WriteLine(obj.Name);
}


问:
How to solve, PermissionError: [Errno 13] Permission denied: 'test.from'
I'm following a tutorial on training data for a chatbot in python. However, whenever I run the code I get this error,

```<code>line 22, in <module>
    with open('test.from','a', encoding='utf8') as f:
PermissionError: [Errno 13] Permission denied: 'test.from'
</code>```

I went to my project folder and changed the permissions for 'staff' and 'everyone'. I made it so that both could read and write. However this did nothing, and I still got the same error.

Below is my code,

```<code>import sqlite3
import pandas as pd

timeframes = ['2015-01']

for timeframe in timeframes:
    connection = sqlite3.connect('/Users/usr/Desktop/fileName/RC_{}.db'.format(timeframe))
    c = connection.cursor()
    limit = 5000
    last_unix = 0
    cur_length = limit
    counter = 0
    test_done = False

    while cur_length == limit:
        df = pd.read_sql("SELECT * FROM parent_reply WHERE unix > {} and parent NOT NULL and score > 0 ORDER BY unix ASC LIMIT {}".format(last_unix,limit),connection)
        last_unix = df.tail(1)['unix'].values[0]
        cur_length = len(df)

        if not test_done:
            with open('test.from','a', encoding='utf8') as f:
                for content in df['parent'].values:
                    f.write(content+'\n')
            with open('test.to','a', encoding='utf8') as f:
                for content in df['comment'].values:
                    f.write(str(content)+'\n')
            test_done = True
</code>```

答:
POssible reasons

The user does not have write access in that directory.

The file is write protected.

The file is in use at another source.

Most probably you dont have write access in that directory so put full path of a directory you have access to and try again.

Body:
I'm following a tutorial on training data for a chatbot in python. However, whenever I run the code I get this error,

line 22, in <module>
    with open('test.from','a', encoding='utf8') as f:
PermissionError: [Errno 13] Permission denied: 'test.from'

I went to my project folder and changed the permissions for 'staff' and 'everyone'. I made it so that both could read and write. However this did nothing, and I still got the same error.

Below is my code,

import sqlite3
import pandas as pd

timeframes = ['2015-01']

for timeframe in timeframes:
    connection = sqlite3.connect('/Users/usr/Desktop/fileName/RC_{}.db'.format(timeframe))
    c = connection.cursor()
    limit = 5000
    last_unix = 0
    cur_length = limit
    counter = 0
    test_done = False

    while cur_length == limit:
        df = pd.read_sql("SELECT * FROM parent_reply WHERE unix > {} and parent NOT NULL and score > 0 ORDER BY unix ASC LIMIT {}".format(last_unix,limit),connection)
        last_unix = df.tail(1)['unix'].values[0]
        cur_length = len(df)

        if not test_done:
            with open('test.from','a', encoding='utf8') as f:
                for content in df['parent'].values:
                    f.write(content+'\n')
            with open('test.to','a', encoding='utf8') as f:
                for content in df['comment'].values:
                    f.write(str(content)+'\n')
            test_done = True


问:
Need help interpreting/converting math formula for javascript
I have a math formula that I need to convert to Javascript readable format.

```<code> const result = (100 × w) / (52.2 + (41.9 × e-0.055 × r))
</code>```

I have no problem with most of it. The part that is holding me up is
     e-0.055

I am assuming that it's referring to Euler's number but am unsure how to get it to work.

I tried:

```<code> const result = (100 * w) / (52.2 + (41.9 * Math.E(-0.055 * r)));
</code>```

but that throws an error.

Another form of the same formula written for some server side language is:
     1 RM = {:frac{100* "w" }{52.2+41.9*e^{-0.055* "r" }}:}

but again, the "e^" part eludes me.

答:
EULER FORMULA

Euler formula, named after Leonhard Euler, is a mathematical formula of the specific area of complex analysis, which shows a relation between trigonometric functions and exponential function (Euler identity is a special case of Euler's formula ). The formula is given by:

euler formula image

AT WHERE

x is the real argument (in radians);

e is the basis of the natural logarithm;

i² = -1, where i is the imaginary unit (complex number)

You are correct, e-0.055 is what you imagined, so knowing this as its formula is static, you can use the following:

a) e-0.055 = 2.66328182846

b) JavaScript E Property

JAVASCRIPT E PROPERTY

The E property returns the Euler's number and the base of natural logarithms, approximately 2.718.

EXAMPLE:

Click the button to display Euler's number.

<button onclick="myFunction()">Try it</button>

```
</div>
</div>
</p>
<p>Complementing, you can use what <strong>@Asleepace</strong> answered you which is correct according to your scenario:</p>
```const result = (100 * w) / (52.2 + (41.9 * Math.E**(-0.055 * r)));
```

OFFICIAL SOURCE - W3SCHOOLS: JAVASCRIPT E PROPERTY

OFFICIAL SOURCE - WIKIPEDIA: EULER FORMULA

Body:
I have a math formula that I need to convert to Javascript readable format.

 const result = (100 × w) / (52.2 + (41.9 × e-0.055 × r))

I have no problem with most of it. The part that is holding me up is
     e-0.055

I am assuming that it's referring to Euler's number but am unsure how to get it to work.

I tried:

 const result = (100 * w) / (52.2 + (41.9 * Math.E(-0.055 * r)));

but that throws an error.

Another form of the same formula written for some server side language is:
     1 RM = {:frac{100* "w" }{52.2+41.9*e^{-0.055* "r" }}:}

but again, the "e^" part eludes me.

Body:
EULER FORMULA

Euler formula, named after Leonhard Euler, is a mathematical formula of the specific area of complex analysis, which shows a relation between trigonometric functions and exponential function (Euler identity is a special case of Euler's formula ). The formula is given by:

euler formula image

AT WHERE

x is the real argument (in radians);

e is the basis of the natural logarithm;

i² = -1, where i is the imaginary unit (complex number)

You are correct, e-0.055 is what you imagined, so knowing this as its formula is static, you can use the following:

a) e-0.055 = 2.66328182846

b) JavaScript E Property

JAVASCRIPT E PROPERTY

The E property returns the Euler's number and the base of natural logarithms, approximately 2.718.

EXAMPLE:

<p>Click the button to display Euler's number.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = Math.E;
}
</script>

Complementing, you can use what @Asleepace answered you which is correct according to your scenario:

const result = (100 * w) / (52.2 + (41.9 * Math.E**(-0.055 * r)));

OFFICIAL SOURCE - W3SCHOOLS: JAVASCRIPT E PROPERTY

OFFICIAL SOURCE - WIKIPEDIA: EULER FORMULA


问:
How to add navigationController to existing tab application?
I have an iPhone application with 2 tabs. This is my application delegate:

```<code> (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
 }
</code>```

My first tab is a subclass of UITableViewController. I would like to push a new view controller when someone clicks on a row of my table. I know that this is done in didSelectRowAtIndexPath like this:

```<code>TableViewDetailViewController *fvController = [[TableViewDetailViewController alloc] initWithNibName:@"TableViewDetailViewController" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:fvController animated:YES];
    [fvController release];
    fvController = nil;
</code>```

My self.navigationController is NIL so nothing gets pushed to the view stack. Where should I create my navigationController, so there would be as little code to change as possible?

答: Instead of setting your TableViewDetailViewController as one of your tabbbars ViewControllers, you should create an UINavigationController for each tab on your tabbar. Then place your TableViewDetailViewController inside the corresponding UINavigationController. self.navigationController will point to a valid UINavigationController in that case.

Body:
I have an iPhone application with 2 tabs. This is my application delegate:

 (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
 }

My first tab is a subclass of UITableViewController. I would like to push a new view controller when someone clicks on a row of my table. I know that this is done in didSelectRowAtIndexPath like this:

TableViewDetailViewController *fvController = [[TableViewDetailViewController alloc] initWithNibName:@"TableViewDetailViewController" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:fvController animated:YES];
    [fvController release];
    fvController = nil;

My self.navigationController is NIL so nothing gets pushed to the view stack. Where should I create my navigationController, so there would be as little code to change as possible?


问:
Centering Buttons With Bootstrap 4
Hi I have this screen:

And it needs to be viewable on phones, tablets and desktops.  Uses BootStrap 4

What I want is a maximum width for each button AND for the buttons to be centered on the screen.

Here is my html/css:

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

<head>
<title>Cacophonator Setup</title>
<meta charset="utf-8">
<meta name="viewport" content="max-width=device-max-width, initial-scale=1">
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<style> a { max-width: 400px; } </style>
</head>

<body>
{{template "navbar"}}

<div class="container">
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/camera" role="button">Camera</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/disk-memory" role="button">Disk & Memory</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/network" role="button">Network</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/wifi-networks" role="button">WiFi Networks</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/speaker" role="button">Speaker Test</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/location" role="button">Location</a>
            </div>
        </div>

</div>

<script src="/static/js/jquery-3.3.1.slim.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>

<script>
    $(document).ready(function(){
        $("#btnBack").hide();
    });
</script>
</code>```

Any help would be much appreciated, thanks.

答:
```<code>.container {
position : absolute;
left : 50%;
top :50%;
transform : translate(-50%,-50%);
}
</code>```

Title: Centering Buttons With Bootstrap 4

Body:
Hi I have this screen:

And it needs to be viewable on phones, tablets and desktops.  Uses BootStrap 4

What I want is a maximum width for each button AND for the buttons to be centered on the screen.

Here is my html/css:

<!DOCTYPE html>

<title>Cacophonator Setup</title>
<meta charset="utf-8">
<meta name="viewport" content="max-width=device-max-width, initial-scale=1">
<link rel="stylesheet" href="/static/css/bootstrap.min.css">

{{template "navbar"}}

                Camera

                Disk & Memory

                Network

                WiFi Networks

                Speaker Test

                Location

Any help would be much appreciated, thanks.


答:
Extracting lines that start and end with a specific character can be done without any regex, use str.startswith and str.endswith methods when iterating through the lines in a file:

```<code>results = []
with open(filepath, 'r') as f:
    for line in f:
        if line.startswith('{') and line.rstrip('\n').endswith('}'):
            results.append(line.rstrip('\n'))
</code>```

Note the .rstrip('\n') is used before .endswith to make sure the final newline does not interfere with the } check at the end of the string.

Title: Python Regex: find all lines that start with '{' and end with '}'

Body:
I am receiving data over a socket, a bunch of JSON strings. However, I receive a set amount of bytes, so sometimes the last of my JSON strings is cut-off. I will typically get the following:

{"pitch":-30.778193,"yaw":-124.63285,"roll":-8.977466}
{"pitch":-30.856342,"yaw":-124.57556,"roll":-7.7220345}
{"pitch":-31.574106,"yaw":-124.65623,"roll":-7.911794}
{"pitch":-30.479567,"yaw":-124.24301,"roll":-8.730827}
{"pitch":-29.30239,"yaw":-123.97949,"roll":-8.134723}
{"pitch":-29.84712,"yaw":-124.584465,"roll":-8.588374}
{"pitch":-31.072054,"yaw":-124.707466,"roll":-8.877062}
{"pitch":-31.493435,"yaw":-124.75457,"roll":-9.019922}
{"pitch":-29.591925,"yaw":-124.960815,"roll":-9.379437}
{"pitch":-29.37105,"yaw":-125.14427,"roll":-9.642341}
{"pitch":-29.483717,"yaw":-125.16528,"roll":-9.687177}
{"pitch":-30.903332,"yaw":-124.603935,"roll":-9.423098}
{"pitch":-30.211857,"yaw":-124.471664,"roll":-9.116135}
{"pitch":-30.837414,"yaw":-125.18984,"roll":-9.824204}
{"pitch":-30.526165,"yaw":-124.85788,"roll":-9.158611}
{"pitch":-30.333513,"yaw":-123.68705,"roll":-7.9481263}
{"pitch":-30.903502,"yaw":-123.78847,"roll":-8.209373}
{"pitch":-31.194769,"yaw":-124.79708,"roll":-8.709783}
{"pitch":-30.816765,"yaw":-125

With Python, I would like to create a string array of the first 18 complete { data... } strings.

Here is what I have tried: cleanData = re.search('{.*}', data) but it seems like this is only giving me the very first { data... } entry. How can I get the full string array of complete { } sets?

Body:
Extracting lines that start and end with a specific character can be done without any regex, use str.startswith and str.endswith methods when iterating through the lines in a file:

results = []
with open(filepath, 'r') as f:
    for line in f:
        if line.startswith('{') and line.rstrip('\n').endswith('}'):
            results.append(line.rstrip('\n'))

Note the .rstrip('\n') is used before .endswith to make sure the final newline does not interfere with the } check at the end of the string.


问:
IF Statement Dependent on Loop
I have the following script:

```<code>import pandas as pd

ls = [
      ['A', 1, 'A1', 9],
      ['A', 1, 'A1', 6],
      ['A', 1, 'A1', 3],
      ['A', 2, 'A2', 7],
      ['A', 3, 'A3', 9],
      ['B', 1, 'B1', 7],
      ['B', 1, 'B1', 3],
      ['B', 2, 'B2', 7],
      ['B', 2, 'B2', 8],
      ['C', 1, 'C1', 9],

      ]

#convert to dataframe
df = pd.DataFrame(ls, columns = ["Main_Group", "Sub_Group", "Concat_GRP_Name", "X_1"])

#get count and sum of concatenated groups
df_sum = df.groupby('Concat_GRP_Name')['X_1'].agg(['sum','count']).reset_index()

#print in permutations formula to calculate different permutation combos
import itertools as it
perms = it.permutations(df_sum.Concat_GRP_Name)

def combute_combinations(df, colname):
    l = []
    import itertools as it
    perms = it.permutations(df[colname])

    for perm_pairs in perms:
        #take in only the first three pairs of permuations and make sure
        #the first column starts with A, secon with B, and third with C
        if 'A' in perm_pairs[0] and 'B' in perm_pairs[1] and 'C' in perm_pairs[2]:
            l.append([perm_pairs[0], perm_pairs[1], perm_pairs[2]])
    return l

#apply function, this will generate a list of all of the permuation pairs
t = combute_combinations(df_sum, 'Concat_GRP_Name' )

#convert to dataframe and drop duplicate pairs
df2 = pd.DataFrame(t, columns = ["Item1", 'Item2', 'Item3']) .drop_duplicates()
</code>```

I am not sure how to combine the components of a loop inside of an IF statement.
From the example above, I knew that I had three different types of the Main_Group variable. Let's say that I didn't know how many unique values existed in the Main_Group column. How do I update the following IF statement to account for this?

```<code>if 'A' in perm_pairs[0] and 'B' in perm_pairs[1] and 'C' in perm_pairs[2]:
                l.append([perm_pairs[0], perm_pairs[1], perm_pairs[2]])
</code>```

I want each of the variable in it's own column. If I have 5 types of main group then I will have perm_pairs[0] to perm_pairs[4] in my IF statement. I was thinking about extracting the values in the Main_Group and turning this into a set. Then I would iterate through each value and use it's length to figure out the IF statement, but so far the logic is not working out. How do I iterate through the set and then update the IF statement?

答:
To make the condition more dynamic, you can refactor your function like this:

```<code>import numpy as np

def combute_combinations(df, colname, main_group_series):
    l = []
    import itertools as it
    perms = it.permutations(df[colname])

    # Provides sorted list of unique values in the Series
    unique_groups = np.unique(main_group_series)

    for perm_pairs in perms:
        #take in only the first three pairs of permuations and make sure
        #the first column starts with A, secon with B, and third with C
        if all([main_group in perm_pairs[ind] for ind, main_group in enumerate(unique_groups)]):
            l.append([perm_pairs[ind] for ind in range(unique_groups.shape[0])])
    return l
</code>```

Then you can just call the function as before, but include the series of the main group column

```<code>t = combute_combinations(df_sum, 'Concat_GRP_Name', df['Main_Group'])
</code>```

Title: IF Statement Dependent on Loop

Body:
I have the following script:

import pandas as pd

ls = [
      ['A', 1, 'A1', 9],
      ['A', 1, 'A1', 6],
      ['A', 1, 'A1', 3],
      ['A', 2, 'A2', 7],
      ['A', 3, 'A3', 9],
      ['B', 1, 'B1', 7],
      ['B', 1, 'B1', 3],
      ['B', 2, 'B2', 7],
      ['B', 2, 'B2', 8],
      ['C', 1, 'C1', 9],

      ]

#convert to dataframe
df = pd.DataFrame(ls, columns = ["Main_Group", "Sub_Group", "Concat_GRP_Name", "X_1"])

#get count and sum of concatenated groups
df_sum = df.groupby('Concat_GRP_Name')['X_1'].agg(['sum','count']).reset_index()

#print in permutations formula to calculate different permutation combos
import itertools as it
perms = it.permutations(df_sum.Concat_GRP_Name)

def combute_combinations(df, colname):
    l = []
    import itertools as it
    perms = it.permutations(df[colname])

    for perm_pairs in perms:
        #take in only the first three pairs of permuations and make sure
        #the first column starts with A, secon with B, and third with C
        if 'A' in perm_pairs[0] and 'B' in perm_pairs[1] and 'C' in perm_pairs[2]:
            l.append([perm_pairs[0], perm_pairs[1], perm_pairs[2]])
    return l

#apply function, this will generate a list of all of the permuation pairs
t = combute_combinations(df_sum, 'Concat_GRP_Name' )

#convert to dataframe and drop duplicate pairs
df2 = pd.DataFrame(t, columns = ["Item1", 'Item2', 'Item3']) .drop_duplicates()

I am not sure how to combine the components of a loop inside of an IF statement.
From the example above, I knew that I had three different types of the Main_Group variable. Let's say that I didn't know how many unique values existed in the Main_Group column. How do I update the following IF statement to account for this?

if 'A' in perm_pairs[0] and 'B' in perm_pairs[1] and 'C' in perm_pairs[2]:
                l.append([perm_pairs[0], perm_pairs[1], perm_pairs[2]])

I want each of the variable in it's own column. If I have 5 types of main group then I will have perm_pairs[0] to perm_pairs[4] in my IF statement. I was thinking about extracting the values in the Main_Group and turning this into a set. Then I would iterate through each value and use it's length to figure out the IF statement, but so far the logic is not working out. How do I iterate through the set and then update the IF statement?

Body:
To make the condition more dynamic, you can refactor your function like this:

import numpy as np

def combute_combinations(df, colname, main_group_series):
    l = []
    import itertools as it
    perms = it.permutations(df[colname])

    # Provides sorted list of unique values in the Series
    unique_groups = np.unique(main_group_series)

    for perm_pairs in perms:
        #take in only the first three pairs of permuations and make sure
        #the first column starts with A, secon with B, and third with C
        if all([main_group in perm_pairs[ind] for ind, main_group in enumerate(unique_groups)]):
            l.append([perm_pairs[ind] for ind in range(unique_groups.shape[0])])
    return l

Then you can just call the function as before, but include the series of the main group column

t = combute_combinations(df_sum, 'Concat_GRP_Name', df['Main_Group'])


问:
Does Typescript set interface properties in the Class Constructor?
In the Typescript documentation on interfaces, under "Class Types," the following example is given:

```<code>interface ClockInterface {
    currentTime: Date;
}

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    constructor(h: number, m: number) { }
}
</code>```

The line immediately below "class Clock..." that begins "currentTime:..." seems to imply that if I do var something = new Clock(), my something variable will have the currentTime attribute accessible on it, i.e. something.currentTime.

This confuses me, because of the following line from the MDN documentation on Javascript Classes:

Instance properties must be defined inside of class methods

The example they give:

```<code>class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
</code>```

The implication is that the following code would be invalid:

```<code>class Rectangle {
  height: 23,
  width: 45,
  constructor(height, width) {
  }
}
</code>```

My confusion: The example code in the Typescript documentation does not assign currentTime in the constructor. Is that step missing from their example, or does their syntax imply that "by the way, properties defined directly on the class are magically given a value, in the constructor?" If that's the case, what happens if you set a given value in the constructor on your own, "manually?"

答:
```<code>class Clock implements ClockInterface {
    currentTime: Date = new Date();
    constructor(h: number, m: number) { }
}
</code>```

The constructor is run and then any properties that are assigned defaults are wired up so currentTime is assigned after the constructor has been called.

This allows syntax like

```<code>class MyClass {
  myProperty = this.myService.serviceProperty;

  constructor(private myService: Myservice) {}
}
</code>```

Marking constructor paramaters as private, protected or public auto assigns them as properties of the class and you don't need to do

```<code>this.property = paramater
</code>```

in the constructor. TypeScript syntax is different that JavaScript but awesome once you get used to it.

Body:
In the Typescript documentation on interfaces, under "Class Types," the following example is given:

interface ClockInterface {
    currentTime: Date;
}

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    constructor(h: number, m: number) { }
}

The line immediately below "class Clock..." that begins "currentTime:..." seems to imply that if I do var something = new Clock(), my something variable will have the currentTime attribute accessible on it, i.e. something.currentTime.

This confuses me, because of the following line from the MDN documentation on Javascript Classes:

Instance properties must be defined inside of class methods

The example they give:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

The implication is that the following code would be invalid:

class Rectangle {
  height: 23,
  width: 45,
  constructor(height, width) {
  }
}

My confusion: The example code in the Typescript documentation does not assign currentTime in the constructor. Is that step missing from their example, or does their syntax imply that "by the way, properties defined directly on the class are magically given a value, in the constructor?" If that's the case, what happens if you set a given value in the constructor on your own, "manually?"

Body:
class Clock implements ClockInterface {
    currentTime: Date = new Date();
    constructor(h: number, m: number) { }
}

The constructor is run and then any properties that are assigned defaults are wired up so currentTime is assigned after the constructor has been called.

This allows syntax like

class MyClass {
  myProperty = this.myService.serviceProperty;

  constructor(private myService: Myservice) {}
}

Marking constructor paramaters as private, protected or public auto assigns them as properties of the class and you don't need to do

this.property = paramater

in the constructor. TypeScript syntax is different that JavaScript but awesome once you get used to it.


问:
Mysql + php with special characters like '(Apostrophe) and " (Quotation mark)
I have been struggling with a small problem for a while. It's been there for years but it's just been an irritating problem and not a serious one, and I have just worked around it. But now I want to find out if anyone can help me. I have done some google'ing but no success.

If I do a form post from a html textarea in a php file like this:

```<code><form action="http://action.com" method="post">
<textarea name="text"><a href="http://google.com">google's site</a></textarea>
</form>
</code>```

and of course there is a submit button and so on.

The value is the problem: google's site The value of the textarea have both "(Quotation mark) and '(Apostrophe).

To save this in a mysql_database I do this:

```<code>$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".$_POST['text']."') ") or die(mysql_error());
</code>```

And now I get the mysql error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's site'' at line 1

答:
Just use prepared statements and you wouldn't have to worry about escaping or sql injection.</p>

```<code>$con = <"Your database connection">;
$input = "What's up?";
$stmt = $con->prepare("insert into `tablename` (`field`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();
</code>```

Body:
I have been struggling with a small problem for a while. It's been there for years but it's just been an irritating problem and not a serious one, and I have just worked around it. But now I want to find out if anyone can help me. I have done some google'ing but no success.

If I do a form post from a html textarea in a php file like this:

<form action="http://action.com" method="post">
<textarea name="text">google's site</textarea>
</form>

and of course there is a submit button and so on.

The value is the problem: google's site The value of the textarea have both "(Quotation mark) and '(Apostrophe).

To save this in a mysql_database I do this:

$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".$_POST['text']."') ") or die(mysql_error());

And now I get the mysql error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's site'' at line 1

Body:
Just use prepared statements and you wouldn't have to worry about escaping or sql injection.

$con = <"Your database connection">;
$input = "What's up?";
$stmt = $con->prepare("insert into `tablename` (`field`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();


问:
Line Passing Through Given Points

I am trying to find the angle of the outer line of the object in the green region of the image as shown in the image above…

For that, I have scanned the green region and get the points (dark blue points as shown in the image)...

As you can see, the points are not making straight line so I can’t find angle easily.

So I think I have to find a middle way and
that is to find the line so that the distance between each point and line remain as minimum as possible.

So how can I find the line so that each point exposes minimum distance to it……?

Is there any algorithm for this or is there any good way other than this?

答:
You might try searching for "total least squares", or "least orthogonal distance" but when I tried that I saw nothing immediately applicable.

Anyway suppose you have points x[],y[], and the line is represented by a*x+b*y+c = 0, where hypot(a,b) = 1. The least orthogonal distance line is the one that minimises Sum{ (a*x[i]+b*y[i]+c)^2}. Some algebra shows that:

c is -(a*X+b*Y) where X is the mean of the x's and Y the mean of the y's.

(a,b) is the eigenvector of C corresponding to it's smaller eigenvalue, where C is the covariance matrix of the x's and y's

Title: Line Passing Through Given Points