问:
Could you make Supertrend line without break
```<code>//@version=4
study("Supertrend1", overlay = true, format=format.price, precision=2, resolution="")

PeriodsA = input(title="ATR Period", type=input.integer, defval=7)
srcA = input(hl2, title="Source")
MultiplierA = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATRA= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignalsA = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlightingA = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2A = sma(tr, PeriodsA)
atrA= changeATRA ? atr(PeriodsA) : atr2A
upA=srcA-(MultiplierA*atrA)
up1A = nz(upA[1],upA)
upA := close[1] > up1A ? max(upA,up1A) : upA
dnA=srcA+(MultiplierA*atrA)
dn1A = nz(dnA[1], dnA)
dnA := close[1] < dn1A ? min(dnA, dn1A) : dnA
trendA = 1
trendA := nz(trendA[1], trendA)
trendA := trendA == -1 and close > dn1A ? 1 : trendA == 1 and close < up1A ? -1 : trendA
upPlotA = plot(trendA == 1 ? upA : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignalA = trendA == 1 and trendA[1] == -1
plotshape(buySignalA ? upA : na, title="Up Arrow", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)

dnPlotA = plot(trendA == 1 ? na : dnA, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignalA = trendA == -1 and trendA[1] == 1
plotshape(sellSignalA ? dnA : na, title="Down Arrow", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)

mPlotA = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColorA = highlightingA ? (trendA == 1 ? color.green : color.white) : color.white
shortFillColorA = highlightingA ? (trendA == -1 ? color.red : color.white) : color.white

plotarrow(buySignalA ? upA : na, title="Up Arrow", colorup=color.green, maxheight=60, minheight=50, transp=0)
plotarrow(sellSignalA ? dnA : na, title="Down Arrow", colorup=color.red, maxheight=60, minheight=50, transp=0)
</code>```

Supertrend line forming with break. If i change style to line from line with break, it connects with previous green line end. I want this to connect with end of red. It should be a continuous line without any break.
Thanks.

Want to make Supertrend line without break like in the picture.

答:
Comment lines 21 and 25, replace them with a single plot() call and include a ternary condition in both series= and color= arguments.

```<code>//@version=4
study("Supertrend1", overlay = true, format=format.price, precision=2, resolution="")

PeriodsA = input(title="ATR Period", type=input.integer, defval=7)
srcA = input(hl2, title="Source")
MultiplierA = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATRA= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignalsA = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlightingA = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2A = sma(tr, PeriodsA)
atrA= changeATRA ? atr(PeriodsA) : atr2A
upA=srcA-(MultiplierA*atrA)
up1A = nz(upA[1],upA)
upA := close[1] > up1A ? max(upA,up1A) : upA
dnA=srcA+(MultiplierA*atrA)
dn1A = nz(dnA[1], dnA)
dnA := close[1] < dn1A ? min(dnA, dn1A) : dnA
trendA = 1
trendA := nz(trendA[1], trendA)
trendA := trendA == -1 and close > dn1A ? 1 : trendA == 1 and close < up1A ? -1 : trendA
// upPlotA = plot(trendA == 1 ? upA : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignalA = trendA == 1 and trendA[1] == -1
plotshape(buySignalA ? upA : na, title="Up Arrow", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)

// dnPlotA = plot(trendA == 1 ? na : dnA, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignalA = trendA == -1 and trendA[1] == 1
plotshape(sellSignalA ? dnA : na, title="Down Arrow", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)

mPlotA = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColorA = highlightingA ? (trendA == 1 ? color.green : color.white) : color.white
shortFillColorA = highlightingA ? (trendA == -1 ? color.red : color.white) : color.white

plotarrow(buySignalA ? upA : na, title="Up Arrow", colorup=color.green, maxheight=60, minheight=50, transp=0)
plotarrow(sellSignalA ? dnA : na, title="Down Arrow", colorup=color.red, maxheight=60, minheight=50, transp=0)

plot(trendA == 1 ? upA : dnA, 'TrendLine', trendA == 1 ? color.green : color.red, 2, plot.style_line)
</code>```

Body:
//@version=4
study("Supertrend1", overlay = true, format=format.price, precision=2, resolution="")

PeriodsA = input(title="ATR Period", type=input.integer, defval=7)
srcA = input(hl2, title="Source")
MultiplierA = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATRA= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignalsA = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlightingA = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2A = sma(tr, PeriodsA)
atrA= changeATRA ? atr(PeriodsA) : atr2A
upA=srcA-(MultiplierA*atrA)
up1A = nz(upA[1],upA)
upA := close[1] > up1A ? max(upA,up1A) : upA
dnA=srcA+(MultiplierA*atrA)
dn1A = nz(dnA[1], dnA)
dnA := close[1] < dn1A ? min(dnA, dn1A) : dnA
trendA = 1
trendA := nz(trendA[1], trendA)
trendA := trendA == -1 and close > dn1A ? 1 : trendA == 1 and close < up1A ? -1 : trendA
upPlotA = plot(trendA == 1 ? upA : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignalA = trendA == 1 and trendA[1] == -1
plotshape(buySignalA ? upA : na, title="Up Arrow", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)

dnPlotA = plot(trendA == 1 ? na : dnA, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignalA = trendA == -1 and trendA[1] == 1
plotshape(sellSignalA ? dnA : na, title="Down Arrow", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)

mPlotA = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColorA = highlightingA ? (trendA == 1 ? color.green : color.white) : color.white
shortFillColorA = highlightingA ? (trendA == -1 ? color.red : color.white) : color.white

plotarrow(buySignalA ? upA : na, title="Up Arrow", colorup=color.green, maxheight=60, minheight=50, transp=0)
plotarrow(sellSignalA ? dnA : na, title="Down Arrow", colorup=color.red, maxheight=60, minheight=50, transp=0)

Supertrend line forming with break. If i change style to line from line with break, it connects with previous green line end. I want this to connect with end of red. It should be a continuous line without any break.
Thanks.

Want to make Supertrend line without break like in the picture.

Body:
Comment lines 21 and 25, replace them with a single plot() call and include a ternary condition in both series= and color= arguments.

//@version=4
study("Supertrend1", overlay = true, format=format.price, precision=2, resolution="")

PeriodsA = input(title="ATR Period", type=input.integer, defval=7)
srcA = input(hl2, title="Source")
MultiplierA = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATRA= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignalsA = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlightingA = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2A = sma(tr, PeriodsA)
atrA= changeATRA ? atr(PeriodsA) : atr2A
upA=srcA-(MultiplierA*atrA)
up1A = nz(upA[1],upA)
upA := close[1] > up1A ? max(upA,up1A) : upA
dnA=srcA+(MultiplierA*atrA)
dn1A = nz(dnA[1], dnA)
dnA := close[1] < dn1A ? min(dnA, dn1A) : dnA
trendA = 1
trendA := nz(trendA[1], trendA)
trendA := trendA == -1 and close > dn1A ? 1 : trendA == 1 and close < up1A ? -1 : trendA
// upPlotA = plot(trendA == 1 ? upA : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignalA = trendA == 1 and trendA[1] == -1
plotshape(buySignalA ? upA : na, title="Up Arrow", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)

// dnPlotA = plot(trendA == 1 ? na : dnA, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignalA = trendA == -1 and trendA[1] == 1
plotshape(sellSignalA ? dnA : na, title="Down Arrow", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)

mPlotA = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColorA = highlightingA ? (trendA == 1 ? color.green : color.white) : color.white
shortFillColorA = highlightingA ? (trendA == -1 ? color.red : color.white) : color.white

plotarrow(buySignalA ? upA : na, title="Up Arrow", colorup=color.green, maxheight=60, minheight=50, transp=0)
plotarrow(sellSignalA ? dnA : na, title="Down Arrow", colorup=color.red, maxheight=60, minheight=50, transp=0)

plot(trendA == 1 ? upA : dnA, 'TrendLine', trendA == 1 ? color.green : color.red, 2, plot.style_line)


来源: stackexchange

问:
IpoptSolver has not been compiled as part of this binary
I have freshly installed drake using pip and while going through tutorials about mathematical programs, I cannot use the example with IpoptSolver. I am getting this error message, however, I cannot find information in the documentation how to compile it. Could you point me to the right direction?

ValueError: IpoptSolver cannot Solve because IpoptSolver::available() is false, i.e., IpoptSolver has not been compiled as part of this binary. Refer to the IpoptSolver class overview documentation for how to compile it.

答:
For the pip install instructions as of today, we see a link to still has some known issues; see issue #15954

Following that, we find a link to Enable IPOPT in pip wheel #15971, an issue which was only resolved 4 hours ago.

So yes, in recent past, the IPOPT solver was not yet shipped in the pip wheels.  However, it will be included as of the v0.39.0 release within the next day or two.  (Edit: Drake v0.39.0 has been released, and has IPOPT available now.)

In the meantime, possibly some other solver like NloptSolver or SnoptSolver would be able to solve the program.

The list of other solvers is here: https://drake.mit.edu/doxygen_cxx/group__solvers.html.

ContentLicense: CC BY-SA 4.0


问:
How to copy a cstring to a member variable in a constructors initializer list?
Instead of doing it this way:

```<code>myClass::myClass(char* name) :
    name(nullptr)
{
this->name = new char[strlen(name) + 1];
    strcpy(this->name, name);
}
</code>```

How can I initialize name completely inside of the initializer list?

答:
The following may be interesting to you.  I wondered what the Joint Strike Fighter (JSF) Air Vehicle C++ Coding Standards document had to say about this, so I checked:

(UNCLASS)

"AV Rule 74:

Initialization of nonstatic class members will be performed through
the member initialization list rather than through assignment in the
body of a constructor. See Meyers [6], item 12.

Exception:

Assignment should be used when an initial value cannot be represented by a
simple expression (e.g. initialization of array values), or when a name must
be introduced before it can be initialized (e.g. value received via an
input stream).

See AV Rule 74 in Appendix A for details."

(/UNCLASS)

Now, the JSF spec is a product of its time-- circa 2005, for the revision I looked at-- but prior to the newer C++ language variants, this was the best thinking on the matter.  (The Meyers reference in question is "Effective C++", for example.)

While the newer language standards provide more options, it can be kind of infuriating getting people who really know those specs to listen to you when you ask how they apply to non-"std::*" types, and more often than not you're talking about C-style, null-terminated strings.  Their response tends to be, "don't do that".

Unfortunately, in the embedded systems world and a number of other places, std::array, std::string, etc., still suffer from significant to severe performance problems with any number of vendor-specific toolchains, and occasionally having no choice but to attempt to find a compromise that uses modern C++ best practices on older C data types is something that, as of 2022, absolutely still occurs.

For my own C-string uses cases, I typically use the initializer list to zero the entire target array, and then strncpy (note the N!) in the function body.  This is because I often have to go to a little extra trouble to make sure all the memory I'm using is thoroughly scrubbed.

(I'll also mention that if you REALLY have to make sure of that, there are replacement memory management libraries that are truly paranoid about it, but you can pay a pretty significant performance penalty, so it's better to learn how to get what you want from your code in the first place.  They can, however, sometimes be a decent solution to help shore up ancient codebases you don't have time to retrofit.)

ContentLicense: CC BY-SA 3.0

Body:
Instead of doing it this way:

myClass::myClass(char* name) :
    name(nullptr)
{
this->name = new char[strlen(name) + 1];
    strcpy(this->name, name);
}

How can I initialize name completely inside of the initializer list?


问:
What is the point of salt and hashing if database is accessible?
I just learned the concept of hashing ("Hey! don't forget the salt!") and using salt to make the password secured.

Hashing it is a one way encryption (actually not encryption but hashing) so it cannot be reversed engineered. Salting is prefixing or appending randomly created values to the password before hashing 'coz the problem in hashing (just hashing) is, some genius has provided a hash table of words from the dictionary so that they'll just compare the hash from that dictionary to the user's table from the database to login - W-wait? did I say table from the database? So it means somebody can access the database so we have to use salt? If that so, then why would the hacker recover the password if he already has access to the database? If I were him, I'll just get all the details I want from the database, why would I use the key I've stolen from a house to open the door if I can access the house already through the window?

So, why hash? why salt? I don't understand. Please, somebody help me.

Thanks in advance.

Important Note: I'm not against hashing or salting, I just want to clarify things.

答:
If that so, then why would the hacker recover the password if he already has access to the database?

Reasons are many. Here are a few:

People reuse their passwords, so not leaking everybodys real passwords does limit the impact of such attack.

Without the real passwords, the hacker will still not be able to log in and, say, post new entries on the hacked system.

Who says all information is stored in the database? What if the database solely consisted of the user name and hashed/salted passwords? Then, knowing the content doesn't help much.


问:
Painting cells using pandas and complex conditions
I have a data frame that contains the std, mean and median for several chemical elements. Sample data:

```<code>test = pd.DataFrame({('Na', 'std'):{'A': 1.73, 'B':0.95, 'C':2.95}, ('Na', 'mean'):{'A': 10.3, 'B':11, 'C':20}, ('Na', 'median'):{'A':11, 'B':22, 'C':34},('K', 'std'):{'A': 1.33, 'B':1.95, 'C':2.66}, ('K', 'mean'):{'A': 220.3, 'B':121, 'C':290}, ('K', 'median'):{'A':211, 'B':122, 'C':340}})
</code>```

Example of table:

```<code>    Na                  K
    std     mean    med std     mean    med
A   1.73    10.3    11  1.33    220.3   211
B   0.95    11.0    22  1.95    121.0   122
C   2.95    20.0    34  2.66    290.0   340
</code>```

I want to paint the cells following certain conditions:

I would like to color the two smallest values in the std column for each chemical element (Example: 0.95 and 1.73 for Na, and 1.33 and 1.95 for K);

I would like to color the mean and median columns based on the two smallest values of the function [abs(mean - median)], for all the elements (Example: (10.3, 11) and (11.0, 22) for Na, and (220.3, 211) and (121, 122) for K).

I made these functions to identify the values of cells to be painted following the conditions I want, but I don't know how to implement them in the pd.style function.

```<code>def paint1(test):
  val_keep = []
  for element,stats in test:
    if stats == 'std':
      paint1 = test[element].nsmallest(2, 'std')
      for value in paint1['std']:
        val_keep.append(value)
  return val_keep

def paint2(test):
val_keep = []
  for element,stats in test:
    if stats == 'mean':
      diff = abs(test[element]['mean'] - test[element]['median'])
      paint2 = diff.nsmallest(2).index
      for value in paint2:
        val_keep.append((test[element]['mean'][value]))
        val_keep.append(test[element]['median'][value])
  return val_keep
</code>```

How can I paint the cells using these conditions? I saw other posts using lambda functions to define the styling, but I think the functions I need are more complicated than that.

答:
Use df.style:

def styler(col):
    chem, stat = col.name
    if stat == 'std':
        return np.where(col.isin(col.nsmallest(2)), 'color: red', '')
    elif stat in ['mean', 'median']:
        delta = (df[(chem, 'mean')] - df[(chem, 'median')]).abs()
        return np.where(delta.isin(delta.nsmallest(2)), 'color: blue', '')
    else:
        return [''] * len(col)

df.style.apply(styler)
```

Body:
I have a data frame that contains the std, mean and median for several chemical elements. Sample data:

test = pd.DataFrame({('Na', 'std'):{'A': 1.73, 'B':0.95, 'C':2.95}, ('Na', 'mean'):{'A': 10.3, 'B':11, 'C':20}, ('Na', 'median'):{'A':11, 'B':22, 'C':34},('K', 'std'):{'A': 1.33, 'B':1.95, 'C':2.66}, ('K', 'mean'):{'A': 220.3, 'B':121, 'C':290}, ('K', 'median'):{'A':211, 'B':122, 'C':340}})

Example of table:

    Na                  K
    std     mean    med std     mean    med
A   1.73    10.3    11  1.33    220.3   211
B   0.95    11.0    22  1.95    121.0   122
C   2.95    20.0    34  2.66    290.0   340

I want to paint the cells following certain conditions:

I would like to color the two smallest values in the std column for each chemical element (Example: 0.95 and 1.73 for Na, and 1.33 and 1.95 for K);

I would like to color the mean and median columns based on the two smallest values of the function [abs(mean - median)], for all the elements (Example: (10.3, 11) and (11.0, 22) for Na, and (220.3, 211) and (121, 122) for K).

I made these functions to identify the values of cells to be painted following the conditions I want, but I don't know how to implement them in the pd.style function.

def paint1(test):
  val_keep = []
  for element,stats in test:
    if stats == 'std':
      paint1 = test[element].nsmallest(2, 'std')
      for value in paint1['std']:
        val_keep.append(value)
  return val_keep

def paint2(test):
val_keep = []
  for element,stats in test:
    if stats == 'mean':
      diff = abs(test[element]['mean'] - test[element]['median'])
      paint2 = diff.nsmallest(2).index
      for value in paint2:
        val_keep.append((test[element]['mean'][value]))
        val_keep.append(test[element]['median'][value])
  return val_keep

How can I paint the cells using these conditions? I saw other posts using lambda functions to define the styling, but I think the functions I need are more complicated than that.


问:
Convert pine script version 2 to version 4
How to convert pine version 2 to version 4? I don't have even basic knowledge about pine. I tried this by watching pine script. But I don't understand version 4.</p>
```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © imani45

//@version=2
study("PRS Supertrend", overlay = true)

//SUPER TREND INPUT

Factor1=input(3, minval=1,maxval = 100)
Factor2=input(2, minval=1,maxval = 100)
Factor3=input(1, minval=1,maxval = 100)

Pd1=input(7, minval=1,maxval = 100)
Pd2=input(14, minval=1,maxval = 100)
Pd3=input(21, minval=1,maxval = 100)

Up1=hl2-(Factor1*atr(Pd1))
Up2=hl2-(Factor2*atr(Pd2))
Up3=hl2-(Factor3*atr(Pd3))
Dn1=hl2+(Factor1*atr(Pd1))
Dn2=hl2+(Factor2*atr(Pd2))
Dn3=hl2+(Factor3*atr(Pd3))

TrendUp1=close[1]>TrendUp1[1]? max(Up1,TrendUp1[1]) : Up1
TrendUp2=close[1]>TrendUp2[1]? max(Up2,TrendUp2[1]) : Up2
TrendUp3=close[1]>TrendUp3[1]? max(Up3,TrendUp3[1]) : Up3

TrendDown1=close[1]<TrendDown1[1]? min(Dn1,TrendDown1[1]) : Dn1
TrendDown2=close[1]<TrendDown2[1]? min(Dn2,TrendDown2[1]) : Dn2
TrendDown3=close[1]<TrendDown3[1]? min(Dn3,TrendDown3[1]) : Dn3

Trend1 = close > TrendDown1[1] ? 1: close< TrendUp1[1]? -1: nz(Trend1[1],1)
Trend2 = close > TrendDown2[1] ? 1: close< TrendUp2[1]? -1: nz(Trend2[1],1)
Trend3 = close > TrendDown3[1] ? 1: close< TrendUp3[1]? -1: nz(Trend3[1],1)

Tsl1 = Trend1==1? TrendUp1: TrendDown1
Tsl2 = Trend2==1? TrendUp2: TrendDown2
Tsl3 = Trend3==1? TrendUp3: TrendDown3

linecolor1 = Trend1 == 1 ? green : red
linecolor2 = Trend2 == 1 ? green : red
linecolor3 = Trend3 == 1 ? green : red

plot(Tsl1, color = linecolor1 , style = line , linewidth = 2,title = "SuperTrend1")
plot(Tsl2, color = linecolor2 , style = line , linewidth = 2,title = "SuperTrend2")
plot(Tsl3, color = linecolor3 , style = line , linewidth = 2,title = "SuperTrend3")

plotshape(cross(close,Tsl1) and close>Tsl1 , "Up Arrow", shape.triangleup,location.belowbar,green,0,0)
plotshape(cross(Tsl1,close) and close<Tsl1 , "Down Arrow", shape.triangledown , location.abovebar, red,0,0)
//plot(Trend==1 and Trend[1]==-1,color = linecolor, style = circles, linewidth = 3,title="Trend")

plotarrow(Trend1 == 1 and Trend1[1] == -1 ? Trend1 : na, title="Up Entry Arrow", colorup=lime, maxheight=60, minheight=50, transp=0)
plotarrow(Trend1 == -1 and Trend1[1] == 1 ? Trend1 : na, title="Down Entry Arrow", colordown=red, maxheight=60, minheight=50, transp=0)
</code>```

答:
For future reference - if you just change the //@version=2 to //@version=5 and try to run the script, most of the changes needed will be written in the console.

Here is the code for version 5:

```<code>//@version=5
indicator("PRS Supertrend", overlay = true)

//SUPER TREND INPUT

Factor1=input.int(3, minval=1,maxval = 100)
Factor2=input.int(2, minval=1,maxval = 100)
Factor3=input.int(1, minval=1,maxval = 100)

Pd1=input.int(7, minval=1,maxval = 100)
Pd2=input.int(14, minval=1,maxval = 100)
Pd3=input.int(21, minval=1,maxval = 100)

Up1=hl2-(Factor1*ta.atr(Pd1))
Up2=hl2-(Factor2*ta.atr(Pd2))
Up3=hl2-(Factor3*ta.atr(Pd3))
Dn1=hl2+(Factor1*ta.atr(Pd1))
Dn2=hl2+(Factor2*ta.atr(Pd2))
Dn3=hl2+(Factor3*ta.atr(Pd3))

TrendUp1 = float(na)
TrendUp2 = float(na)
TrendUp3 = float(na)

TrendUp1 := close[1]>TrendUp1[1]? math.max(Up1,TrendUp1[1]) : Up1
TrendUp2 := close[1]>TrendUp2[1]? math.max(Up2,TrendUp2[1]) : Up2
TrendUp3 := close[1]>TrendUp3[1]? math.max(Up3,TrendUp3[1]) : Up3

TrendDown1 = float(na)
TrendDown2 = float(na)
TrendDown3 = float(na)

TrendDown1 := close[1]<TrendDown1[1]? math.min(Dn1,TrendDown1[1]) : Dn1
TrendDown2 := close[1]<TrendDown2[1]? math.min(Dn2,TrendDown2[1]) : Dn2
TrendDown3 := close[1]<TrendDown3[1]? math.min(Dn3,TrendDown3[1]) : Dn3

Trend1 = float(na)
Trend2 = float(na)
Trend3 = float(na)

Trend1 := close > TrendDown1[1] ? 1: close< TrendUp1[1]? -1: nz(Trend1[1],1)
Trend2 := close > TrendDown2[1] ? 1: close< TrendUp2[1]? -1: nz(Trend2[1],1)
Trend3 := close > TrendDown3[1] ? 1: close< TrendUp3[1]? -1: nz(Trend3[1],1)

Tsl1 = Trend1==1? TrendUp1: TrendDown1
Tsl2 = Trend2==1? TrendUp2: TrendDown2
Tsl3 = Trend3==1? TrendUp3: TrendDown3

linecolor1 = Trend1 == 1 ? color.green : color.red
linecolor2 = Trend2 == 1 ? color.green : color.red
linecolor3 = Trend3 == 1 ? color.green : color.red

plot(Tsl1, color = linecolor1 , style = plot.style_line , linewidth = 2,title = "SuperTrend1")
plot(Tsl2, color = linecolor2 , style = plot.style_line , linewidth = 2,title = "SuperTrend2")
plot(Tsl3, color = linecolor3 , style = plot.style_line , linewidth = 2,title = "SuperTrend3")

plotshape(ta.cross(close,Tsl1) and close>Tsl1 , "Up Arrow", shape.triangleup,location.belowbar,color.green)
plotshape(ta.cross(Tsl1,close) and close<Tsl1 , "Down Arrow", shape.triangledown , location.abovebar, color.red)

plotarrow(Trend1 == 1 and Trend1[1] == -1 ? Trend1 : na, title="Up Entry Arrow", colorup=color.new(color.lime, 0), maxheight=60, minheight=50)
plotarrow(Trend1 == -1 and Trend1[1] == 1 ? Trend1 : na, title="Down Entry Arrow", colordown=color.new(color.red, 0), maxheight=60, minheight=50)
</code>```

Body:
How to convert pine version 2 to version 4? I don't have even basic knowledge about pine. I tried this by watching pine script. But I don't understand version 4.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © imani45

//@version=2
study("PRS Supertrend", overlay = true)

//SUPER TREND INPUT

Factor1=input(3, minval=1,maxval = 100)
Factor2=input(2, minval=1,maxval = 100)
Factor3=input(1, minval=1,maxval = 100)

Pd1=input(7, minval=1,maxval = 100)
Pd2=input(14, minval=1,maxval = 100)
Pd3=input(21, minval=1,maxval = 100)

Up1=hl2-(Factor1*atr(Pd1))
Up2=hl2-(Factor2*atr(Pd2))
Up3=hl2-(Factor3*atr(Pd3))
Dn1=hl2+(Factor1*atr(Pd1))
Dn2=hl2+(Factor2*atr(Pd2))
Dn3=hl2+(Factor3*atr(Pd3))

TrendUp1=close[1]>TrendUp1[1]? max(Up1,TrendUp1[1]) : Up1
TrendUp2=close[1]>TrendUp2[1]? max(Up2,TrendUp2[1]) : Up2
TrendUp3=close[1]>TrendUp3[1]? max(Up3,TrendUp3[1]) : Up3

TrendDown1=close[1]<TrendDown1[1]? min(Dn1,TrendDown1[1]) : Dn1
TrendDown2=close[1]<TrendDown2[1]? min(Dn2,TrendDown2[1]) : Dn2
TrendDown3=close[1]<TrendDown3[1]? min(Dn3,TrendDown3[1]) : Dn3

Trend1 = close > TrendDown1[1] ? 1: close< TrendUp1[1]? -1: nz(Trend1[1],1)
Trend2 = close > TrendDown2[1] ? 1: close< TrendUp2[1]? -1: nz(Trend2[1],1)
Trend3 = close > TrendDown3[1] ? 1: close< TrendUp3[1]? -1: nz(Trend3[1],1)

Tsl1 = Trend1==1? TrendUp1: TrendDown1
Tsl2 = Trend2==1? TrendUp2: TrendDown2
Tsl3 = Trend3==1? TrendUp3: TrendDown3

linecolor1 = Trend1 == 1 ? green : red
linecolor2 = Trend2 == 1 ? green : red
linecolor3 = Trend3 == 1 ? green : red

plot(Tsl1, color = linecolor1 , style = line , linewidth = 2,title = "SuperTrend1")
plot(Tsl2, color = linecolor2 , style = line , linewidth = 2,title = "SuperTrend2")
plot(Tsl3, color = linecolor3 , style = line , linewidth = 2,title = "SuperTrend3")

plotshape(cross(close,Tsl1) and close>Tsl1 , "Up Arrow", shape.triangleup,location.belowbar,green,0,0)
plotshape(cross(Tsl1,close) and close<Tsl1 , "Down Arrow", shape.triangledown , location.abovebar, red,0,0)
//plot(Trend==1 and Trend[1]==-1,color = linecolor, style = circles, linewidth = 3,title="Trend")

plotarrow(Trend1 == 1 and Trend1[1] == -1 ? Trend1 : na, title="Up Entry Arrow", colorup=lime, maxheight=60, minheight=50, transp=0)
plotarrow(Trend1 == -1 and Trend1[1] == 1 ? Trend1 : na, title="Down Entry Arrow", colordown=red, maxheight=60, minheight=50, transp=0)

Body:
For future reference - if you just change the //@version=2 to //@version=5 and try to run the script, most of the changes needed will be written in the console.

Here is the code for version 5:

//@version=5
indicator("PRS Supertrend", overlay = true)

//SUPER TREND INPUT

Factor1=input.int(3, minval=1,maxval = 100)
Factor2=input.int(2, minval=1,maxval = 100)
Factor3=input.int(1, minval=1,maxval = 100)

Pd1=input.int(7, minval=1,maxval = 100)
Pd2=input.int(14, minval=1,maxval = 100)
Pd3=input.int(21, minval=1,maxval = 100)

Up1=hl2-(Factor1*ta.atr(Pd1))
Up2=hl2-(Factor2*ta.atr(Pd2))
Up3=hl2-(Factor3*ta.atr(Pd3))
Dn1=hl2+(Factor1*ta.atr(Pd1))
Dn2=hl2+(Factor2*ta.atr(Pd2))
Dn3=hl2+(Factor3*ta.atr(Pd3))

TrendUp1 = float(na)
TrendUp2 = float(na)
TrendUp3 = float(na)

TrendUp1 := close[1]>TrendUp1[1]? math.max(Up1,TrendUp1[1]) : Up1
TrendUp2 := close[1]>TrendUp2[1]? math.max(Up2,TrendUp2[1]) : Up2
TrendUp3 := close[1]>TrendUp3[1]? math.max(Up3,TrendUp3[1]) : Up3

TrendDown1 = float(na)
TrendDown2 = float(na)
TrendDown3 = float(na)

TrendDown1 := close[1]<TrendDown1[1]? math.min(Dn1,TrendDown1[1]) : Dn1
TrendDown2 := close[1]<TrendDown2[1]? math.min(Dn2,TrendDown2[1]) : Dn2
TrendDown3 := close[1]<TrendDown3[1]? math.min(Dn3,TrendDown3[1]) : Dn3

Trend1 = float(na)
Trend2 = float(na)
Trend3 = float(na)

Trend1 := close > TrendDown1[1] ? 1: close< TrendUp1[1]? -1: nz(Trend1[1],1)
Trend2 := close > TrendDown2[1] ? 1: close< TrendUp2[1]? -1: nz(Trend2[1],1)
Trend3 := close > TrendDown3[1] ? 1: close< TrendUp3[1]? -1: nz(Trend3[1],1)

Tsl1 = Trend1==1? TrendUp1: TrendDown1
Tsl2 = Trend2==1? TrendUp2: TrendDown2
Tsl3 = Trend3==1? TrendUp3: TrendDown3

linecolor1 = Trend1 == 1 ? color.green : color.red
linecolor2 = Trend2 == 1 ? color.green : color.red
linecolor3 = Trend3 == 1 ? color.green : color.red

plot(Tsl1, color = linecolor1 , style = plot.style_line , linewidth = 2,title = "SuperTrend1")
plot(Tsl2, color = linecolor2 , style = plot.style_line , linewidth = 2,title = "SuperTrend2")
plot(Tsl3, color = linecolor3 , style = plot.style_line , linewidth = 2,title = "SuperTrend3")

plotshape(ta.cross(close,Tsl1) and close>Tsl1 , "Up Arrow", shape.triangleup,location.belowbar,color.green)
plotshape(ta.cross(Tsl1,close) and close<Tsl1 , "Down Arrow", shape.triangledown , location.abovebar, color.red)

plotarrow(Trend1 == 1 and Trend1[1] == -1 ? Trend1 : na, title="Up Entry Arrow", colorup=color.new(color.lime, 0), maxheight=60, minheight=50)
plotarrow(Trend1 == -1 and Trend1[1] == 1 ? Trend1 : na, title="Down Entry Arrow", colordown=color.new(color.red, 0), maxheight=60, minheight=50)


问:
laravel 6 csrf token expired in every 60 seconds?
I am using laravel 6.I Want my laravel CSRF Token expire in every 60 seconds.

config/session

'lifetime' => 60,

答:
First of All, CSRF is stored in XSRF-TOKEN cookie. Ref: 50904763

According to the question (Ref: 51615122), We change the configuration in app/Http/Middleware/VerifyCsrfToken.php by adding a new method named addCookieToResponse

```<code>use Symfony\Component\HttpFoundation\Cookie;

public function addCookieToResponse($request, $response) {
    $config = config('session');
    $session_life = env('CSRF_LIFE');

    $response->headers->setCookie(
        new Cookie(
            'XSRF-TOKEN', $request->session()->token(), $this->availableAt($session_life),
            $config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
        )
    );
}
</code>```

where $config is used to get session information from existing lifetime. However, I parse $session_life from .env to make sure you can customize as much as you can.

So, the result is simple, configure everything as belongs but in area $this->availableAt($session_life) where session_life is in seconds.

So, please set session_life to 60 in .env as below:

```<code>CSRF_LIFE="60"
</code>```

After you save and refresh your page, or clean cache and configs, Session LifeTime will be two hours but CSRF will be only 60 secs.

Hope this works.

Body:
First of All, CSRF is stored in XSRF-TOKEN cookie. Ref: 50904763

According to the question (Ref: 51615122), We change the configuration in app/Http/Middleware/VerifyCsrfToken.php by adding a new method named addCookieToResponse

use Symfony\Component\HttpFoundation\Cookie;

public function addCookieToResponse($request, $response) {
    $config = config('session');
    $session_life = env('CSRF_LIFE');

    $response->headers->setCookie(
        new Cookie(
            'XSRF-TOKEN', $request->session()->token(), $this->availableAt($session_life),
            $config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
        )
    );
}

where $config is used to get session information from existing lifetime. However, I parse $session_life from .env to make sure you can customize as much as you can.

So, the result is simple, configure everything as belongs but in area $this->availableAt($session_life) where session_life is in seconds.

So, please set session_life to 60 in .env as below:

CSRF_LIFE="60"

After you save and refresh your page, or clean cache and configs, Session LifeTime will be two hours but CSRF will be only 60 secs.

Hope this works.


问:
How to sort the date in dd-mm-yyyy format in c++
Suggest way to store and sort in c++.

input:

```<code>01-02-2022
15-01-2022
20-10-2021
25-12-2022
</code>```

答:
Slightly based off Andrey Semashev 's answer, you could parse and then store the date into a struct with a constructor taking a string input and having a less than operator for sorting, like so:</p>
```<code>#include <algorithm> // for std::less
#include <string>
#include <tuple>     // for std::tie
#include <vector>

struct date
{
    unsigned int y, m, d;

    date(const std::string& date_str) : y(0), m(0), d(0)
    {
        if (std::sscanf(date_str.c_str(), "%u-%u-%u", &d, &m, &y) != 3)
            throw std::invalid_argument("Date is in invalid format: " + date_str);
    }

    friend bool operator< (const date& lhs, const date& rhs)
    {
        // Check years first, then months, then days
        return std::tie(lhs.y, lhs.m, lhs.d) < std::tie(rhs.y, rhs.m, rhs.d);
    }
};

void sort_dates(std::vector< std::string >& dates)
{
    // Requires an implicit constructor.
    // A lambda would be simple to write as an alternative.
    std::sort(dates.begin(), dates.end(), std::less<date>{});
}
</code>```

Body:
Suggest way to store and sort in c++.

input:

01-02-2022
15-01-2022
20-10-2021
25-12-2022

Body:
Slightly based off Andrey Semashev 's answer, you could parse and then store the date into a struct with a constructor taking a string input and having a less than operator for sorting, like so:

#include <algorithm> // for std::less
#include <string>
#include <tuple>     // for std::tie
#include <vector>

struct date
{
    unsigned int y, m, d;

    date(const std::string& date_str) : y(0), m(0), d(0)
    {
        if (std::sscanf(date_str.c_str(), "%u-%u-%u", &d, &m, &y) != 3)
            throw std::invalid_argument("Date is in invalid format: " + date_str);
    }

    friend bool operator< (const date& lhs, const date& rhs)
    {
        // Check years first, then months, then days
        return std::tie(lhs.y, lhs.m, lhs.d) < std::tie(rhs.y, rhs.m, rhs.d);
    }
};

void sort_dates(std::vector< std::string >& dates)
{
    // Requires an implicit constructor.
    // A lambda would be simple to write as an alternative.
    std::sort(dates.begin(), dates.end(), std::less<date>{});
}


问:
Create One Calendar Event for Recordset range
I'm trying to figure out how to add a loop that will only create one Outlook calendar event per Markdown End Date.

In my Table Pack Number 6772457 has a shared Markdown End Date date between all my Brand Offers of 2/9/2022 8AM. I'd like to find a way to create only one Entry for all these Brand Offers.

Logically, I'm having an issue figuring out how I would do a loop that would see Multiple Pack numbers on different dates and create event.

Note: The recordset could have multiple pack numbers with different dates and I want to try to make it so each pack number with a date gets a calendar event.
My current code is below.

Any thoughts or push in the right direction would be greatly appreciated!

Pack_Number
Brand Offer
Markdown End Date

6772457
W6
2/9/2022 8:00:00 AM

6772457
V6
2/9/2022 8:00:00 AM

6772457
S6
2/9/2022 8:00:00 AM

6772457
R6
2/9/2022 8:00:00 AM

6772457
P6
2/9/2022 8:00:00 AM

```<code>Private Sub Process_InSeason_Click()
Dim olobj As Outlook.Application
Dim oloappt As Outlook.AppointmentItem
Dim myOptionalAttendee As Outlook.Recipient
Dim PackNum As String
Dim rs As Dao.Recordset

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Define objects
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Appt = [Forms]![In Season MD Tracking]![InS_tbl_Original].[Form]![Markdown End Date].Value
Appt = DateSerial(Year(Appt), Month(Appt), Day(Appt))
Appt = Appt + TimeSerial(8, 0, 0)

PackNum = [Forms]![In Season MD Tracking]![InS_tbl_Original].[Form]![Pack_Number].Value

Set rs = CurrentDb.OpenRecordset("InS_tbl_Original")
Set olobj = CreateObject("Outlook.Application")
Set oloappt = olobj.CreateItem(olAppointmentItem)
Set myOptionalAttendee = oloappt.Recipients.Add("")
myOptionalAttendee.Type = olOptional

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Save records and turn on Error Control
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'DoCmd.RunCommand acCmdSaveRecord
On Error GoTo Add_Err

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Validate if Markdown End date is future date
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rs.Fields("Markdown End Date").Value > Date Then

With oloappt
        .RequiredAttendees = myOptionalAttendee
        .Subject = "InSeason TEST" 'PackNum & " TEST"
        '.Body =
        .MeetingStatus = 1
        .ResponseRequested = True
        .Start = Appt
        .Duration = 10
        .ReminderSet = True
        .ReminderMinutesBeforeStart = 1440
        .Save
        '.Display
        .Send
        .Close (olSave)
End With
DoCmd.RunCommand acCmdSaveRecord
MsgBox "Appointment Added!"

Else 'do nothing
End If

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'End process and clean up
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Set oloappt = Nothing
Set olobj = Nothing

Exit Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Error validation
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Add_Err:
MsgBox "oops error found " & Err.Number & vbCrLf & Err.Description
Exit Sub

End Sub
</code>```

答: I figured it out. In order to make this work I created a query off my table that will remove duplicate pack Numbers. From there I created a look through the records of the query. I want to leave this code active though for anyone who is trying to setup an outlook event through Access. Hopefully this helps!</p>

Body:
I'm trying to figure out how to add a loop that will only create one Outlook calendar event per Markdown End Date.

In my Table Pack Number 6772457 has a shared Markdown End Date date between all my Brand Offers of 2/9/2022 8AM. I'd like to find a way to create only one Entry for all these Brand Offers.

Logically, I'm having an issue figuring out how I would do a loop that would see Multiple Pack numbers on different dates and create event.

Note: The recordset could have multiple pack numbers with different dates and I want to try to make it so each pack number with a date gets a calendar event.
My current code is below.

Any thoughts or push in the right direction would be greatly appreciated!

Pack_Number
Brand Offer
Markdown End Date

6772457
W6
2/9/2022 8:00:00 AM

6772457
V6
2/9/2022 8:00:00 AM

6772457
S6
2/9/2022 8:00:00 AM

6772457
R6
2/9/2022 8:00:00 AM

6772457
P6
2/9/2022 8:00:00 AM

Private Sub Process_InSeason_Click()
Dim olobj As Outlook.Application
Dim oloappt As Outlook.AppointmentItem
Dim myOptionalAttendee As Outlook.Recipient
Dim PackNum As String
Dim rs As Dao.Recordset

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Define objects
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Appt = [Forms]![In Season MD Tracking]![InS_tbl_Original].[Form]![Markdown End Date].Value
Appt = DateSerial(Year(Appt), Month(Appt), Day(Appt))
Appt = Appt + TimeSerial(8, 0, 0)

PackNum = [Forms]![In Season MD Tracking]![InS_tbl_Original].[Form]![Pack_Number].Value

Set rs = CurrentDb.OpenRecordset("InS_tbl_Original")
Set olobj = CreateObject("Outlook.Application")
Set oloappt = olobj.CreateItem(olAppointmentItem)
Set myOptionalAttendee = oloappt.Recipients.Add("")
myOptionalAttendee.Type = olOptional

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Save records and turn on Error Control
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'DoCmd.RunCommand acCmdSaveRecord
On Error GoTo Add_Err

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Validate if Markdown End date is future date
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rs.Fields("Markdown End Date").Value > Date Then

With oloappt
        .RequiredAttendees = myOptionalAttendee
        .Subject = "InSeason TEST" 'PackNum & " TEST"
        '.Body =
        .MeetingStatus = 1
        .ResponseRequested = True
        .Start = Appt
        .Duration = 10
        .ReminderSet = True
        .ReminderMinutesBeforeStart = 1440
        .Save
        '.Display
        .Send
        .Close (olSave)
End With
DoCmd.RunCommand acCmdSaveRecord
MsgBox "Appointment Added!"

Else 'do nothing
End If

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'End process and clean up
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Set oloappt = Nothing
Set olobj = Nothing

Exit Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Error validation
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Add_Err:
MsgBox "oops error found " & Err.Number & vbCrLf & Err.Description
Exit Sub

End Sub


问:
Reduce custom object using RxJava
I'm using RxJava, I have a list of Point and i want to calculate the distance between each point and get the sum.

The point class look like this

```<code>public class Point {
    public double x;
    public double y;
}
</code>```

So i need to map and reduce at same time, but i didn't found a solution.

```<code>public Observable<Double> totalDistance(Observable<List<Point>> obs) {
 return obs.reduceMap(new ArrayList<Integer>, (list, pointA, pointB) -> distance(pointA, pointB)). ?
}
</code>```

What its the most efficient way to do it (or at least a solution that works) ? Which operator should i use ?

To give a more concrete example, here is what I have and what I want:

```<code>Point a (45, 32)
Point b (56, 75)
Point c (44, 53)
Point d (42, 54)
Point e (42, 55)

a to b = 10m
b to c = 15m
c to d = 25m
d to e = 10m

Result = 60m
</code>```

In reality my points are GPS positions and I use the haversine formula to calculate the distance between two positions.

I use observables because the list of points to be calculated is updated sometime. In fact every x points the user has reached, I have an instruction to send. After sending the instruction, a new list of points until the next instruction is emit.

答:
You can try buffer and reduce operators. For example:</p>
```<code>public Observable<Double> totalDistance(Observable<List<Point>> obs) {
    return obs.flatMap(points ->
            Observable.fromIterable(points)
                    .buffer(2 /* count */, 1 /* skip */)
                    /* this emits a list of each two adjacent points from a given list of points. */
                    .reduce(0.0  /* initial value */, (totalDistance, twoPoints) -> {
                                // note: calculation may be skipped if the twoPoints list contains less than
                                // two elements.
                                final Point pointA = twoPoints.get(0);
                                final Point pointB = twoPoints.get(1);
                                return totalDistance + distance(pointA, pointB);
                            }
                    ).toObservable());
}
</code>```

Title: Reduce custom object using RxJava

Body:
I'm using RxJava, I have a list of Point and i want to calculate the distance between each point and get the sum.

The point class look like this

public class Point {
    public double x;
    public double y;
}

So i need to map and reduce at same time, but i didn't found a solution.

public Observable<Double> totalDistance(Observable<List<Point>> obs) {
 return obs.reduceMap(new ArrayList<Integer>, (list, pointA, pointB) -> distance(pointA, pointB)). ?
}

What its the most efficient way to do it (or at least a solution that works) ? Which operator should i use ?

To give a more concrete example, here is what I have and what I want:

Point a (45, 32)
Point b (56, 75)
Point c (44, 53)
Point d (42, 54)
Point e (42, 55)

a to b = 10m
b to c = 15m
c to d = 25m
d to e = 10m

Result = 60m

In reality my points are GPS positions and I use the haversine formula to calculate the distance between two positions.

I use observables because the list of points to be calculated is updated sometime. In fact every x points the user has reached, I have an instruction to send. After sending the instruction, a new list of points until the next instruction is emit.

Body:
You can try buffer and reduce operators. For example:

public Observable<Double> totalDistance(Observable<List<Point>> obs) {
    return obs.flatMap(points ->
            Observable.fromIterable(points)
                    .buffer(2 /* count */, 1 /* skip */)
                    /* this emits a list of each two adjacent points from a given list of points. */
                    .reduce(0.0  /* initial value */, (totalDistance, twoPoints) -> {
                                // note: calculation may be skipped if the twoPoints list contains less than
                                // two elements.
                                final Point pointA = twoPoints.get(0);
                                final Point pointB = twoPoints.get(1);
                                return totalDistance + distance(pointA, pointB);
                            }
                    ).toObservable());
}


问:
Go template remove the last comma in range loop
I have code like this:

```<code>package main

import (
    "text/template"
    "os"
)

func main() {
    type Map map[string]string
    m := Map {
        "a": "b",
        "c": "d",
    }
    const temp = `{{range $key, $value := $}}key:{{$key}} value:{{$value}},{{end}}`
    t := template.Must(template.New("example").Parse(temp))
    t.Execute(os.Stdout, m)
}
</code>```

it will output :

key:a value:b,key:c value:d,

but I want something like this:

key:a value:b,key:c value:d

I don't need the last comma, how to remove it. I found a solution for looping an array here: https://groups.google.com/d/msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ , but I can't get index for a map.

答:
I used the below template to correctly format some JSON using a go template.

It handles a collection of any size or empty.

{{- define "JoinList" -}}
   {{- $lastIndex := math.Sub (len .) 1 -}}
   {{- range $index, $property := . -}}
   {{ if isKind "string" $property.value }}
   "{{ $property.key }}": "{{ $property.value }}"{{ if ne $index $lastIndex }},{{ end }}
   {{- else -}}
   "{{ $property.key }}": {{ $property.value }}{{ if ne $index $lastIndex }},{{ end }}
   {{ end }}
   {{- end -}}
{{- end -}}
```

Body:
I have code like this:

package main

import (
    "text/template"
    "os"
)

func main() {
    type Map map[string]string
    m := Map {
        "a": "b",
        "c": "d",
    }
    const temp = `{{range $key, $value := $}}key:{{$key}} value:{{$value}},{{end}}`
    t := template.Must(template.New("example").Parse(temp))
    t.Execute(os.Stdout, m)
}

it will output :

key:a value:b,key:c value:d,

but I want something like this:

key:a value:b,key:c value:d

I don't need the last comma, how to remove it. I found a solution for looping an array here: https://groups.google.com/d/msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ , but I can't get index for a map.


问:
How to send data to port in binary format
I am newbie in Low level programming. In my project(C#.NET) we are using EDBS protocol(7 bit format) for communication and i have the data in bit format to send like 00101010 so we would please guide me how to send these to port.I know that the serial port class accepts data in binary format but dont know how convert the bit format into byte .

Thanks in advance

prem

答:
Use the BitConverter class to create basic types (like bytes or ints) from bytes.

http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx

There is also a class called BitArray that can be used to store bit representations:

Convert from BitArray to Byte

OwnerDisplayName: prem

LastEditorDisplayName: Brian Campbell

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Johan S

LastEditorDisplayName: Johan S


问:
How do I append a text after an element has faded out completely?
I want to append a class .Appear only after ensuring the element has been removed completely..How can I achieve this?

```<code><html>
 <body>
     <div id="Append"></div>
 </body>
</html>

$(function(){
$(".Appear").stop().fadeOut("fast",function(){
    $(this).remove();
    alert(123);
    })

   $("#Append").append("<span class='Appear'>Appear</span>"); alert(8);
})
</code>```

http://jsfiddle.net/uyPJB/

答:
```<code>  $(".Appear").stop(true,true).fadeOut("slow",function(){
        $(this).remove();
        alert(123);
         $("#Append").append("<span class='Appear'>Appear</span>");
    });
</code>```

http://jsfiddle.net/uyPJB/4/

Body:
I want to append a class .Appear only after ensuring the element has been removed completely..How can I achieve this?

$(function(){
$(".Appear").stop().fadeOut("fast",function(){
    $(this).remove();
    alert(123);
    })

   $("#Append").append("Appear"); alert(8);
})

http://jsfiddle.net/uyPJB/

Body:
  $(".Appear").stop(true,true).fadeOut("slow",function(){
        $(this).remove();
        alert(123);
         $("#Append").append("<span class='Appear'>Appear</span>");
    });

http://jsfiddle.net/uyPJB/4/


问:
why all the commits and branches are shown in a straight forwarding line after git merge
as a sample i take these steps :

```<code>git branch -b newFeature
git add -A
git commit -m `my feature added`
git checkout master
git merge newFeature
</code>```

when i do git branch the branches are listed correctly

i expect the branches to be like this :

1.why all the commits and branches are shown in a straight forwarding line?

2.how to achieve the mentioned branching?

答:
Because git merge will do fast-forward (--ff) merge when possible by default. A fast-forward merge is possible when the two branches are not diverged. To get the branch graph like you expected, use --no-ff:

```<code>git merge --no-ff newFeature
</code>```

From the docs:

With --no-ff, create a merge commit in all cases, even when the merge could instead be resolved as a fast-forward.

Body:
as a sample i take these steps :

git branch -b newFeature
git add -A
git commit -m `my feature added`
git checkout master
git merge newFeature

when i do git branch the branches are listed correctly

i expect the branches to be like this :

1.why all the commits and branches are shown in a straight forwarding line?

2.how to achieve the mentioned branching?

Body:
Because git merge will do fast-forward (--ff) merge when possible by default. A fast-forward merge is possible when the two branches are not diverged. To get the branch graph like you expected, use --no-ff:

git merge --no-ff newFeature

From the docs:

With --no-ff, create a merge commit in all cases, even when the merge could instead be resolved as a fast-forward.


问:
Insert to web-page one instance of custom HTML element more than once
As example, I dynamically create instance of some custom HTML element.
After this, I twice use document.body.appendChild() and this work, but this should no be. What I may do for prevent this?

I put sample about this situation below in the text. RandomParagraphSizePlaceholder is simple web-component from some book. I use it only for illustration purposes.

https://jsfiddle.net/h6cxjae5/

P.S. I see, that is something wrong with web component, may be.

答:
Only one instance of web component exists in web-page.
But web component content is duplicated. May be, because it created in connectedCallback. I dont very famimiliar with web component :(.


问:
Call operator<< for a base class from within operator<< for a derived class, when they are not class members in C++
I have a base b and a derived d classes.
Within operator<< for d (which is not a class member) I want to call operator<< for b, plus other actions.
I used static_cast for that.

Is there any other way to achieve the same?
What are pros and cons of the alternatives?

```<code>class b {
};

class d : public b {
};

ostream& operator<<(ostream& os, const b& bi) {
    os << "base";
    return os;
}

ostream& operator<<(ostream& os, const d& di) {
    // call operator for the base class...;
    os << static_cast<b>(di) << endl;
    os << " ... and derived";
    return os;
}
</code>```

答:
This would be better handled by defining only 1 operator<< for just b, and then add a virtual method in b for that operator<< to call, and then have d override that method, eg:

```<code>class b {
public:
    virtual void printTo(ostream& os) const;
};

class d : public b {
public:
    void printTo(ostream& os) const override;
};

ostream& operator<<(ostream& os, const b& bi) {
    bi.printTo(os);
    return os;
}

void b::printTo(ostream& os) const {
    os << "base";
}

void d::printTo(ostream& os) const {
    b::printTo(os);
    os << endl << " ... and derived";
}
</code>```

Body:
I have a base b and a derived d classes.
Within operator<< for d (which is not a class member) I want to call operator<< for b, plus other actions.
I used static_cast for that.

Is there any other way to achieve the same?
What are pros and cons of the alternatives?

class b {
};

class d : public b {
};

ostream& operator<<(ostream& os, const b& bi) {
    os << "base";
    return os;
}

ostream& operator<<(ostream& os, const d& di) {
    // call operator for the base class...;
    os << static_cast(di) << endl;
    os << " ... and derived";
    return os;
}

Body:
This would be better handled by defining only 1 operator<< for just b, and then add a virtual method in b for that operator<< to call, and then have d override that method, eg:

class b {
public:
    virtual void printTo(ostream& os) const;
};

class d : public b {
public:
    void printTo(ostream& os) const override;
};

ostream& operator<<(ostream& os, const b& bi) {
    bi.printTo(os);
    return os;
}

void b::printTo(ostream& os) const {
    os << "base";
}

void d::printTo(ostream& os) const {
    b::printTo(os);
    os << endl << " ... and derived";
}


问:
Django Q object is adding extra - IS NOT NULL
for the below raw query, I want to build Django ORM query

```<code>Select * from employee
WHERE (address_id is not null OR address_id<>'*')
    AND (xyz_id is null OR xyz_id='*')
    AND (abc_id is null OR abc_id='*')
</code>```

So I have build ORM query as below

```<code>data = Employee.objects.filter(~Q(address_id="23") | Q(address_id__isnull=False),
                            Q(xyz_id__isnull=False) | Q(xyz_id='*'),
                            Q(abc_id__isnull=True) | Q(abc_id=‘*’))
</code>```

and when i print the query, it is showing as below

SELECT "employee"."id", "employee"."xyz_id", "employee"."abc_id" FROM
"employee" WHERE ((NOT ("employee"."address_id" = 23 AND
"employee"."address_id" IS NOT NULL) OR "employee"."address_id" IS
NOT NULL) AND ("employee"."xyz_id" IS NOT NULL OR "employee"."xyz_id"
= *) AND ("employee"."abc_id" IS NULL OR "employee"."abc_id" = *))

my question is why Q object in Django is adding bolded line in above generated query ? which is not solving for above raw sql criteria.

i am using Django 2.2 version

Kindly advise

答:
If you write Q(foo=bar), then an implicit constraint is that foo is not NULL, if you negate that however, it will write NOT (foo = bar) but if foo is NULL, then NOT (foo = bar) is NOT (NULL = bar) which is NULL, so this will be filtered out of the queryset. which would thus result in FALSE whereas for NULL, one would expect that this is TRUE.

To thus ensure that ~Q(…) is the full opposite of Q(…), it thus should add foo IS NOT NULL to the condition.

In this specific case however the query optimizer could probably indeed figure out that it is not necessary due to the address_id IS NOT NULL later in the query, but here apparently the optimizer does not eliminate that clause.

Body:
for the below raw query, I want to build Django ORM query

Select * from employee
WHERE (address_id is not null OR address_id<>'*')
    AND (xyz_id is null OR xyz_id='*')
    AND (abc_id is null OR abc_id='*')

So I have build ORM query as below

data = Employee.objects.filter(~Q(address_id="23") | Q(address_id__isnull=False),
                            Q(xyz_id__isnull=False) | Q(xyz_id='*'),
                            Q(abc_id__isnull=True) | Q(abc_id=‘*’))

and when i print the query, it is showing as below

SELECT "employee"."id", "employee"."xyz_id", "employee"."abc_id" FROM
"employee" WHERE ((NOT ("employee"."address_id" = 23 AND
"employee"."address_id" IS NOT NULL) OR "employee"."address_id" IS
NOT NULL) AND ("employee"."xyz_id" IS NOT NULL OR "employee"."xyz_id"
= *) AND ("employee"."abc_id" IS NULL OR "employee"."abc_id" = *))

my question is why Q object in Django is adding bolded line in above generated query ? which is not solving for above raw sql criteria.

i am using Django 2.2 version

Kindly advise


问:
Using MongoDB query to show all items in a Collection with a specific value (DiscordJS v13)
I'm trying to make my last command for my discord bot (Discord.js v13), a marketplace with a MongoDB Collection called "Perso".

The problem is that I really don't know how to make it work, even after reading MongoDB and mongoose documentation, also searching similar (not really) problems on Stack Overflow.

Here is the little piece of code I did to test a return of value :

```<code>    let persoOnSale = await Perso.count({ onSale: 1}); // There are 2 "Perso" with the "onSale" field equals to 1.
    let perso = Perso.find({ onSale: 1}, 'name value').sort({value: 1});

     for (let index = 0; index < persoOnSale; index++) {
         const element = perso[index];
         console.log(element); // element return "undefined", 2 times.

     }
</code>```

Here is the console.log return when it's console.log(perso) :

```<code>[
  {
    _id: new ObjectId("61fc60165a048fa5700de25d"),
    name: 'Perso Name',
    value: 160
  },
  {
    _id: new ObjectId("61fbe486ef3f2c2b31c57dc5"),
    name: 'Perso Name 2',
    value: 10000
  }
]

</code>```

I was trying to show all the "Perso" with (onSale: 1), showing their name and value, and sort them in order to show the "Perso" with the least value amount first.

First of all, I imagine I need to put an index on the "perso" array, but I clearly don't know how to do that.

I'd be really thankful for your help.

答:
I guess your problem comes from the usage of findOne() instead of find()

Try this:

```<code>    let persoOnSale = await Perso.count({ onSale: 1});
    let perso = Perso.find({ onSale: 1}, 'name value').sort({value: 1});

     for (let index = 0; index < persoOnSale; index++) {
         const element = perso[index];
         console.log(element);

     }
</code>```

Body:
I'm trying to make my last command for my discord bot (Discord.js v13), a marketplace with a MongoDB Collection called "Perso".

The problem is that I really don't know how to make it work, even after reading MongoDB and mongoose documentation, also searching similar (not really) problems on Stack Overflow.

Here is the little piece of code I did to test a return of value :

    let persoOnSale = await Perso.count({ onSale: 1}); // There are 2 "Perso" with the "onSale" field equals to 1.
    let perso = Perso.find({ onSale: 1}, 'name value').sort({value: 1});

     for (let index = 0; index < persoOnSale; index++) {
         const element = perso[index];
         console.log(element); // element return "undefined", 2 times.

     }

Here is the console.log return when it's console.log(perso) :

[
  {
    _id: new ObjectId("61fc60165a048fa5700de25d"),
    name: 'Perso Name',
    value: 160
  },
  {
    _id: new ObjectId("61fbe486ef3f2c2b31c57dc5"),
    name: 'Perso Name 2',
    value: 10000
  }
]

I was trying to show all the "Perso" with (onSale: 1), showing their name and value, and sort them in order to show the "Perso" with the least value amount first.

First of all, I imagine I need to put an index on the "perso" array, but I clearly don't know how to do that.

I'd be really thankful for your help.

Body:
I guess your problem comes from the usage of findOne() instead of find()

Try this:

    let persoOnSale = await Perso.count({ onSale: 1});
    let perso = Perso.find({ onSale: 1}, 'name value').sort({value: 1});

     for (let index = 0; index < persoOnSale; index++) {
         const element = perso[index];
         console.log(element);

     }


问:
the difference between unset and = null
From a random php.net post:

If you are doing $whatever = null; then you are rewriting variable's
  data. You might get memory freed / shrunk faster, but it may steal CPU
  cycles from the code that truly needs them sooner, resulting in a
  longer overall execution time.

Apparently this is the undisputed truth so maybe someone would be so kind as to explain.

I mean, what, does unset magically not execute any assembly instructions whereas $whatever = null; does? The answer, as given, is about as useful as saying

$whatever = null resets the buffer and the L1 cache whereas unset clears the buffer and resets the L2 cache.

Techno mumbo jumbo doesn't constitute an answer.

答:
The difference is that assignment of null is assignment of null and not uninitialization. If you do not work on performance critical issue, you shut use unset, if you do test both possibility on your PHP version.
Main difference came with PHP 7.4, and properties types, you can unset not nullable property, but you can't assign null.

```<code>class C {
    public int $value;
}

$c = new C();
var_dump(isset($c->value));   // false
$c->value = 5;
var_dump($c->value);          //5
unset($c->value);
//var_dump($c->value);       //Error: Typed property C::$value must not be accessed before initialization
var_dump(isset($c->value));  // false
$c->value = 5;
$c->value = null;            //Error Typed property C::$value must be int, null used
</code>```

https://3v4l.org/VUVD1

Title: the difference between unset and = null

Body:
The difference is that assignment of null is assignment of null and not uninitialization. If you do not work on performance critical issue, you shut use unset, if you do test both possibility on your PHP version.
Main difference came with PHP 7.4, and properties types, you can unset not nullable property, but you can't assign null.

class C {
    public int $value;
}

$c = new C();
var_dump(isset($c->value));   // false
$c->value = 5;
var_dump($c->value);          //5
unset($c->value);
//var_dump($c->value);       //Error: Typed property C::$value must not be accessed before initialization
var_dump(isset($c->value));  // false
$c->value = 5;
$c->value = null;            //Error Typed property C::$value must be int, null used

https://3v4l.org/VUVD1


问:
How to find out if a number is a perfect square without using sqrt function or ** in Python?
I have to write a program that finds out whether or not a number is a perfect square. The terms are I don't use a sqrt function or an exponent (**)

I previously showed my teacher my solution using exponent (**) and she told me not to include that there.

```<code>num=int(input("Enter a positive integer: "))
base=1
while num/base!=base:
    base=base+1
if (num/base)%1==0:
    print(num,"is a square")
else:
    print(num,"is not a square")
</code>```

It works fine with perfect squares but when they're not, it won't work because I can't find a way to get it out of the while loop even though it's not a perfect square.

答:
The sum of the first odd integers, beginning with one, is a perfect square.
See proof

1 = 1

1 + 3 = 4

1 + 3 + 5 = 9

1 + 3 + 5 + 7 = 16

and so on .....

So here, we can make use of this important fact to find a solution without using pow() or sqrt() in-built functions.

```<code>num = int(input("Enter a positive integer: "))
odd = 1

while num > 0:
num -= odd
odd += 2
if num == 0:
print('It is a pefect square')
else:
print('It is not a pefect square')
</code>```

Body:
I have to write a program that finds out whether or not a number is a perfect square. The terms are I don't use a sqrt function or an exponent (**)

I previously showed my teacher my solution using exponent (**) and she told me not to include that there.

num=int(input("Enter a positive integer: "))
base=1
while num/base!=base:
    base=base+1
if (num/base)%1==0:
    print(num,"is a square")
else:
    print(num,"is not a square")

It works fine with perfect squares but when they're not, it won't work because I can't find a way to get it out of the while loop even though it's not a perfect square.

Body:
The sum of the first odd integers, beginning with one, is a perfect square.
See proof

1 = 1

1 + 3 = 4

1 + 3 + 5 = 9

1 + 3 + 5 + 7 = 16

and so on .....

So here, we can make use of this important fact to find a solution without using pow() or sqrt() in-built functions.

num = int(input("Enter a positive integer: "))
odd = 1

while num > 0:
num -= odd
odd += 2
if num == 0:
print('It is a pefect square')
else:
print('It is not a pefect square')


问:
Deploy feature on android without creating apk file
For very small changes, it is sometimes very difficult to always deploy the features with a new apk files. Every time, the build number is increased for such a step and it doesn't really looks good seeing so many apks. So, I wanted to know, if there's a way, like we can deploy features on our android app and that could be done without increasing any build number or making new apk files. When tester confirms the scenarios then, we can go for pre-production/production release directly.

答:
There are severall approaches to this:

Feature flags

By applying a programming pattern which allows you to enable / disable features in your app through configuration flags which can be toggled at runtime, it is possible to enable / dissable certain features in your app. Your app could check in your backend if a new configuration is available and enable features based on this configuration.

This makes shipping new features safer since they can easily be turned off if it turns out that they cause problems.

Firebase also offers a library for this called Firebase Remote Config.

Use WebViews

For content that changes frequently, an easy solution is to implement the content as a website and use a WebView which loads the content from a web URL. The content can then easily be changed remotely.

An example that comes to mind is a "Latest promotions" page in a shopping app. Having the promotions page as a WebView gives designers full flexibility without requiring an app update.


问:
Making a slide down menu
I am making a slide down menu, but it just jumps to its intended height, with no transition. Can anyone point me in the right direction?</p>
```<code>const Container = styled.section`
  position: relative;
  overflow: hidden;
`

const WrapperItems = styled.div`
  padding-left: 2rem;
  user-select: none;
  transition: all 1s ease-in-out;
  position: relative;
  height: 0;

  &.active {
    max-height: 100vh;
    height: auto;
  }

return (
    <Container>
      <Wrapper onClick={() => setIsOpen(!isOpen)}>
        <div className="title">{title}</div>

      </Wrapper>
      <WrapperItems className={isOpen ? "active" : ""}>
        {items.map(item => (
          <div className="item" onClick={() => navigate(item.to)}>{item.title}</div>
        ))}
      </WrapperItems>
    </Container>
  );
</code>```

答:
CSS solutions

Unfortunately there is no way to make a transition on an auto value in CSS. This choice has been made because it was considered as too expensive.

It will work if you replace the auto by a fixed value like 500px.

To avoid fixing exactly the content, you could also use a "hack" by doing the transition on max-height, and choosing to animate to a value that you know is always higher than the value of your content.
But you will have to choose a value that is high enough, but not too high because there will be a delay where the animation will start collapsing the non visible part of the items wrapper.

padding-left: 2rem;
user-select: none;
transition: all 1s ease-in-out;
position: relative;
max-height: 0;

&.active {
  max-height: 30vh; /* you know for sure that your content will never exceed 30 vh*/
}
```
<h3>JavaScript solutions</h3>
<p>You have also JavaScript based solutions that work well.</p>
<p>Here is an example with framer motion that lets you use the <code>height: auto</code> syntax :</p>
```import { motion } from "framer-motion";

// [...]

return (
  <Container>
    <Wrapper onClick={() => setIsOpen(!isOpen)}>

{title}

    </Wrapper>
    <WrapperItems>
      <motion.div
        animate={isOpen ? "open" : "closed"}
        variants={{
          open: { height: "auto" },
          closed: { height: 0 },
        }}
      >
        {items.map((item) => (

 navigate(item.to)}>
            {item.title}

        ))}
      </motion.div>
    </WrapperItems>
  </Container>
);

// [...]

```

Title: Making a slide down menu

Body:
I am making a slide down menu, but it just jumps to its intended height, with no transition. Can anyone point me in the right direction?

const Container = styled.section`
  position: relative;
  overflow: hidden;
`

const WrapperItems = styled.div`
  padding-left: 2rem;
  user-select: none;
  transition: all 1s ease-in-out;
  position: relative;
  height: 0;

  &.active {
    max-height: 100vh;
    height: auto;
  }

return (
    <Container>
      <Wrapper onClick={() => setIsOpen(!isOpen)}>

{title}

      </Wrapper>
      <WrapperItems className={isOpen ? "active" : ""}>
        {items.map(item => (

 navigate(item.to)}>{item.title}

        ))}
      </WrapperItems>
    </Container>
  );

Body:
CSS solutions

Unfortunately there is no way to make a transition on an auto value in CSS. This choice has been made because it was considered as too expensive.

It will work if you replace the auto by a fixed value like 500px.

To avoid fixing exactly the content, you could also use a "hack" by doing the transition on max-height, and choosing to animate to a value that you know is always higher than the value of your content.
But you will have to choose a value that is high enough, but not too high because there will be a delay where the animation will start collapsing the non visible part of the items wrapper.

padding-left: 2rem;
user-select: none;
transition: all 1s ease-in-out;
position: relative;
max-height: 0;

&.active {
  max-height: 30vh; /* you know for sure that your content will never exceed 30 vh*/
}

JavaScript solutions

You have also JavaScript based solutions that work well.

Here is an example with framer motion that lets you use the height: auto syntax :

import { motion } from "framer-motion";

// [...]

return (
  <Container>
    <Wrapper onClick={() => setIsOpen(!isOpen)}>
      <div className="title">{title}</div>
    </Wrapper>
    <WrapperItems>
      <motion.div
        animate={isOpen ? "open" : "closed"}
        variants={{
          open: { height: "auto" },
          closed: { height: 0 },
        }}
      >
        {items.map((item) => (
          <div className="item" onClick={() => navigate(item.to)}>
            {item.title}
          </div>
        ))}
      </motion.div>
    </WrapperItems>
  </Container>
);

// [...]


问:
How to split df with a column of dictionary need to split all its values and keys into respective coulmn
```<code>{'labels': ['travel', 'dancing', 'cooking'],
'scores': [0.9938651323318481, 0.0032737774308770895, 0.002861034357920289],
'sequence': 'one day I will see the world'}
</code>```

i have this a df['prediction'] column i want to split this result into three different column as df['travel'],df['dancing'],df['cooking'] and their respective scores i am sorry if the question is not appropriaterequired result

required result

答:
you can edit your data as a list of dicts and each dict is row data
and at the end, you can you set_index  you select the index

```<code>import pandas as pd

list_t = [{
    "travel":0.9938651323318481,
    "dancing": 0.0032737774308770895,
    "cooking":0.002861034357920289,
    "sequence":'one day I will see the world'
}]

df = pd.DataFrame(list_t)
df.set_index("sequence")
#output
                                  travel    dancing     cooking
sequence
one day I will see the world    0.993865    0.003274    0.002861
</code>```

Body:
{'labels': ['travel', 'dancing', 'cooking'],
'scores': [0.9938651323318481, 0.0032737774308770895, 0.002861034357920289],
'sequence': 'one day I will see the world'}

i have this a df['prediction'] column i want to split this result into three different column as df['travel'],df['dancing'],df['cooking'] and their respective scores i am sorry if the question is not appropriaterequired result

required result

Body:
you can edit your data as a list of dicts and each dict is row data
and at the end, you can you set_index  you select the index

import pandas as pd

list_t = [{
    "travel":0.9938651323318481,
    "dancing": 0.0032737774308770895,
    "cooking":0.002861034357920289,
    "sequence":'one day I will see the world'
}]

df = pd.DataFrame(list_t)
df.set_index("sequence")
#output
                                  travel    dancing     cooking
sequence
one day I will see the world    0.993865    0.003274    0.002861


问:
What is the point of salt and hashing if database is accessible?
I just learned the concept of hashing ("Hey! don't forget the salt!") and using salt to make the password secured.

Hashing it is a one way encryption (actually not encryption but hashing) so it cannot be reversed engineered. Salting is prefixing or appending randomly created values to the password before hashing 'coz the problem in hashing (just hashing) is, some genius has provided a hash table of words from the dictionary so that they'll just compare the hash from that dictionary to the user's table from the database to login - W-wait? did I say table from the database? So it means somebody can access the database so we have to use salt? If that so, then why would the hacker recover the password if he already has access to the database? If I were him, I'll just get all the details I want from the database, why would I use the key I've stolen from a house to open the door if I can access the house already through the window?

So, why hash? why salt? I don't understand. Please, somebody help me.

Thanks in advance.

Important Note: I'm not against hashing or salting, I just want to clarify things.

答:
Salt is used so that identical passwords have different hashes, making an attempt at figuring out the passwords harder.

Hashing makes it so that generating the password via brute force methods take a very long time (especially with SHA2) so that it makes it "unfeasible" to find out the password.

A hash will do you no good if you don't know the password as typing the hash into a password field will not work (obviously).

Usually hackers only find users tables and maybe some basic information but if they want to be able to actually access that users info and change something then they need the actual password (since they don't know the whole DB schema changing something could look very suspicious and is easily traceable unless you legitimately login as the person)

One last thing I forgot about is that people do reuse passwords. So maybe you hacked some random site that has no useful information on it but the person used the same user/password combination on their online banking. This could be very bad as you can see so not being able to easily discern the password is key.


问:
Importing JSON file in TypeScript
I have a JSON file that looks like following:

```<code>{

  "primaryBright":    "#2DC6FB",
  "primaryMain":      "#05B4F0",
  "primaryDarker":    "#04A1D7",
  "primaryDarkest":   "#048FBE",

  "secondaryBright":  "#4CD2C0",
  "secondaryMain":    "#00BFA5",
  "secondaryDarker":  "#009884",
  "secondaryDarkest": "#007F6E",

  "tertiaryMain":     "#FA555A",
  "tertiaryDarker":   "#F93C42",
  "tertiaryDarkest":  "#F9232A",

  "darkGrey":         "#333333",
  "lightGrey":        "#777777"
}
</code>```

I'm trying to import it into a .tsx file. For this I added this to the type definition:

```<code>declare module "*.json" {
  const value: any;
  export default value;
}
</code>```

And I'm importing it like this.

import colors = require('../colors.json')

And in the file, I use the color primaryMain as colors.primaryMain. However I get an error:

Property 'primaryMain' does not exist on type 'typeof "*.json"

答:
In an Angular (typescript) app, I needed to include a .json file in my environment.ts. To do so, I had to set two options in tsconfig:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "resolveJsonModule": true
  }
}
```
<p>Then, I could import my json file into the <code>environment.ts</code>:</p>
<pre class="lang-js prettyprint-override"><code>import { default as someObjectName } from "../some-json-file.json";
</code>```

Title: Importing JSON file in TypeScript

Body:
I have a JSON file that looks like following:

{

  "primaryBright":    "#2DC6FB",
  "primaryMain":      "#05B4F0",
  "primaryDarker":    "#04A1D7",
  "primaryDarkest":   "#048FBE",

  "secondaryBright":  "#4CD2C0",
  "secondaryMain":    "#00BFA5",
  "secondaryDarker":  "#009884",
  "secondaryDarkest": "#007F6E",

  "tertiaryMain":     "#FA555A",
  "tertiaryDarker":   "#F93C42",
  "tertiaryDarkest":  "#F9232A",

  "darkGrey":         "#333333",
  "lightGrey":        "#777777"
}

I'm trying to import it into a .tsx file. For this I added this to the type definition:

declare module "*.json" {
  const value: any;
  export default value;
}

And I'm importing it like this.

import colors = require('../colors.json')

And in the file, I use the color primaryMain as colors.primaryMain. However I get an error:

Property 'primaryMain' does not exist on type 'typeof "*.json"

Body:
In an Angular (typescript) app, I needed to include a .json file in my environment.ts. To do so, I had to set two options in tsconfig:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "resolveJsonModule": true
  }
}

Then, I could import my json file into the environment.ts:

import { default as someObjectName } from "../some-json-file.json";


问:
Unable to create an object of type 'DbContext'
When I try to run

```<code>dotnet ef migration add Init
</code>```

I get error

Unable to create an object of type 'IdentityContext'.

I know what caused the problem. I wanted to learn using message bus and added it to my project, so I run for some course and implemented it. Ofc bus working perfectly. But the problem is that I can no longer migrate via EF.

My Startup.cs before was.

```<code>public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}
</code>```

Now it looks like this.

```<code>public static void Main(string[] args)
{
  ServiceHost.Create<Startup>(args)
    .UseRabbitMq()
    .Build()
    .Run();
}
</code>```

And ServiceHost class

```<code>public void Run() => _webHost.Run();

public static HostBuilder Create<TStartup>(string[] args) where TStartup : class
{
  Console.Title = typeof(TStartup).Namespace;
  var config = new ConfigurationBuilder()
    .AddEnvironmentVariables()
    .AddCommandLine(args)
    .Build();
  var webHostBuilder = WebHost.CreateDefaultBuilder()
    .UseConfiguration(config)
    .UseStartup<TStartup>();

  return new HostBuilder(webHostBuilder.Build());
}
</code>```

So anyone would give advice why migration stopped to work? For me it looks like it should work, but it isn't so I guess I'm wrong.

And ofc I have in my Startup.cs

```<code>services.AddEntityFrameworkNpgsql().AddDbContext<IdentityContext>(options =>
    options.UseNpgsql(Configuration.GetConnectionString("IdentityConnection")));
</code>```

EDIT
IdentityContext class:

```<code>  public class IdentityContext : DbContext
  {
    public IdentityContext(DbContextOptions<IdentityContext> options) : base(options)
    {
      while (!Debugger.IsAttached)
      {
        Thread.Sleep(100);
      }
    }
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity<User>().HasIndex(user => user.Email).IsUnique();
      modelBuilder.Entity<User>().HasIndex(user => user.Username).IsUnique();
    }
  }
</code>```

EDIT2.
Verbose migration

```<code>Using project '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj'.
Using startup project '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj'.
Writing '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/obj/CrossX.Identity.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/tmp/tmpCq3PQa.tmp /verbosity:quiet /nologo /home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj
Writing '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/obj/CrossX.Identity.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/tmp/tmpR48yu8.tmp /verbosity:quiet /nologo /home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj
dotnet build /home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj /verbosity:quiet /nologo

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.17
dotnet exec --depsfile /home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2/CrossX.Identity.deps.json --additionalprobingpath /home/msek/.nuget/packages --runtimeconfig /home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2/CrossX.Identity.runtimeconfig.json /home/msek/.dotnet/tools/.store/dotnet-ef/2.2.2/dotnet-ef/2.2.2/tools/netcoreapp2.2/any/tools/netcoreapp2.0/any/ef.dll migrations add Init --assembly /home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2/CrossX.Identity.dll --startup-assembly /home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2/CrossX.Identity.dll --project-dir /home/msek/Projects/inz/CrossX/src/CrossX.Identity/ --language C# --working-dir /home/msek/Projects/inz/CrossX/src/CrossX.Identity --verbose --root-namespace CrossX.Identity
Using assembly 'CrossX.Identity'.
Using startup assembly 'CrossX.Identity'.
Using application base '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2'.
Using working directory '/home/msek/Projects/inz/CrossX/src/CrossX.Identity'.
Using root namespace 'CrossX.Identity'.
Using project directory '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding IWebHost accessor...
No CreateWebHostBuilder(string[]) method was found on type 'CrossX.Identity.Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'IdentityContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'IdentityContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ---> System.MissingMethodException: No parameterless constructor defined for this object.
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'IdentityContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
</code>```

答:
in my case the reason of issue was the incorrect path to the dbsettings.json file.
This path is should be written in the Startup.cs file.</p>
```<code> public Startup(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostEnv)
    {
        _confString = new ConfigurationBuilder().SetBasePath(hostEnv.ContentRootPath).AddJsonFile("dbsettings.json").Build();

    }
</code>```

Body:
When I try to run

dotnet ef migration add Init

I get error

Unable to create an object of type 'IdentityContext'.

I know what caused the problem. I wanted to learn using message bus and added it to my project, so I run for some course and implemented it. Ofc bus working perfectly. But the problem is that I can no longer migrate via EF.

My Startup.cs before was.

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

Now it looks like this.

public static void Main(string[] args)
{
  ServiceHost.Create<Startup>(args)
    .UseRabbitMq()
    .Build()
    .Run();
}

And ServiceHost class

public void Run() => _webHost.Run();

public static HostBuilder Create<TStartup>(string[] args) where TStartup : class
{
  Console.Title = typeof(TStartup).Namespace;
  var config = new ConfigurationBuilder()
    .AddEnvironmentVariables()
    .AddCommandLine(args)
    .Build();
  var webHostBuilder = WebHost.CreateDefaultBuilder()
    .UseConfiguration(config)
    .UseStartup<TStartup>();

  return new HostBuilder(webHostBuilder.Build());
}

So anyone would give advice why migration stopped to work? For me it looks like it should work, but it isn't so I guess I'm wrong.

And ofc I have in my Startup.cs

services.AddEntityFrameworkNpgsql().AddDbContext<IdentityContext>(options =>
    options.UseNpgsql(Configuration.GetConnectionString("IdentityConnection")));

EDIT
IdentityContext class:

  public class IdentityContext : DbContext
  {
    public IdentityContext(DbContextOptions<IdentityContext> options) : base(options)
    {
      while (!Debugger.IsAttached)
      {
        Thread.Sleep(100);
      }
    }
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity<User>().HasIndex(user => user.Email).IsUnique();
      modelBuilder.Entity<User>().HasIndex(user => user.Username).IsUnique();
    }
  }

EDIT2.
Verbose migration

Using project '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj'.
Using startup project '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj'.
Writing '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/obj/CrossX.Identity.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/tmp/tmpCq3PQa.tmp /verbosity:quiet /nologo /home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj
Writing '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/obj/CrossX.Identity.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/tmp/tmpR48yu8.tmp /verbosity:quiet /nologo /home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj
dotnet build /home/msek/Projects/inz/CrossX/src/CrossX.Identity/CrossX.Identity.csproj /verbosity:quiet /nologo

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.17
dotnet exec --depsfile /home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2/CrossX.Identity.deps.json --additionalprobingpath /home/msek/.nuget/packages --runtimeconfig /home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2/CrossX.Identity.runtimeconfig.json /home/msek/.dotnet/tools/.store/dotnet-ef/2.2.2/dotnet-ef/2.2.2/tools/netcoreapp2.2/any/tools/netcoreapp2.0/any/ef.dll migrations add Init --assembly /home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2/CrossX.Identity.dll --startup-assembly /home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2/CrossX.Identity.dll --project-dir /home/msek/Projects/inz/CrossX/src/CrossX.Identity/ --language C# --working-dir /home/msek/Projects/inz/CrossX/src/CrossX.Identity --verbose --root-namespace CrossX.Identity
Using assembly 'CrossX.Identity'.
Using startup assembly 'CrossX.Identity'.
Using application base '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/bin/Debug/netcoreapp2.2'.
Using working directory '/home/msek/Projects/inz/CrossX/src/CrossX.Identity'.
Using root namespace 'CrossX.Identity'.
Using project directory '/home/msek/Projects/inz/CrossX/src/CrossX.Identity/'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding IWebHost accessor...
No CreateWebHostBuilder(string[]) method was found on type 'CrossX.Identity.Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'IdentityContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'IdentityContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ---> System.MissingMethodException: No parameterless constructor defined for this object.
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'IdentityContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Body:
in my case the reason of issue was the incorrect path to the dbsettings.json file.
This path is should be written in the Startup.cs file.

 public Startup(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostEnv)
    {
        _confString = new ConfigurationBuilder().SetBasePath(hostEnv.ContentRootPath).AddJsonFile("dbsettings.json").Build();

    }


问:
Which cluster type should I choose for Spark?
I am new to Apache Spark, and I just learned that Spark supports three types of cluster:

Standalone - meaning Spark will manage its own cluster

YARN - using Hadoop's YARN resource manager

Mesos - Apache's dedicated resource manager project

I think I should try Standalone first. In the future, I need to build a large cluster (hundreds of instances).

Which cluster type should I choose?

答:
In this case and similar dilemmas in data engineering, there are many side questions to be answered before choosing one distribution method over another.
For example, if you are not running your processing engine on more than 3 nodes, you usually are not facing too big of a problem to handle so your margin of performance tuning between YARN and SparkStandalone (based on experience) will not clarify your decision. Because usually you will try to make your pipeline simple, specially when your services are not self-managed by cloud and bugs and failures happen often.

I choose standalone for relatively small or not-complex pipelines but if I'm feeling alright and have a Hadoop cluster already in place, I prefer to take advantage of all the extra configs that Hadoop(Yarn) can give me.


问:
InfluxDB: unrecognized service
I tried to follow the tutorial to run InfluxDB on WSL Ubuntu. But when I tried to run the service by

```<code>sudo service influxdb start
</code>```

it shows:

influxdb: unrecognized service

答:
On WSL Ubuntu, you can manually run the InfluxDB daemon with:

influxd &
```
<p>The ampersand at the end makes the daemon run in the background, so you can still execute commands after launching it. You can also close the WSL window, and the daemon will keep running.</p>
<p>Note: you can accidently run multiple instances of the InfluxDB with this method; you can check that none is running with:</p>
<pre class="lang-sh prettyprint-override"><code>ps -A | grep influxd
</code>```

Title: InfluxDB: unrecognized service

Body:
I tried to follow the tutorial to run InfluxDB on WSL Ubuntu. But when I tried to run the service by

sudo service influxdb start

it shows:

influxdb: unrecognized service

Body:
On WSL Ubuntu, you can manually run the InfluxDB daemon with:

influxd &

The ampersand at the end makes the daemon run in the background, so you can still execute commands after launching it. You can also close the WSL window, and the daemon will keep running.

Note: you can accidently run multiple instances of the InfluxDB with this method; you can check that none is running with:

ps -A | grep influxd