问:
Why is my attempt to fit a tanh(x) function to data not working well?
I've got data of anode currents for different anode voltages. I'm trying to fit a tanh(x) curve to the resulting I-V curve using curve_fit, but I keep getting a line.

Since I'm trying to fit a curve to y against log10(x) I did the curve_fit 2 ways:

I took the log10 of the data first and fit the curve second

I fit the curve first and took the log10 of the data second.

Method 1 code and output:

```<code>import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def fitfunction(v, a, b, c, d):
    return a * np.tanh(b * v + c) + d

# x data = V90
# y data = np.log10(I90)

pars, cov = curve_fit(fitfunction, V90, np.log10(I90))

plt.plot(V90, fitfunction(V90, *pars), 'r-', linewidth='3', label='Line of Best Fit')
plt.scatter(V90, np.log10(I90), marker='.', label='Data')

plt.title('Graph of Line of Best Fit of Anode Current against Anode Potential')
plt.grid(True)
plt.xlabel('Voltage (V)')
plt.ylabel('Current (A)')
plt.legend()
plt.show()
</code>```

The resulting graph using the above code was:

Method 2 code and output:

```<code>pars, cov = curve_fit(fitfunction, V90, I90)
print(pars)

y = fitfunction(V90, *pars)

if any(i < 0 for i in y) == True:
    y = y + abs(min(y))

y = y[377:]
x = V90[377:]

plt.plot(x, np.log10(y), 'r-', linewidth='3', label='Line of Best Fit')
plt.scatter(V90, np.log10(I90), marker='.', label='Data')

plt.title('Graph of Line of Best Fit of Anode Current against Anode Potential')
plt.grid(True)
plt.xlabel('Voltage (V)')
plt.ylabel('Current (A)')
plt.legend()
plt.show()
</code>```

The resulting graph using this code was:

I'm not quite sure why in the second method, even if I do cut off the 0 values, there is still such a drastic deviation when V90 < 0.

The part of the data that's causing problems seems to be somewhere in 2.5V-5.0V which is about 500 lines of data:

```<code>#Voltages(V) Currents(A) Af=89.9mA Vf=24.3V
2.50000,0.0003815846315912
2.50500,0.0003816979315912
2.51000,0.0003817056315912
2.51500,0.00038173013159120006
2.52000,0.00038178253159120004
2.52500,0.0003818257315912
2.53000,0.0003819050315912
2.53500,0.0003818466315912
2.54000,0.0003818978315912
2.54500,0.0003819977315912
2.55000,0.00038197953159120005
2.55500,0.00038198843159120005
2.56000,0.00038210623159120005
2.56500,0.00038209303159120005
2.57000,0.0003821845315912
2.57500,0.0003821863315912
2.58000,0.00038220063159120004
2.58500,0.0003822367315912
2.59000,0.00038230733159120005
2.59500,0.00038230853159120003
2.60000,0.00038232433159120005
2.60500,0.0003823070315912
2.61000,0.0003824262315912
2.61500,0.0003824784315912
2.62000,0.0003825377315912
2.62500,0.0003825299315912
2.63000,0.0003825463315912
2.63500,0.00038256423159120005
2.64000,0.00038260893159120006
2.64500,0.0003826748315912
2.65000,0.0003826939315912
2.65500,0.0003826620315912
2.66000,0.00038270823159120004
2.66500,0.00038275413159120003
2.67000,0.0003827898315912
2.67500,0.0003828730315912
2.68000,0.00038286673159120005
2.68500,0.00038290933159120004
2.69000,0.0003829376315912
2.69500,0.0003829943315912
2.70000,0.0003830041315912
2.70500,0.00038304703159120005
2.71000,0.0003830539315912
2.71500,0.0003830631315912
2.72000,0.0003831442315912
2.72500,0.00038314893159120005
2.73000,0.0003831841315912
2.73500,0.0003832354315912
2.74000,0.00038327293159120005
2.74500,0.0003833084315912
2.75000,0.0003833653315912
2.75500,0.0003834109315912
2.76000,0.00038340913159120004
2.76500,0.0003834842315912
2.77000,0.00038352123159120005
2.77500,0.00038353283159120005
2.78000,0.00038357873159120003
2.78500,0.00038351133159120004
2.79000,0.00038353613159120004
2.79500,0.0003836058315912
2.80000,0.00038369733159120004
2.80500,0.0003836595315912
2.81000,0.00038369343159120006
2.81500,0.0003837056315912
2.82000,0.0003837095315912
2.82500,0.0003837635315912
2.83000,0.0003838389315912
2.83500,0.00038387283159120004
2.84000,0.00038388863159120006
2.84500,0.00038390353159120004
2.85000,0.00038393663159120005
2.85500,0.00038400643159120006
2.86000,0.00038402783159120004
2.86500,0.0003840540315912
2.87000,0.00038411223159120003
2.87500,0.00038411843159120003
2.88000,0.0003841074315912
2.88500,0.0003841589315912
2.89000,0.00038417953159120005
2.89500,0.0003841864315912
2.90000,0.00038419383159120005
2.90500,0.0003842904315912
2.91000,0.0003843029315912
2.91500,0.0003842731315912
2.92000,0.0003843509315912
2.92500,0.0003843986315912
2.93000,0.00038439503159120003
2.93500,0.0003843986315912
2.94000,0.00038445253159120007
2.94500,0.0003844441315912
2.95000,0.00038448443159120005
2.95500,0.00038446503159120005
2.96000,0.00038451213159120006
2.96500,0.0003845723315912
2.97000,0.0003846322315912
2.97500,0.0003846078315912
2.98000,0.00038468173159120005
2.98500,0.0003846975315912
2.99000,0.00038470823159120004
2.99500,0.00038466083159120003
3.00000,0.00038470853159120003
3.00500,0.00038475533159120005
3.01000,0.00038481043159120003
3.01500,0.0003848238315912
3.02000,0.0003848566315912
3.02500,0.00038489833159120003
3.03000,0.0003848757315912
3.03500,0.0003849278315912
3.04000,0.0003849609315912
3.04500,0.0003849475315912
3.05000,0.0003850175315912
3.05500,0.0003850137315912
3.06000,0.0003850512315912
3.06500,0.0003851350315912
3.07000,0.0003850923315912
3.07500,0.0003851168315912
3.08000,0.00038514873159120003
3.08500,0.0003851388315912
3.09000,0.00038523033159120005
3.09500,0.00038527003159120004
3.10000,0.00038524373159120007
3.10500,0.00038534923159120005
3.11000,0.0003853215315912
3.11500,0.00038534393159120003
3.12000,0.0003853278315912
3.12500,0.0003853394315912
3.13000,0.0003853603315912
3.13500,0.0003853787315912
3.14000,0.00038547143159120003
3.14500,0.0003854083315912
3.15000,0.00038548693159120006
3.15500,0.00038548843159120003
3.16000,0.00038548723159120005
3.16500,0.0003855608315912
3.17000,0.0003855918315912
3.17500,0.0003855635315912
3.18000,0.0003856055315912
3.18500,0.00038563923159120006
3.19000,0.0003856708315912
3.19500,0.00038566013159120003
3.20000,0.0003857125315912
3.20500,0.00038573913159120003
3.21000,0.00038580913159120005
3.21500,0.00038580463159120003
3.22000,0.0003858180315912
3.22500,0.0003858449315912
3.23000,0.00038583533159120004
3.23500,0.00038587913159120006
3.24000,0.0003858967315912
3.24500,0.0003858645315912
3.25000,0.0003859590315912
3.25500,0.0003859778315912
3.26000,0.00038596353159120006
3.26500,0.00038597303159120005
3.27000,0.00038599453159120006
3.27500,0.0003860436315912
3.28000,0.0003860785315912
3.28500,0.0003860782315912
3.29000,0.00038609913159120006
3.29500,0.0003861384315912
3.30000,0.0003861640315912
3.30500,0.0003861927315912
3.31000,0.0003862037315912
3.31500,0.0003861900315912
3.32000,0.0003862180315912
3.32500,0.00038625343159120004
3.33000,0.00038624963159120004
3.33500,0.0003862892315912
3.34000,0.0003863312315912
3.34500,0.00038631103159120006
3.35000,0.00038635183159120004
3.35500,0.00038638793159120004
3.36000,0.0003863819315912
3.36500,0.0003864013315912
3.37000,0.00038648713159120004
3.37500,0.0003864919315912
3.38000,0.00038650973159120005
3.38500,0.0003865127315912
3.39000,0.0003865819315912
3.39500,0.0003865768315912
3.40000,0.00038658543159120006
3.40500,0.00038663733159120003
3.41000,0.00038662423159120006
3.41500,0.0003866617315912
3.42000,0.00038666563159120003
3.42500,0.0003866883315912
3.43000,0.00038664123159120006
3.43500,0.00038672403159120005
3.44000,0.0003867511315912
3.44500,0.00038671243159120005
3.45000,0.00038679173159120005
3.45500,0.00038677233159120004
3.46000,0.0003867619315912
3.46500,0.0003867944315912
3.47000,0.00038678993159120003
3.47500,0.0003868668315912
3.48000,0.00038685753159120004
3.48500,0.0003868131315912
3.49000,0.0003868772315912
3.49500,0.00038690763159120005
3.50000,0.00038699083159120007
3.50500,0.0003869496315912
3.51000,0.0003869472315912
3.51500,0.0003870432315912
3.52000,0.0003870340315912
3.52500,0.0003870396315912
3.53000,0.0003870617315912
3.53500,0.0003870569315912
3.54000,0.00038713173159120003
3.54500,0.00038711033159120005
3.55000,0.00038715503159120006
3.55500,0.00038715383159120003
3.56000,0.0003871439315912
3.56500,0.00038713713159120003
3.57000,0.00038718153159120005
3.57500,0.00038722833159120007
3.58000,0.0003871866315912
3.58500,0.0003872426315912
3.59000,0.0003872560315912
3.59500,0.00038726643159120005
3.60000,0.0003872912315912
3.60500,0.0003872947315912
3.61000,0.0003873543315912
3.61500,0.00038739643159120004
3.62000,0.0003873946315912
3.62500,0.0003874357315912
3.63000,0.00038740023159120003
3.63500,0.0003874494315912
3.64000,0.00038744203159120003
3.64500,0.00038750963159120004
3.65000,0.00038753823159120004
3.65500,0.0003876038315912
3.66000,0.0003876062315912
3.66500,0.0003876419315912
3.67000,0.00038765513159120006
3.67500,0.00038764313159120003
3.68000,0.0003876282315912
3.68500,0.0003876902315912
3.69000,0.0003876959315912
3.69500,0.0003877227315912
3.70000,0.0003877594315912
3.70500,0.0003877594315912
3.71000,0.00038777433159120005
3.71500,0.0003877194315912
3.72000,0.0003878219315912
3.72500,0.00038785143159120005
3.73000,0.0003878336315912
3.73500,0.00038787443159120003
3.74000,0.0003878839315912
3.74500,0.00038790993159120004
3.75000,0.0003879575315912
3.75500,0.0003880106315912
3.76000,0.00038798413159120003
3.76500,0.0003880049315912
3.77000,0.0003880705315912
3.77500,0.00038805773159120003
3.78000,0.0003880672315912
3.78500,0.00038812413159120007
3.79000,0.0003881292315912
3.79500,0.00038814233159120004
3.80000,0.0003881444315912
3.80500,0.0003881864315912
3.81000,0.0003881593315912
3.81500,0.0003881632315912
3.82000,0.0003881823315912
3.82500,0.00038825473159120004
3.83000,0.0003882901315912
3.83500,0.00038829763159120003
3.84000,0.0003882907315912
3.84500,0.00038834053159119997
3.85000,0.0003883670315912
3.85500,0.0003883939315912
3.86000,0.0003883834315912
3.86500,0.0003883804315912
3.87000,0.0003884391315912
3.87500,0.0003884344315912
3.88000,0.0003884836315912
3.88500,0.00038849013159120003
3.89000,0.00038856043159120004
3.89500,0.0003885616315912
3.90000,0.00038857123159120004
3.90500,0.0003886108315912
3.91000,0.0003886305315912
3.91500,0.0003886633315912
3.92000,0.00038866483159119997
3.92500,0.0003886671315912
3.93000,0.00038875213159120003
3.93500,0.0003887288315912
3.94000,0.0003887735315912
3.94500,0.0003887700315912
3.95000,0.00038872023159120005
3.95500,0.00038880303159120004
3.96000,0.0003888695315912
3.96500,0.0003888597315912
3.97000,0.00038894643159120005
3.97500,0.0003889258315912
3.98000,0.00038898183159120003
3.98500,0.0003889664315912
3.99000,0.0003889261315912
3.99500,0.00038897353159120007
4.00000,0.0003890727315912
4.00500,0.0003890072315912
4.01000,0.00038906323159120003
4.01500,0.00038904213159120005
4.02000,0.00038912523159120003
4.02500,0.0003891359315912
4.03000,0.0003891619315912
4.03500,0.0003891288315912
4.04000,0.0003892173315912
4.04500,0.0003891940315912
4.05000,0.0003892384315912
4.05500,0.0003893127315912
4.06000,0.0003893159315912
4.06500,0.0003892709315912
4.07000,0.0003892769315912
4.07500,0.0003892754315912
4.08000,0.00038935383159120003
4.08500,0.00038933983159120003
4.09000,0.00038941553159120004
4.09500,0.00038942323159120006
4.10000,0.0003894319315912
4.10500,0.0003895219315912
4.11000,0.0003895454315912
4.11500,0.00038950883159120003
4.12000,0.0003896175315912
4.12500,0.00038962773159120003
4.13000,0.0003896372315912
4.13500,0.0003896017315912
4.14000,0.0003896599315912
4.14500,0.00038967243159120004
4.15000,0.00038972243159120007
4.15500,0.00038967923159120003
4.16000,0.0003897564315912
4.16500,0.00038985093159120003
4.17000,0.0003898157315912
4.17500,0.0003898777315912
4.18000,0.00038985683159120004
4.18500,0.00038996063159120003
4.19000,0.00038990393159120005
4.19500,0.0003898995315912
4.20000,0.00039002143159120006
4.20500,0.0003900357315912
4.21000,0.00039002343159120004
4.21500,0.00039006813159120005
4.22000,0.00039010213159120004
4.22500,0.0003901114315912
4.23000,0.0003901018315912
4.23500,0.0003901289315912
4.24000,0.0003902195315912
4.24500,0.0003902076315912
4.25000,0.00039021833159120004
4.25500,0.0003902306315912
4.26000,0.00039023533159120003
4.26500,0.00039031403159120004
4.27000,0.0003903662315912
4.27500,0.00039037843159120004
4.28000,0.00039042283159120006
4.28500,0.0003903867315912
4.29000,0.00039044223159120006
4.29500,0.0003904630315912
4.30000,0.0003904529315912
4.30500,0.0003904729315912
4.31000,0.00039054473159120005
4.31500,0.0003905533315912
4.32000,0.0003905974315912
4.32500,0.0003905998315912
4.33000,0.0003906898315912
4.33500,0.00039066933159120004
4.34000,0.00039072833159120004
4.34500,0.00039076823159120004
4.35000,0.0003907929315912
4.35500,0.00039083443159120007
4.36000,0.0003908636315912
4.36500,0.00039086923159120006
4.37000,0.00039087253159120005
4.37500,0.0003908964315912
4.38000,0.0003909136315912
4.38500,0.00039098463159120006
4.39000,0.0003910287315912
4.39500,0.0003910355315912
4.40000,0.0003910477315912
4.40500,0.0003910922315912
4.41000,0.0003910749315912
4.41500,0.0003911458315912
4.42000,0.0003911830315912
4.42500,0.00039118783159120007
4.43000,0.00039116373159120004
4.43500,0.0003912555315912
4.44000,0.0003912483315912
4.44500,0.00039127843159120006
4.45000,0.0003914009315912
4.45500,0.0003913550315912
4.46000,0.00039139433159120007
4.46500,0.0003914075315912
4.47000,0.0003914602315912
4.47500,0.0003914307315912
4.48000,0.0003914930315912
4.48500,0.0003914924315912
4.49000,0.00039153143159120004
4.49500,0.00039155053159120004
4.50000,0.0003916068315912
4.50500,0.0003916372315912
4.51000,0.00039167213159120004
4.51500,0.00039174183159120006
4.52000,0.00039177053159120004
4.52500,0.00039176813159120003
4.53000,0.00039181583159120004
4.53500,0.0003918697315912
4.54000,0.00039187893159120003
4.54500,0.0003918822315912
4.55000,0.0003919370315912
4.55500,0.0003919138315912
4.56000,0.0003919716315912
4.56500,0.00039199283159120006
4.57000,0.00039201103159120003
4.57500,0.00039209833159120004
4.58000,0.00039208733159120003
4.58500,0.0003921516315912
4.59000,0.0003921233315912
4.59500,0.00039217223159120003
4.60000,0.0003922100315912
4.60500,0.0003922246315912
4.61000,0.0003922810315912
4.61500,0.00039230933159120006
4.62000,0.00039232663159120005
4.62500,0.0003923683315912
4.63000,0.00039239963159120006
4.63500,0.0003924449315912
4.64000,0.00039247533159120007
4.64500,0.0003924917315912
4.65000,0.0003925414315912
4.65500,0.0003925510315912
4.66000,0.0003926022315912
4.66500,0.00039258413159120003
4.67000,0.0003926276315912
4.67500,0.0003927253315912
4.68000,0.0003927191315912
4.68500,0.0003926767315912
4.69000,0.0003927778315912
4.69500,0.0003928117315912
4.70000,0.0003928255315912
4.70500,0.00039284933159120005
4.71000,0.00039287673159120007
4.71500,0.0003929137315912
4.72000,0.00039292833159120004
4.72500,0.00039297333159120005
4.73000,0.00039305613159120004
4.73500,0.00039298043159120003
4.74000,0.00039306123159120004
4.74500,0.00039308923159120005
4.75000,0.0003931020315912
4.75500,0.0003931107315912
4.76000,0.00039316343159120004
4.76500,0.00039320483159120006
4.77000,0.00039318313159120003
4.77500,0.0003932430315912
4.78000,0.00039328623159120006
4.78500,0.0003932948315912
4.79000,0.0003933348315912
4.79500,0.0003933708315912
4.80000,0.0003934275315912
4.80500,0.0003934933315912
4.81000,0.0003933869315912
4.81500,0.00039350763159120005
4.82000,0.00039353273159120004
4.82500,0.0003935321315912
4.83000,0.0003935798315912
4.83500,0.0003935836315912
4.84000,0.0003936641315912
4.84500,0.00039368763159120006
4.85000,0.00039365193159120003
4.85500,0.00039369873159120005
4.86000,0.0003937326315912
4.86500,0.00039382033159120005
4.87000,0.0003938480315912
4.87500,0.00039383903159120003
4.88000,0.0003938897315912
4.88500,0.0003940000315912
4.89000,0.0003939517315912
4.89500,0.0003940104315912
4.90000,0.0003940086315912
4.90500,0.0003939877315912
4.91000,0.00039403513159120006
4.91500,0.00039411413159120006
4.92000,0.0003941618315912
4.92500,0.00039414903159120003
4.93000,0.00039421843159120006
4.93500,0.00039421603159120006
4.94000,0.00039430313159120005
4.94500,0.0003943028315912
4.95000,0.0003943370315912
4.95500,0.0003943808315912
4.96000,0.0003943910315912
4.96500,0.00039442853159120004
4.97000,0.0003944494315912
4.97500,0.00039449833159120004
4.98000,0.00039456143159120004
4.98500,0.0003945686315912
4.99000,0.0003945677315912
4.99500,0.0003946011315912
</code>```

答:
I have to confess that I do not see any particular problem in the data and in fitting it. I'd actually say that any problems likely occur due to problems with initial values. The outliers are negligible, but one could try to use robust fitting. Start values can be guessed automatically like this:

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

def f( x, a, b, c, d ):
    return a * np.tanh( b * x + c ) + d

def g( x, a, b, c, d, p ):
    """
    sharpen the transition to the flat part with parameter p
    """
    w = np.copysign( np.ones( len( x ) ), b * x + c )
    return a * w * np.tanh( np.abs( b * x + c )**p )**( 1 / p ) + d

data = np.loadtxt(
    "anode_90ma_test1.txt",
    skiprows=1, delimiter=","
)

xl, yl = data[:,0], np.log10( data[:,1] )

### simple guesses for a, c and d
d0 = ( min( yl ) + max( yl ) ) / 2
a0 = ( max( yl ) - min( yl ) ) / 2
npa = np.argwhere( np.heaviside( yl - d0, 0 ) == 0 )
c0 = -xl[ npa[-1,0] ]
print ("a0, c0, d0 = ", a0, c0, d0 )

### best guess for b via differential equation
### and alternative guesses for a and d
### uses: dy/dx = u * y**2 + v * y + w
### with u = -b/a, v = 2 b / a d and w = -b/a d^2 + a b
dy = np.gradient( yl, xl )

VT = np.array([
    yl**2, yl, np.ones( len( yl ) )
])
V = np.transpose( VT )
eta = np.dot( VT, dy )
A = np.dot( VT, V )
sol = np.linalg.solve( A, eta )
print( sol )
u, v, w = sol

df = -v / 2 / u
bf = np.sqrt( u**2 * df**2 - w * u )
af = -bf / u
print( "d = ", df )
print( "b = ", bf )
print( "a = ", af )

### non-linear fit

sol, cov = curve_fit( f, xl, yl, p0=[ a0, bf, c0, d0 ] )
print( sol )
### with sharpened edges
sol2, cov2 = curve_fit( g, xl, yl, p0=np.append( sol, 1 ) )

### plotting
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )

ax.plot(
    data[:,0], np.log10( data[:,1] ),
    ls='', marker='+', label='data', alpha=0.5
)
ax.plot( data[:,0], f( data[:,0], *sol ), label="round edges" )
ax.plot( data[:,0], g( data[:,0], *sol2 ), label="sharp edges" )
ax.plot( data[:,0], f( data[:,0], af, bf, c0, df ), ls=':',label="guess" )
ax.axhline( y=d0, color='k', ls=':' )
ax.grid()
ax.legend( loc=0 )
plt.show()
```
<p>providing</p>
<pre class="lang-py prettyprint-override"><code>a0, c0, d0 =  3.9470363024506527 0.205 -7.350877976113524
[ -0.62643791  -8.42148481 -21.38742817]
d =  -6.721723517680841
b =  2.0814552335484855
a =  3.3226840415005183
[ 3.30445925  2.18844797  0.19235933 -6.7106928 ]
</code>```

and

Final non-linear fit works flawless.

Body:
I've got data of anode currents for different anode voltages. I'm trying to fit a tanh(x) curve to the resulting I-V curve using curve_fit, but I keep getting a line.

Since I'm trying to fit a curve to y against log10(x) I did the curve_fit 2 ways:

I took the log10 of the data first and fit the curve second

I fit the curve first and took the log10 of the data second.

Method 1 code and output:

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def fitfunction(v, a, b, c, d):
    return a * np.tanh(b * v + c) + d

# x data = V90
# y data = np.log10(I90)

pars, cov = curve_fit(fitfunction, V90, np.log10(I90))

plt.plot(V90, fitfunction(V90, *pars), 'r-', linewidth='3', label='Line of Best Fit')
plt.scatter(V90, np.log10(I90), marker='.', label='Data')

plt.title('Graph of Line of Best Fit of Anode Current against Anode Potential')
plt.grid(True)
plt.xlabel('Voltage (V)')
plt.ylabel('Current (A)')
plt.legend()
plt.show()

The resulting graph using the above code was:

Method 2 code and output:

pars, cov = curve_fit(fitfunction, V90, I90)
print(pars)

y = fitfunction(V90, *pars)

if any(i < 0 for i in y) == True:
    y = y + abs(min(y))

y = y[377:]
x = V90[377:]

plt.plot(x, np.log10(y), 'r-', linewidth='3', label='Line of Best Fit')
plt.scatter(V90, np.log10(I90), marker='.', label='Data')

plt.title('Graph of Line of Best Fit of Anode Current against Anode Potential')
plt.grid(True)
plt.xlabel('Voltage (V)')
plt.ylabel('Current (A)')
plt.legend()
plt.show()

The resulting graph using this code was:

I'm not quite sure why in the second method, even if I do cut off the 0 values, there is still such a drastic deviation when V90 < 0.

The part of the data that's causing problems seems to be somewhere in 2.5V-5.0V which is about 500 lines of data:

#Voltages(V) Currents(A) Af=89.9mA Vf=24.3V
2.50000,0.0003815846315912
2.50500,0.0003816979315912
2.51000,0.0003817056315912
2.51500,0.00038173013159120006
2.52000,0.00038178253159120004
2.52500,0.0003818257315912
2.53000,0.0003819050315912
2.53500,0.0003818466315912
2.54000,0.0003818978315912
2.54500,0.0003819977315912
2.55000,0.00038197953159120005
2.55500,0.00038198843159120005
2.56000,0.00038210623159120005
2.56500,0.00038209303159120005
2.57000,0.0003821845315912
2.57500,0.0003821863315912
2.58000,0.00038220063159120004
2.58500,0.0003822367315912
2.59000,0.00038230733159120005
2.59500,0.00038230853159120003
2.60000,0.00038232433159120005
2.60500,0.0003823070315912
2.61000,0.0003824262315912
2.61500,0.0003824784315912
2.62000,0.0003825377315912
2.62500,0.0003825299315912
2.63000,0.0003825463315912
2.63500,0.00038256423159120005
2.64000,0.00038260893159120006
2.64500,0.0003826748315912
2.65000,0.0003826939315912
2.65500,0.0003826620315912
2.66000,0.00038270823159120004
2.66500,0.00038275413159120003
2.67000,0.0003827898315912
2.67500,0.0003828730315912
2.68000,0.00038286673159120005
2.68500,0.00038290933159120004
2.69000,0.0003829376315912
2.69500,0.0003829943315912
2.70000,0.0003830041315912
2.70500,0.00038304703159120005
2.71000,0.0003830539315912
2.71500,0.0003830631315912
2.72000,0.0003831442315912
2.72500,0.00038314893159120005
2.73000,0.0003831841315912
2.73500,0.0003832354315912
2.74000,0.00038327293159120005
2.74500,0.0003833084315912
2.75000,0.0003833653315912
2.75500,0.0003834109315912
2.76000,0.00038340913159120004
2.76500,0.0003834842315912
2.77000,0.00038352123159120005
2.77500,0.00038353283159120005
2.78000,0.00038357873159120003
2.78500,0.00038351133159120004
2.79000,0.00038353613159120004
2.79500,0.0003836058315912
2.80000,0.00038369733159120004
2.80500,0.0003836595315912
2.81000,0.00038369343159120006
2.81500,0.0003837056315912
2.82000,0.0003837095315912
2.82500,0.0003837635315912
2.83000,0.0003838389315912
2.83500,0.00038387283159120004
2.84000,0.00038388863159120006
2.84500,0.00038390353159120004
2.85000,0.00038393663159120005
2.85500,0.00038400643159120006
2.86000,0.00038402783159120004
2.86500,0.0003840540315912
2.87000,0.00038411223159120003
2.87500,0.00038411843159120003
2.88000,0.0003841074315912
2.88500,0.0003841589315912
2.89000,0.00038417953159120005
2.89500,0.0003841864315912
2.90000,0.00038419383159120005
2.90500,0.0003842904315912
2.91000,0.0003843029315912
2.91500,0.0003842731315912
2.92000,0.0003843509315912
2.92500,0.0003843986315912
2.93000,0.00038439503159120003
2.93500,0.0003843986315912
2.94000,0.00038445253159120007
2.94500,0.0003844441315912
2.95000,0.00038448443159120005
2.95500,0.00038446503159120005
2.96000,0.00038451213159120006
2.96500,0.0003845723315912
2.97000,0.0003846322315912
2.97500,0.0003846078315912
2.98000,0.00038468173159120005
2.98500,0.0003846975315912
2.99000,0.00038470823159120004
2.99500,0.00038466083159120003
3.00000,0.00038470853159120003
3.00500,0.00038475533159120005
3.01000,0.00038481043159120003
3.01500,0.0003848238315912
3.02000,0.0003848566315912
3.02500,0.00038489833159120003
3.03000,0.0003848757315912
3.03500,0.0003849278315912
3.04000,0.0003849609315912
3.04500,0.0003849475315912
3.05000,0.0003850175315912
3.05500,0.0003850137315912
3.06000,0.0003850512315912
3.06500,0.0003851350315912
3.07000,0.0003850923315912
3.07500,0.0003851168315912
3.08000,0.00038514873159120003
3.08500,0.0003851388315912
3.09000,0.00038523033159120005
3.09500,0.00038527003159120004
3.10000,0.00038524373159120007
3.10500,0.00038534923159120005
3.11000,0.0003853215315912
3.11500,0.00038534393159120003
3.12000,0.0003853278315912
3.12500,0.0003853394315912
3.13000,0.0003853603315912
3.13500,0.0003853787315912
3.14000,0.00038547143159120003
3.14500,0.0003854083315912
3.15000,0.00038548693159120006
3.15500,0.00038548843159120003
3.16000,0.00038548723159120005
3.16500,0.0003855608315912
3.17000,0.0003855918315912
3.17500,0.0003855635315912
3.18000,0.0003856055315912
3.18500,0.00038563923159120006
3.19000,0.0003856708315912
3.19500,0.00038566013159120003
3.20000,0.0003857125315912
3.20500,0.00038573913159120003
3.21000,0.00038580913159120005
3.21500,0.00038580463159120003
3.22000,0.0003858180315912
3.22500,0.0003858449315912
3.23000,0.00038583533159120004
3.23500,0.00038587913159120006
3.24000,0.0003858967315912
3.24500,0.0003858645315912
3.25000,0.0003859590315912
3.25500,0.0003859778315912
3.26000,0.00038596353159120006
3.26500,0.00038597303159120005
3.27000,0.00038599453159120006
3.27500,0.0003860436315912
3.28000,0.0003860785315912
3.28500,0.0003860782315912
3.29000,0.00038609913159120006
3.29500,0.0003861384315912
3.30000,0.0003861640315912
3.30500,0.0003861927315912
3.31000,0.0003862037315912
3.31500,0.0003861900315912
3.32000,0.0003862180315912
3.32500,0.00038625343159120004
3.33000,0.00038624963159120004
3.33500,0.0003862892315912
3.34000,0.0003863312315912
3.34500,0.00038631103159120006
3.35000,0.00038635183159120004
3.35500,0.00038638793159120004
3.36000,0.0003863819315912
3.36500,0.0003864013315912
3.37000,0.00038648713159120004
3.37500,0.0003864919315912
3.38000,0.00038650973159120005
3.38500,0.0003865127315912
3.39000,0.0003865819315912
3.39500,0.0003865768315912
3.40000,0.00038658543159120006
3.40500,0.00038663733159120003
3.41000,0.00038662423159120006
3.41500,0.0003866617315912
3.42000,0.00038666563159120003
3.42500,0.0003866883315912
3.43000,0.00038664123159120006
3.43500,0.00038672403159120005
3.44000,0.0003867511315912
3.44500,0.00038671243159120005
3.45000,0.00038679173159120005
3.45500,0.00038677233159120004
3.46000,0.0003867619315912
3.46500,0.0003867944315912
3.47000,0.00038678993159120003
3.47500,0.0003868668315912
3.48000,0.00038685753159120004
3.48500,0.0003868131315912
3.49000,0.0003868772315912
3.49500,0.00038690763159120005
3.50000,0.00038699083159120007
3.50500,0.0003869496315912
3.51000,0.0003869472315912
3.51500,0.0003870432315912
3.52000,0.0003870340315912
3.52500,0.0003870396315912
3.53000,0.0003870617315912
3.53500,0.0003870569315912
3.54000,0.00038713173159120003
3.54500,0.00038711033159120005
3.55000,0.00038715503159120006
3.55500,0.00038715383159120003
3.56000,0.0003871439315912
3.56500,0.00038713713159120003
3.57000,0.00038718153159120005
3.57500,0.00038722833159120007
3.58000,0.0003871866315912
3.58500,0.0003872426315912
3.59000,0.0003872560315912
3.59500,0.00038726643159120005
3.60000,0.0003872912315912
3.60500,0.0003872947315912
3.61000,0.0003873543315912
3.61500,0.00038739643159120004
3.62000,0.0003873946315912
3.62500,0.0003874357315912
3.63000,0.00038740023159120003
3.63500,0.0003874494315912
3.64000,0.00038744203159120003
3.64500,0.00038750963159120004
3.65000,0.00038753823159120004
3.65500,0.0003876038315912
3.66000,0.0003876062315912
3.66500,0.0003876419315912
3.67000,0.00038765513159120006
3.67500,0.00038764313159120003
3.68000,0.0003876282315912
3.68500,0.0003876902315912
3.69000,0.0003876959315912
3.69500,0.0003877227315912
3.70000,0.0003877594315912
3.70500,0.0003877594315912
3.71000,0.00038777433159120005
3.71500,0.0003877194315912
3.72000,0.0003878219315912
3.72500,0.00038785143159120005
3.73000,0.0003878336315912
3.73500,0.00038787443159120003
3.74000,0.0003878839315912
3.74500,0.00038790993159120004
3.75000,0.0003879575315912
3.75500,0.0003880106315912
3.76000,0.00038798413159120003
3.76500,0.0003880049315912
3.77000,0.0003880705315912
3.77500,0.00038805773159120003
3.78000,0.0003880672315912
3.78500,0.00038812413159120007
3.79000,0.0003881292315912
3.79500,0.00038814233159120004
3.80000,0.0003881444315912
3.80500,0.0003881864315912
3.81000,0.0003881593315912
3.81500,0.0003881632315912
3.82000,0.0003881823315912
3.82500,0.00038825473159120004
3.83000,0.0003882901315912
3.83500,0.00038829763159120003
3.84000,0.0003882907315912
3.84500,0.00038834053159119997
3.85000,0.0003883670315912
3.85500,0.0003883939315912
3.86000,0.0003883834315912
3.86500,0.0003883804315912
3.87000,0.0003884391315912
3.87500,0.0003884344315912
3.88000,0.0003884836315912
3.88500,0.00038849013159120003
3.89000,0.00038856043159120004
3.89500,0.0003885616315912
3.90000,0.00038857123159120004
3.90500,0.0003886108315912
3.91000,0.0003886305315912
3.91500,0.0003886633315912
3.92000,0.00038866483159119997
3.92500,0.0003886671315912
3.93000,0.00038875213159120003
3.93500,0.0003887288315912
3.94000,0.0003887735315912
3.94500,0.0003887700315912
3.95000,0.00038872023159120005
3.95500,0.00038880303159120004
3.96000,0.0003888695315912
3.96500,0.0003888597315912
3.97000,0.00038894643159120005
3.97500,0.0003889258315912
3.98000,0.00038898183159120003
3.98500,0.0003889664315912
3.99000,0.0003889261315912
3.99500,0.00038897353159120007
4.00000,0.0003890727315912
4.00500,0.0003890072315912
4.01000,0.00038906323159120003
4.01500,0.00038904213159120005
4.02000,0.00038912523159120003
4.02500,0.0003891359315912
4.03000,0.0003891619315912
4.03500,0.0003891288315912
4.04000,0.0003892173315912
4.04500,0.0003891940315912
4.05000,0.0003892384315912
4.05500,0.0003893127315912
4.06000,0.0003893159315912
4.06500,0.0003892709315912
4.07000,0.0003892769315912
4.07500,0.0003892754315912
4.08000,0.00038935383159120003
4.08500,0.00038933983159120003
4.09000,0.00038941553159120004
4.09500,0.00038942323159120006
4.10000,0.0003894319315912
4.10500,0.0003895219315912
4.11000,0.0003895454315912
4.11500,0.00038950883159120003
4.12000,0.0003896175315912
4.12500,0.00038962773159120003
4.13000,0.0003896372315912
4.13500,0.0003896017315912
4.14000,0.0003896599315912
4.14500,0.00038967243159120004
4.15000,0.00038972243159120007
4.15500,0.00038967923159120003
4.16000,0.0003897564315912
4.16500,0.00038985093159120003
4.17000,0.0003898157315912
4.17500,0.0003898777315912
4.18000,0.00038985683159120004
4.18500,0.00038996063159120003
4.19000,0.00038990393159120005
4.19500,0.0003898995315912
4.20000,0.00039002143159120006
4.20500,0.0003900357315912
4.21000,0.00039002343159120004
4.21500,0.00039006813159120005
4.22000,0.00039010213159120004
4.22500,0.0003901114315912
4.23000,0.0003901018315912
4.23500,0.0003901289315912
4.24000,0.0003902195315912
4.24500,0.0003902076315912
4.25000,0.00039021833159120004
4.25500,0.0003902306315912
4.26000,0.00039023533159120003
4.26500,0.00039031403159120004
4.27000,0.0003903662315912
4.27500,0.00039037843159120004
4.28000,0.00039042283159120006
4.28500,0.0003903867315912
4.29000,0.00039044223159120006
4.29500,0.0003904630315912
4.30000,0.0003904529315912
4.30500,0.0003904729315912
4.31000,0.00039054473159120005
4.31500,0.0003905533315912
4.32000,0.0003905974315912
4.32500,0.0003905998315912
4.33000,0.0003906898315912
4.33500,0.00039066933159120004
4.34000,0.00039072833159120004
4.34500,0.00039076823159120004
4.35000,0.0003907929315912
4.35500,0.00039083443159120007
4.36000,0.0003908636315912
4.36500,0.00039086923159120006
4.37000,0.00039087253159120005
4.37500,0.0003908964315912
4.38000,0.0003909136315912
4.38500,0.00039098463159120006
4.39000,0.0003910287315912
4.39500,0.0003910355315912
4.40000,0.0003910477315912
4.40500,0.0003910922315912
4.41000,0.0003910749315912
4.41500,0.0003911458315912
4.42000,0.0003911830315912
4.42500,0.00039118783159120007
4.43000,0.00039116373159120004
4.43500,0.0003912555315912
4.44000,0.0003912483315912
4.44500,0.00039127843159120006
4.45000,0.0003914009315912
4.45500,0.0003913550315912
4.46000,0.00039139433159120007
4.46500,0.0003914075315912
4.47000,0.0003914602315912
4.47500,0.0003914307315912
4.48000,0.0003914930315912
4.48500,0.0003914924315912
4.49000,0.00039153143159120004
4.49500,0.00039155053159120004
4.50000,0.0003916068315912
4.50500,0.0003916372315912
4.51000,0.00039167213159120004
4.51500,0.00039174183159120006
4.52000,0.00039177053159120004
4.52500,0.00039176813159120003
4.53000,0.00039181583159120004
4.53500,0.0003918697315912
4.54000,0.00039187893159120003
4.54500,0.0003918822315912
4.55000,0.0003919370315912
4.55500,0.0003919138315912
4.56000,0.0003919716315912
4.56500,0.00039199283159120006
4.57000,0.00039201103159120003
4.57500,0.00039209833159120004
4.58000,0.00039208733159120003
4.58500,0.0003921516315912
4.59000,0.0003921233315912
4.59500,0.00039217223159120003
4.60000,0.0003922100315912
4.60500,0.0003922246315912
4.61000,0.0003922810315912
4.61500,0.00039230933159120006
4.62000,0.00039232663159120005
4.62500,0.0003923683315912
4.63000,0.00039239963159120006
4.63500,0.0003924449315912
4.64000,0.00039247533159120007
4.64500,0.0003924917315912
4.65000,0.0003925414315912
4.65500,0.0003925510315912
4.66000,0.0003926022315912
4.66500,0.00039258413159120003
4.67000,0.0003926276315912
4.67500,0.0003927253315912
4.68000,0.0003927191315912
4.68500,0.0003926767315912
4.69000,0.0003927778315912
4.69500,0.0003928117315912
4.70000,0.0003928255315912
4.70500,0.00039284933159120005
4.71000,0.00039287673159120007
4.71500,0.0003929137315912
4.72000,0.00039292833159120004
4.72500,0.00039297333159120005
4.73000,0.00039305613159120004
4.73500,0.00039298043159120003
4.74000,0.00039306123159120004
4.74500,0.00039308923159120005
4.75000,0.0003931020315912
4.75500,0.0003931107315912
4.76000,0.00039316343159120004
4.76500,0.00039320483159120006
4.77000,0.00039318313159120003
4.77500,0.0003932430315912
4.78000,0.00039328623159120006
4.78500,0.0003932948315912
4.79000,0.0003933348315912
4.79500,0.0003933708315912
4.80000,0.0003934275315912
4.80500,0.0003934933315912
4.81000,0.0003933869315912
4.81500,0.00039350763159120005
4.82000,0.00039353273159120004
4.82500,0.0003935321315912
4.83000,0.0003935798315912
4.83500,0.0003935836315912
4.84000,0.0003936641315912
4.84500,0.00039368763159120006
4.85000,0.00039365193159120003
4.85500,0.00039369873159120005
4.86000,0.0003937326315912
4.86500,0.00039382033159120005
4.87000,0.0003938480315912
4.87500,0.00039383903159120003
4.88000,0.0003938897315912
4.88500,0.0003940000315912
4.89000,0.0003939517315912
4.89500,0.0003940104315912
4.90000,0.0003940086315912
4.90500,0.0003939877315912
4.91000,0.00039403513159120006
4.91500,0.00039411413159120006
4.92000,0.0003941618315912
4.92500,0.00039414903159120003
4.93000,0.00039421843159120006
4.93500,0.00039421603159120006
4.94000,0.00039430313159120005
4.94500,0.0003943028315912
4.95000,0.0003943370315912
4.95500,0.0003943808315912
4.96000,0.0003943910315912
4.96500,0.00039442853159120004
4.97000,0.0003944494315912
4.97500,0.00039449833159120004
4.98000,0.00039456143159120004
4.98500,0.0003945686315912
4.99000,0.0003945677315912
4.99500,0.0003946011315912

Body:
I have to confess that I do not see any particular problem in the data and in fitting it. I'd actually say that any problems likely occur due to problems with initial values. The outliers are negligible, but one could try to use robust fitting. Start values can be guessed automatically like this:

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

def f( x, a, b, c, d ):
    return a * np.tanh( b * x + c ) + d

def g( x, a, b, c, d, p ):
    """
    sharpen the transition to the flat part with parameter p
    """
    w = np.copysign( np.ones( len( x ) ), b * x + c )
    return a * w * np.tanh( np.abs( b * x + c )**p )**( 1 / p ) + d

data = np.loadtxt(
    "anode_90ma_test1.txt",
    skiprows=1, delimiter=","
)

xl, yl = data[:,0], np.log10( data[:,1] )

### simple guesses for a, c and d
d0 = ( min( yl ) + max( yl ) ) / 2
a0 = ( max( yl ) - min( yl ) ) / 2
npa = np.argwhere( np.heaviside( yl - d0, 0 ) == 0 )
c0 = -xl[ npa[-1,0] ]
print ("a0, c0, d0 = ", a0, c0, d0 )

### best guess for b via differential equation
### and alternative guesses for a and d
### uses: dy/dx = u * y**2 + v * y + w
### with u = -b/a, v = 2 b / a d and w = -b/a d^2 + a b
dy = np.gradient( yl, xl )

VT = np.array([
    yl**2, yl, np.ones( len( yl ) )
])
V = np.transpose( VT )
eta = np.dot( VT, dy )
A = np.dot( VT, V )
sol = np.linalg.solve( A, eta )
print( sol )
u, v, w = sol

df = -v / 2 / u
bf = np.sqrt( u**2 * df**2 - w * u )
af = -bf / u
print( "d = ", df )
print( "b = ", bf )
print( "a = ", af )

### non-linear fit

sol, cov = curve_fit( f, xl, yl, p0=[ a0, bf, c0, d0 ] )
print( sol )
### with sharpened edges
sol2, cov2 = curve_fit( g, xl, yl, p0=np.append( sol, 1 ) )

### plotting
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )

ax.plot(
    data[:,0], np.log10( data[:,1] ),
    ls='', marker='+', label='data', alpha=0.5
)
ax.plot( data[:,0], f( data[:,0], *sol ), label="round edges" )
ax.plot( data[:,0], g( data[:,0], *sol2 ), label="sharp edges" )
ax.plot( data[:,0], f( data[:,0], af, bf, c0, df ), ls=':',label="guess" )
ax.axhline( y=d0, color='k', ls=':' )
ax.grid()
ax.legend( loc=0 )
plt.show()

providing

a0, c0, d0 =  3.9470363024506527 0.205 -7.350877976113524
[ -0.62643791  -8.42148481 -21.38742817]
d =  -6.721723517680841
b =  2.0814552335484855
a =  3.3226840415005183
[ 3.30445925  2.18844797  0.19235933 -6.7106928 ]

and

Final non-linear fit works flawless.


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: Join DataFrames based on multiple columns

Body:
I want to join two tables. The one is a DataTable DT_1 and the other a DataFrame DF_2. The columns name and value in DT_1 are related to the rows and columns of the DF_2. The output would be the DT_1 with a new column expr consists of the corresponding values sourced from the DF_2.

View(DT_1)
CHR        POS           ID         name   value
<dbl>     <chr>        <chr>       <chr>   <dbl>
 1     1 31439_T_A ENSG00000232325 indv1     1
 2     1 31439_T_A ENSG00000232325 indv2     1
 3     1 31439_T_A ENSG00000232325 indv3     2
 4     1 31504_G_A ENSG00000242474 indv1     2
 5     1 31504_G_A ENSG00000242474 indv2     1
 6     1 31504_G_A ENSG00000242474 indv3     1
 7     1 34713_A_C ENSG00000242474 indv1     1
 8     1 34713_A_C ENSG00000242474 indv2     0
 9     1 34713_A_C ENSG00000242474 indv3     1
10     1 34918_C_T ENSG00000242474 indv1     1
11     1 34918_C_T ENSG00000242474 indv2     0
12     1 34918_C_T ENSG00000242474 indv3     1
13     1 35119_G_A ENSG00000239715 indv1     0
14     1 35119_G_A ENSG00000239715 indv2     0
15     1 35119_G_A ENSG00000239715 indv3     1

view(DF_2)
name    ENSG00000232325  ENSG00000242474  ENSG00000239715
indv1       0.1                0.4              0.22
indv2       0.3              -0.003            0.0001
indv3      -0.02               0.1              0.1

The desired output:

> OUTPUT
CHR       POS            ID         name   value  expr
<dbl>    <chr>          <chr>      <chr>   <dbl> <dbl>
 1     1 31439_T_A ENSG00000232325 indv1     1    0.1
 2     1 31439_T_A ENSG00000232325 indv2     1    0.3
 3     1 31439_T_A ENSG00000232325 indv3     2   -0.02
 4     1 31504_G_A ENSG00000242474 indv1     2    0.4
 5     1 31504_G_A ENSG00000242474 indv2     1   -0.003
 6     1 31504_G_A ENSG00000242474 indv3     1    0.1
 7     1 34713_A_C ENSG00000242474 indv1     1    0.4
 8     1 34713_A_C ENSG00000242474 indv2     0   -0.003
 9     1 34713_A_C ENSG00000242474 indv3     1    0.1
10     1 34918_C_T ENSG00000242474 indv1     1    0.4
11     1 34918_C_T ENSG00000242474 indv2     0   -0.003
12     1 34918_C_T ENSG00000242474 indv3     1    0.1
13     1 35119_G_A ENSG00000239715 indv1     0    0.22
14     1 35119_G_A ENSG00000239715 indv2     0   0.0001
15     1 35119_G_A ENSG00000239715 indv3     1    0.1

thanks!

Body:
library(tidyverse)

# create example data
DF_1 <- tribble(
  ~CHR, ~POS, ~ID, ~name, ~value,
  1, "1 31439_T_A", "ENSG00000232325", "indv1", 1,
  2, "1 31439_T_A", "ENSG00000232325", "indv2", 1,
  3, "1 31439_T_A", "ENSG00000232325", "indv3", 2,
)
DF_2 <- tribble(
  ~name, ~ENSG00000232325, ~ENSG00000242474, ~ENSG00000239715,
  "indv1", 0.1, 0.4, 0.22,
  "indv2", 0.3, -0.003, 0.0001,
  "indv3", -0.02, 0.1, 0.1
)

DF_2 %>%
  pivot_longer(-name, names_to = "ID", values_to = "expr") %>%
  inner_join(DF_1)
#> Joining, by = c("name", "ID")
#> # A tibble: 3 x 6
#>   name  ID               expr   CHR POS         value
#>   <chr> <chr>           <dbl> <dbl> <chr>       <dbl>
#> 1 indv1 ENSG00000232325  0.1      1 1 31439_T_A     1
#> 2 indv2 ENSG00000232325  0.3      2 1 31439_T_A     1
#> 3 indv3 ENSG00000232325 -0.02     3 1 31439_T_A     2

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
Curl request to a Kubernetes cluster type service
I am trying to send a curl request to a Kubernetes ClusterType service. Is there any way to perform curl requests to service?

I am deploying an application with Blue/Green deployment. So here need to verify the Blue version is properly working or not. So decide to send a curl request to the blue version. When I get 200 status, I will route all traffic to this version.

But now am facing that send curl request to the new version(Blue version) of the application.

答:
You can't send a curl request to ClusterType Service, unless you are inside the cluster, you can run a pod to do that e.g

```<code>kubectl run --rm --image nginx -i -- curl 'http://clusterip/'
</code>```

This will run a temp pod  to run your command and die afterward.

Body:
You can't send a curl request to ClusterType Service, unless you are inside the cluster, you can run a pod to do that e.g

kubectl run --rm --image nginx -i -- curl 'http://clusterip/'

This will run a temp pod  to run your command and die afterward.


问:
Setting umask in Git / Gitolite
I have set up Git and Gitolite, and at some point I recall having seen an "umask" setting, in one of the configuration files. Does this set the permissions for all files I sync using Git? That is exactly what I need. Where can I find it? </p>

答:
The umask settings in Gitolite are there for changing the umask for newly created repos (and not about the files managed in versions by those repos).

See gitolite.rc doc:

$REPO_UMASK, octal, default 0077

The default UMASK that gitolite uses makes all the repos and their contents have rwx------ permissions. People who want to run gitweb realise that this will not do.

The correct way to deal with this is to give this variable a value like 0027 (note the syntax: the leading 0 is required), and then make the user running the webserver (apache, www-data, whatever) a member of the 'git' group.

If you've already installed gitolite then existing files will have to be fixed up manually (for a umask or 0027, that would be chmod -R g+rX). This is because umask only affects permissions on newly created files, not existing ones.

This settings is similar to the one use when you create directly a git repo (without gitolite):

```<code>core.sharedRepository
</code>```

When group (or true), the repository is made shareable between several users in a group (making sure all the files and objects are group-writable).

When all (or world or everybody), the repository will be readable by all users, additionally to being group-shareable.

When umask (or false), git will use permissions reported by umask.

See also "How do I share a Git repository with multiple users on a machine?" for more.

When you have conflicts between platforms relative to permissions, you also have the option to "instruct git to ignore file permissions changes" (git config core.fileMode false).

Update: This answer covers gitolite 2. With gitolite 3 the setting changed from $REPO_UMASK to just $UMASK.

ContentLicense: CC BY-SA 3.0

Title: Setting umask in Git / Gitolite

Body:
The umask settings in Gitolite are there for changing the umask for newly created repos (and not about the files managed in versions by those repos).

See gitolite.rc doc:

$REPO_UMASK, octal, default 0077

The default UMASK that gitolite uses makes all the repos and their contents have rwx------ permissions. People who want to run gitweb realise that this will not do.

The correct way to deal with this is to give this variable a value like 0027 (note the syntax: the leading 0 is required), and then make the user running the webserver (apache, www-data, whatever) a member of the 'git' group.

If you've already installed gitolite then existing files will have to be fixed up manually (for a umask or 0027, that would be chmod -R g+rX). This is because umask only affects permissions on newly created files, not existing ones.

This settings is similar to the one use when you create directly a git repo (without gitolite):

core.sharedRepository

When group (or true), the repository is made shareable between several users in a group (making sure all the files and objects are group-writable).

When all (or world or everybody), the repository will be readable by all users, additionally to being group-shareable.

When umask (or false), git will use permissions reported by umask.

See also "How do I share a Git repository with multiple users on a machine?" for more.

When you have conflicts between platforms relative to permissions, you also have the option to "instruct git to ignore file permissions changes" (git config core.fileMode false).

Update: This answer covers gitolite 2. With gitolite 3 the setting changed from $REPO_UMASK to just $UMASK.


问:
How to remove one value from a key in localstorage that has many values?
I've seen this question asked before but the solutions didn't help me hence why i've asked it again.

Currently, I am storing values into an array and that array is getting stored into localstorage.

This is the object

```<code>data.items -

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}
</code>```

I have mapped through this and used 'name' as the value. I am calling this value through a button using this function

```<code>const favs = [];

  function checkId(e) {
    if (e.target.value !== ""){
      if (!favs.includes(e.target.value)){
      favs.push(e.target.value);
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      }
    }

    }
</code>```

and to remove the value from localstorage I am using this function.

```<code>function removeId(e, value) {
    if (e.target.value !== "") {

      favs.pop(e.target.value);
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value];
      localStorage.setItem("name", JSON.stringify(stored));
      console.log(stored);

    }
  }
</code>```

Although the value is being removed from the array, it is not being removed from localstorage.

side note - I am calling this function with a separate button.

console log

```<code>array (item is gone)
[]

localstorage (the value is still there)
[
    "Spiral-Up-Cut-Router-Bit"
]
</code>```

But if I select another item to be added to localstorage, then the previous item gets removed.

```<code>UNFAVORITE - FUNCTION REMOVEid
[
        "Spiral-Up-Cut-Router-Bit"
    ]

 NEW FAVORITE - FUNCTION NEWId

[
    "graphqless"
]
</code>```

I hope this makes sense, I tried to add detail to it as best as possible.

答:
Try to use localStorage.removeItem method to remove item from storage:

```<code>function removeId(e, value) {
   if (e.target.value !== "") {
      favs.pop();
      // other code here

      localStorage.removeItem('name'); // method to remove item from storage

   }
}
</code>```

UPDATE:

If an item is removed from array and we want to set this updated value to localstorage, then we can just update this value:

```<code>function removeId(e, value) {
   if (e.target.value !== "") {
      favs.pop();
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value]; // this code looks very fishy - charlietfl

      localStorage.setItem("name", JSON.stringify(favs));

      console.log(stored);
   }
}
</code>```

Body:
I've seen this question asked before but the solutions didn't help me hence why i've asked it again.

Currently, I am storing values into an array and that array is getting stored into localstorage.

This is the object

data.items -

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}

I have mapped through this and used 'name' as the value. I am calling this value through a button using this function

const favs = [];

  function checkId(e) {
    if (e.target.value !== ""){
      if (!favs.includes(e.target.value)){
      favs.push(e.target.value);
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      }
    }

    }

and to remove the value from localstorage I am using this function.

function removeId(e, value) {
    if (e.target.value !== "") {

      favs.pop(e.target.value);
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value];
      localStorage.setItem("name", JSON.stringify(stored));
      console.log(stored);

    }
  }

Although the value is being removed from the array, it is not being removed from localstorage.

side note - I am calling this function with a separate button.

console log

array (item is gone)
[]

localstorage (the value is still there)
[
    "Spiral-Up-Cut-Router-Bit"
]

But if I select another item to be added to localstorage, then the previous item gets removed.

UNFAVORITE - FUNCTION REMOVEid
[
        "Spiral-Up-Cut-Router-Bit"
    ]

 NEW FAVORITE - FUNCTION NEWId

[
    "graphqless"
]

I hope this makes sense, I tried to add detail to it as best as possible.

Body:
Try to use localStorage.removeItem method to remove item from storage:

function removeId(e, value) {
   if (e.target.value !== "") {
      favs.pop();
      // other code here

      localStorage.removeItem('name'); // method to remove item from storage

   }
}

UPDATE:

If an item is removed from array and we want to set this updated value to localstorage, then we can just update this value:

function removeId(e, value) {
   if (e.target.value !== "") {
      favs.pop();
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value]; // this code looks very fishy - charlietfl

      localStorage.setItem("name", JSON.stringify(favs));

      console.log(stored);
   }
}


问:
'for' loop through form fields and excluding one of the fields with 'if'
The problem I'm struggling with is as follows:

I have:

```<code>{% for field in form %}
    {{ field }}
{% end for %}
</code>```

What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:

```<code>{% for field in form%}
    {% if field == title %}
    {% else %}
        {{ field }}
    {% endif %}
{% endfor %}
</code>```

Is it possible? I have to many fields to write them one by one and only one or two to exclude.

Thank you for any tips.

BR,
Czlowiekwidmo.

答:
You might be a lot happier creating a subclass of the form, excluding the offending field.
See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance</p>

```<code>class SmallerForm( MyForm ):
    class Meta(MyForm.Meta):
        exclude = [ title ]
</code>```

OwnerDisplayName: Czlowiekwidmo

ContentLicense: CC BY-SA 2.5

Body:
The problem I'm struggling with is as follows:

I have:

{% for field in form %}
    {{ field }}
{% end for %}

What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:

{% for field in form%}
    {% if field == title %}
    {% else %}
        {{ field }}
    {% endif %}
{% endfor %}

Is it possible? I have to many fields to write them one by one and only one or two to exclude.

Thank you for any tips.

BR,
Czlowiekwidmo.

Body:
You might be a lot happier creating a subclass of the form, excluding the offending field.
See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance

class SmallerForm( MyForm ):
    class Meta(MyForm.Meta):
        exclude = [ title ]


问:
Zoom in and out of image on click using event listeners
I would like to create a function that takes in an array of images, checks whether an image has been clicked. If an image is clicked Zooms into the image, if the same image is clicked again, it would zoom out of the image.

This is what I have written

```<code>let imagesArr = document.querySelectorAll('img')
let isZoomed = false;
function rotateImage (e,isZoomed) {
    isZoomed = false ?
    e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1.5)";
            event.stopImmediatePropagation();
        })
    }) : e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1)";
            event.stopImmediatePropagation();
        })
    })
    isZoomed = true;
}
rotateImage(imagesArr,isZoomed);
</code>```

I an trying to check whether the image is already zoomed (true, false) and zoom/zoom out based on this condition. Not getting an error, but my function does not work (nothing happens when I click an image)

答:
Delegate

use a class

document.getElementById('container').addEventListener('click', function(e) {
  const tgt = e.target;
  tgt.classList.toggle('zoomed')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container img.zoomed {
  transform: scale(1.5);
}</code>```

```

Body:
I would like to create a function that takes in an array of images, checks whether an image has been clicked. If an image is clicked Zooms into the image, if the same image is clicked again, it would zoom out of the image.

This is what I have written

let imagesArr = document.querySelectorAll('img')
let isZoomed = false;
function rotateImage (e,isZoomed) {
    isZoomed = false ?
    e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1.5)";
            event.stopImmediatePropagation();
        })
    }) : e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1)";
            event.stopImmediatePropagation();
        })
    })
    isZoomed = true;
}
rotateImage(imagesArr,isZoomed);

I an trying to check whether the image is already zoomed (true, false) and zoom/zoom out based on this condition. Not getting an error, but my function does not work (nothing happens when I click an image)

Body:
Delegate

use a class

document.getElementById('container').addEventListener('click', function(e) {
  const tgt = e.target;
  tgt.classList.toggle('zoomed')
})

#container img.zoomed {
  transform: scale(1.5);
}

<div id="container">
  <img src="https://assets.stickpng.com/images/58afd6b70187e59a7d8a8f1c.png" />
  <img src="https://assets.stickpng.com/images/58afd6b70187e59a7d8a8f1c.png" />
  <img src="https://assets.stickpng.com/images/58afd6b70187e59a7d8a8f1c.png" />
</div>


问:
I have the correct credentials but my emails wont go through using flask_mail
I am trying to use flask_mail to send emails with Gmail but for some reason, my emails won't go through.
I successfully manage to login to my Gmail account just to ensure that my password is correct.

The function looks like the following:

```<code>def send_reset_email(user):
    token = user.get_reset_token()

    msg = Message('Password reset request', sender='myemail@gmail.com', recipients=['anotheremail@example.com'])
    msg.body = f'''To reset your password visit the following link:
{url_for('reset_token', token=token, _external=True)}

If you did not make this request simply ignore this email and no changes will be made
    '''
    mail.send(msg)
</code>```

Inside my init.py I have the following configurations for flask mail:

from flask_mail import Mail

######## EMAIL CONFIURATION ##########
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_POST'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'myemail@gmail.com'
app.config['MAIL_PASSWORD'] = 'mygmailpassword'

mail = Mail(app)
```

<p>When I press the button to send the email I see the following error:</p>

```smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials v13sm322058edy.8 - gsmtp')
```

Note: I already went to my Gmail settings and disabled less secure apps

How do I use flask-mail to send emails?

EDITED: The answer of this link does not answer my question because I still see the same error. I changed my mail server to smtp.gmail.com but nothing.

答:
try to take as MAIL_USERNAME the part of your Gmail address before @gmail.com is your Google account username!!</p>
```<code>app.config['MAIL_USERNAME'] = 'myemail'
</code>```

Body:
I am trying to use flask_mail to send emails with Gmail but for some reason, my emails won't go through.
I successfully manage to login to my Gmail account just to ensure that my password is correct.

The function looks like the following:

def send_reset_email(user):
    token = user.get_reset_token()

    msg = Message('Password reset request', sender='myemail@gmail.com', recipients=['anotheremail@example.com'])
    msg.body = f'''To reset your password visit the following link:
{url_for('reset_token', token=token, _external=True)}

If you did not make this request simply ignore this email and no changes will be made
    '''
    mail.send(msg)

Inside my init.py I have the following configurations for flask mail:

from flask_mail import Mail

######## EMAIL CONFIURATION ##########
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_POST'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'myemail@gmail.com'
app.config['MAIL_PASSWORD'] = 'mygmailpassword'

mail = Mail(app)

When I press the button to send the email I see the following error:

smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials v13sm322058edy.8 - gsmtp')

Note: I already went to my Gmail settings and disabled less secure apps

How do I use flask-mail to send emails?

EDITED: The answer of this link does not answer my question because I still see the same error. I changed my mail server to smtp.gmail.com but nothing.

Body:
try to take as MAIL_USERNAME the part of your Gmail address before @gmail.com is your Google account username!!

app.config['MAIL_USERNAME'] = 'myemail'


问:
typeof object of array of object in typescript?
How do I replace any below with options's object shape below?

```<code>interface selectComponentProps {
  options: {
    label: string;
    value: string;
  }[];
}

const SelectComponent: React.FC<selectComponentProps> = ({
   options,
}) => {
  const handleChange = (selectedOption: any) => { //here

  };

  return (
    <Select
      options={options}
    />
  );
};
</code>```

答:
Option 1.

```<code>const handleChange = (selectedOption: typeof options[0]) => { //here

};
</code>```

Option 2.

```<code>interface Option {
  label: string;
  value: string;
}
interface selectComponentProps {
  options: Option[];
}
const handleChange = (selectedOption: Option) => { //here

};
</code>```

Body:
How do I replace any below with options's object shape below?

interface selectComponentProps {
  options: {
    label: string;
    value: string;
  }[];
}

const SelectComponent: React.FC<selectComponentProps> = ({
   options,
}) => {
  const handleChange = (selectedOption: any) => { //here

  };

  return (
    <Select
      options={options}
    />
  );
};

Body:
Option 1.

const handleChange = (selectedOption: typeof options[0]) => { //here

};

Option 2.

interface Option {
  label: string;
  value: string;
}
interface selectComponentProps {
  options: Option[];
}
const handleChange = (selectedOption: Option) => { //here

};


问:
CSV - how to fix encoding issues
I have a csv file, which says it has UTF-8 encoding (as per Notepad++), but it's obviously not correct and when I try to decode it using other typical encoding, it does not work and it is still not readable.

I just wanted to ask for an advice, if there is a way, how to fix the encoding issues?
I've also tried to detect the econding via Python, but it says UTF-8 as well

```<code>with open("data.csv", 'rb') as rawdata:
    result = chardet.detect(rawdata.read(100000))

# check what the character encoding might be
print(result)
</code>```

Example:

```<code>Location
Switzerland Â» Lake Geneva Â» VÃ©senaz
Germany Â» BÃ¶nningstedt
Switzerland Â» Lake of Zurich Â» StÃ¤fa ZH
Denmark Â» Svendborg
Germany Â» Bayern Â» MÃ¼nchen
Switzerland Â» Lake Constance Â» Uttwil
Switzerland Â» Neuenburgersee Â» Yvonand
Denmark Â» Svendborg
Germany Â» Bayern Â» Boote+service Oberbayern
Italy Â» Dormelletto
Switzerland Â» Seengen
Switzerland Â» Lake of Zurich Â» StÃ¤fa am ZÃ¼richsee
Italy Â» Lake Garda Â» Moniga del Garda (BS)
Switzerland Â» Zugersee Â» Neuheim
Switzerland Â» VierwaldstÃ¤ttersee Â» 6004
Switzerland Â» Safenwil
Switzerland Â» Lake Constance Â» Uttwil
Denmark Â» Svendborg
"France Â» MARTGUES, MARTIGUES"
Germany Â» Bayern Â» Forchheim/Ofr.
Germany Â» Bayern Â» MÃ¼nchen
Switzerland Â» Luganersee Â» Caslano
Germany Â» Nordrhein-Westfalen Â» WSC Hopp / MÃ¶nchengladbach
"Germany Â» BOOTSSERVICE ENK IN TREIS KARDEN, BOOTSSERVICE ENK"
</code>```

答:
The file is correctly encode as UTF-8. But you later display it as UTF-8 on a system that would expect Latin1 or cp1252 encoding.

Here is an evidence:

```<code>t = '''Location
Switzerland Â» Lake Geneva Â» VÃ©senaz
Germany Â» BÃ¶nningstedt
Switzerland Â» Lake of Zurich Â» StÃ¤fa ZH
Denmark Â» Svendborg
Germany Â» Bayern Â» MÃ¼nchen
Switzerland Â» Lake Constance Â» Uttwil
Switzerland Â» Neuenburgersee Â» Yvonand
Denmark Â» Svendborg
Germany Â» Bayern Â» Boote+service Oberbayern
Italy Â» Dormelletto
Switzerland Â» Seengen
Switzerland Â» Lake of Zurich Â» StÃ¤fa am ZÃ¼richsee
Italy Â» Lake Garda Â» Moniga del Garda (BS)
Switzerland Â» Zugersee Â» Neuheim
Switzerland Â» VierwaldstÃ¤ttersee Â» 6004
Switzerland Â» Safenwil
Switzerland Â» Lake Constance Â» Uttwil
Denmark Â» Svendborg
"France Â» MARTGUES, MARTIGUES"
Germany Â» Bayern Â» Forchheim/Ofr.
Germany Â» Bayern Â» MÃ¼nchen
Switzerland Â» Luganersee Â» Caslano
Germany Â» Nordrhein-Westfalen Â» WSC Hopp / MÃ¶nchengladbach
"Germany Â» BOOTSSERVICE ENK IN TREIS KARDEN, BOOTSSERVICE ENK"
'''
print(t.encode('latin1').decode())
</code>```

On my unicode enabled systems it gives as expected:

```<code>Location
Switzerland » Lake Geneva » Vésenaz
Germany » Bönningstedt
Switzerland » Lake of Zurich » Stäfa ZH
Denmark » Svendborg
Germany » Bayern » München
Switzerland » Lake Constance » Uttwil
Switzerland » Neuenburgersee » Yvonand
Denmark » Svendborg
Germany » Bayern » Boote+service Oberbayern
Italy » Dormelletto
Switzerland » Seengen
Switzerland » Lake of Zurich » Stäfa am Zürichsee
Italy » Lake Garda » Moniga del Garda (BS)
Switzerland » Zugersee » Neuheim
Switzerland » Vierwaldstättersee » 6004
Switzerland » Safenwil
Switzerland » Lake Constance » Uttwil
Denmark » Svendborg
"France » MARTGUES, MARTIGUES"
Germany » Bayern » Forchheim/Ofr.
Germany » Bayern » München
Switzerland » Luganersee » Caslano
Germany » Nordrhein-Westfalen » WSC Hopp / Mönchengladbach
"Germany » BOOTSSERVICE ENK IN TREIS KARDEN, BOOTSSERVICE ENK"
</code>```

Said differently, the file is correct, it is correctly read by read_csv. Only the next part is plain wrong. You are not using Excel, are you?

Title: CSV - how to fix encoding issues

Body:
I have a csv file, which says it has UTF-8 encoding (as per Notepad++), but it's obviously not correct and when I try to decode it using other typical encoding, it does not work and it is still not readable.

I just wanted to ask for an advice, if there is a way, how to fix the encoding issues?
I've also tried to detect the econding via Python, but it says UTF-8 as well

with open("data.csv", 'rb') as rawdata:
    result = chardet.detect(rawdata.read(100000))

# check what the character encoding might be
print(result)

Example:

Location
Switzerland Â» Lake Geneva Â» VÃ©senaz
Germany Â» BÃ¶nningstedt
Switzerland Â» Lake of Zurich Â» StÃ¤fa ZH
Denmark Â» Svendborg
Germany Â» Bayern Â» MÃ¼nchen
Switzerland Â» Lake Constance Â» Uttwil
Switzerland Â» Neuenburgersee Â» Yvonand
Denmark Â» Svendborg
Germany Â» Bayern Â» Boote+service Oberbayern
Italy Â» Dormelletto
Switzerland Â» Seengen
Switzerland Â» Lake of Zurich Â» StÃ¤fa am ZÃ¼richsee
Italy Â» Lake Garda Â» Moniga del Garda (BS)
Switzerland Â» Zugersee Â» Neuheim
Switzerland Â» VierwaldstÃ¤ttersee Â» 6004
Switzerland Â» Safenwil
Switzerland Â» Lake Constance Â» Uttwil
Denmark Â» Svendborg
"France Â» MARTGUES, MARTIGUES"
Germany Â» Bayern Â» Forchheim/Ofr.
Germany Â» Bayern Â» MÃ¼nchen
Switzerland Â» Luganersee Â» Caslano
Germany Â» Nordrhein-Westfalen Â» WSC Hopp / MÃ¶nchengladbach
"Germany Â» BOOTSSERVICE ENK IN TREIS KARDEN, BOOTSSERVICE ENK"

Body:
The file is correctly encode as UTF-8. But you later display it as UTF-8 on a system that would expect Latin1 or cp1252 encoding.

Here is an evidence:

t = '''Location
Switzerland Â» Lake Geneva Â» VÃ©senaz
Germany Â» BÃ¶nningstedt
Switzerland Â» Lake of Zurich Â» StÃ¤fa ZH
Denmark Â» Svendborg
Germany Â» Bayern Â» MÃ¼nchen
Switzerland Â» Lake Constance Â» Uttwil
Switzerland Â» Neuenburgersee Â» Yvonand
Denmark Â» Svendborg
Germany Â» Bayern Â» Boote+service Oberbayern
Italy Â» Dormelletto
Switzerland Â» Seengen
Switzerland Â» Lake of Zurich Â» StÃ¤fa am ZÃ¼richsee
Italy Â» Lake Garda Â» Moniga del Garda (BS)
Switzerland Â» Zugersee Â» Neuheim
Switzerland Â» VierwaldstÃ¤ttersee Â» 6004
Switzerland Â» Safenwil
Switzerland Â» Lake Constance Â» Uttwil
Denmark Â» Svendborg
"France Â» MARTGUES, MARTIGUES"
Germany Â» Bayern Â» Forchheim/Ofr.
Germany Â» Bayern Â» MÃ¼nchen
Switzerland Â» Luganersee Â» Caslano
Germany Â» Nordrhein-Westfalen Â» WSC Hopp / MÃ¶nchengladbach
"Germany Â» BOOTSSERVICE ENK IN TREIS KARDEN, BOOTSSERVICE ENK"
'''
print(t.encode('latin1').decode())

On my unicode enabled systems it gives as expected:

Location
Switzerland » Lake Geneva » Vésenaz
Germany » Bönningstedt
Switzerland » Lake of Zurich » Stäfa ZH
Denmark » Svendborg
Germany » Bayern » München
Switzerland » Lake Constance » Uttwil
Switzerland » Neuenburgersee » Yvonand
Denmark » Svendborg
Germany » Bayern » Boote+service Oberbayern
Italy » Dormelletto
Switzerland » Seengen
Switzerland » Lake of Zurich » Stäfa am Zürichsee
Italy » Lake Garda » Moniga del Garda (BS)
Switzerland » Zugersee » Neuheim
Switzerland » Vierwaldstättersee » 6004
Switzerland » Safenwil
Switzerland » Lake Constance » Uttwil
Denmark » Svendborg
"France » MARTGUES, MARTIGUES"
Germany » Bayern » Forchheim/Ofr.
Germany » Bayern » München
Switzerland » Luganersee » Caslano
Germany » Nordrhein-Westfalen » WSC Hopp / Mönchengladbach
"Germany » BOOTSSERVICE ENK IN TREIS KARDEN, BOOTSSERVICE ENK"

Said differently, the file is correct, it is correctly read by read_csv. Only the next part is plain wrong. You are not using Excel, are you?


问:
JPA excesive querys for mapping an entity
I have the following entity:

```<code>    @Name("estructuraOrganica")
    @Entity
    @Table(name = "srht_estructuras_organicas")
    public class EstructuraOrganica extends EntidadBasica implements Auditable,
    Desplegable<EstructuraOrganica> {

private static final long serialVersionUID = 1L;

@NotNull
@Length(max = 50)
@Column(name = "codigo", nullable = false, length = 50)
private String codigo;

@Length(max = 300)
@Column(name = "nombre", nullable = true, length = 160)
private String nombre;

@Column(name = "institucion_id")
private Long institucionId;

@NotNull
@Length(max = 1)
@Column(name = "es_uarh", nullable = false, length = 1)
private String esUARH;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "catalogo_jerarquia_proceso_unidad_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Catalogo catalogoJerarquiaProcesoUnidad;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estatuto_id", nullable = false)
private Estatuto estatuto;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "estructura_organica_padre_id", nullable = true)
private EstructuraOrganica estructuraOrganicaPadre;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "padre_auxiliar_estructura_id", nullable = true)
private EstructuraOrganica estructuraOrganicaJerarquia;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estado_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Estado estado;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY,                             mappedBy                    =                           "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
private List<EstructuraOrganica> estructurasOrganicas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
private List<OrganigramaPosicion> organigramasPosiciones;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
@Where(clause = "estado_id=1")
private List<OrganigramaPosicion> organigramasPosicionesActivas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
@Where(clause = "estado_id=1")
private List<EstructuraOrganica> estructurasOrganicasActivas;

@Column(name = "estado_plan_vacaciones")
private Integer estadoPlanVacaciones;

@Column(name = "tipo")
private Integer tipo;

@Column(name = "puesto_jefe_inmediato")
private Long puestoJefeInmediato;

@Length(max = 10)
@Column(name = "codigo_mef", nullable = true, length = 10)
private String codigoMef;

@Transient
private Boolean puedeEliminarse;

@Transient
private Boolean uarh;

@Transient
private Boolean puedeGrabarse;

@Transient
private RegimenDePersonal regimenDePersonal;

@Column(name="institucion_desconcentrada_id")
private Long institucionDesconcentradaId;

... Getters and Setters omitted...

   }
</code>```

Now the JPQL query to find a certain instance of this entity is the following:

```<code>   SELECT o FROM EstructuraOrganica o WHERE o.estatuto.institucion.id=:institucionId and        o.estructuraOrganicaPadre is null AND o.estado.id=1 ORDER BY o.codigo ASC")
</code>```

However, the problem is that this simple query is generating an excesive count of calls to the database... doing selects basically. A native sql for doing the same could be:

```<code>    SELECT * from sch_senres.srht_estructuras_organicas,
          sch_senres.srht_estatutos,
          sch_senres.srht_instituciones,
          sch_senres.srht_estados
    WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id
    AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id
    AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id
    AND   sch_senres.srht_instituciones.id=91122
    AND   sch_senres.srht_estados.id=1
    AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL
    ORDER BY sch_senres.srht_estructuras_organicas.codigo
</code>```

So the idea was to create a NativeQuery like this:

```<code>    Query query=entityManager.createNativeQuery("SELECT * from  sch_senres.srht_estructuras_organicas,"+                                                    "sch_senres.srht_estatutos,sch_senres.srht_instituciones,"+
                                                "sch_senres.srht_estados "+
                                                "WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id "+
                                                "AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id "+
                                                "AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id "+
                                                "AND   sch_senres.srht_instituciones.id= :institucionId "+
                                                "AND   sch_senres.srht_estados.id=1 "+
                                                "AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL "+
                                                "ORDER BY sch_senres.srht_estructuras_organicas.codigo", EstructuraOrganica.class);
    query.setParameter("institucionId", institucionId);
</code>```

However I got no result... hibernate continues doing like 50 calls to the database. Does anybody know why is this happening, and how could I avoid so many calls?. Thanks a lot.

答:
I'd suggest to have a close look at when exactly the DB calls happen, and what exactly is queried in them.

If you haven't already done this, I'd suggest to activate logging of SQL statements by hibernate:

You have to set logging like this:

org.hibernate.type to TRACE level.

org.hibernate.SQL to DEBUG level.

This will show/log all the SQL statements and parameters that hibernate is using for your persistence.

In Log4J the above loggin would be configured like this...

```<code><category name="org.hibernate.type">
  <priority value="TRACE"/>
  <appender-ref ref="[..whatever appender you want..]"/>
</category>
<category name="org.hibernate.SQL">
  <priority value="DEBUG"/>
  <appender-ref ref="[..whatever appender you want..]"/>
</category>
</code>```

Body:
I have the following entity:

    @Name("estructuraOrganica")
    @Entity
    @Table(name = "srht_estructuras_organicas")
    public class EstructuraOrganica extends EntidadBasica implements Auditable,
    Desplegable<EstructuraOrganica> {

private static final long serialVersionUID = 1L;

@NotNull
@Length(max = 50)
@Column(name = "codigo", nullable = false, length = 50)
private String codigo;

@Length(max = 300)
@Column(name = "nombre", nullable = true, length = 160)
private String nombre;

@Column(name = "institucion_id")
private Long institucionId;

@NotNull
@Length(max = 1)
@Column(name = "es_uarh", nullable = false, length = 1)
private String esUARH;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "catalogo_jerarquia_proceso_unidad_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Catalogo catalogoJerarquiaProcesoUnidad;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estatuto_id", nullable = false)
private Estatuto estatuto;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "estructura_organica_padre_id", nullable = true)
private EstructuraOrganica estructuraOrganicaPadre;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "padre_auxiliar_estructura_id", nullable = true)
private EstructuraOrganica estructuraOrganicaJerarquia;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estado_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Estado estado;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY,                             mappedBy                    =                           "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
private List<EstructuraOrganica> estructurasOrganicas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
private List<OrganigramaPosicion> organigramasPosiciones;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
@Where(clause = "estado_id=1")
private List<OrganigramaPosicion> organigramasPosicionesActivas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
@Where(clause = "estado_id=1")
private List<EstructuraOrganica> estructurasOrganicasActivas;

@Column(name = "estado_plan_vacaciones")
private Integer estadoPlanVacaciones;

@Column(name = "tipo")
private Integer tipo;

@Column(name = "puesto_jefe_inmediato")
private Long puestoJefeInmediato;

@Length(max = 10)
@Column(name = "codigo_mef", nullable = true, length = 10)
private String codigoMef;

@Transient
private Boolean puedeEliminarse;

@Transient
private Boolean uarh;

@Transient
private Boolean puedeGrabarse;

@Transient
private RegimenDePersonal regimenDePersonal;

@Column(name="institucion_desconcentrada_id")
private Long institucionDesconcentradaId;

... Getters and Setters omitted...

   }

Now the JPQL query to find a certain instance of this entity is the following:

   SELECT o FROM EstructuraOrganica o WHERE o.estatuto.institucion.id=:institucionId and        o.estructuraOrganicaPadre is null AND o.estado.id=1 ORDER BY o.codigo ASC")

However, the problem is that this simple query is generating an excesive count of calls to the database... doing selects basically. A native sql for doing the same could be:

    SELECT * from sch_senres.srht_estructuras_organicas,
          sch_senres.srht_estatutos,
          sch_senres.srht_instituciones,
          sch_senres.srht_estados
    WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id
    AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id
    AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id
    AND   sch_senres.srht_instituciones.id=91122
    AND   sch_senres.srht_estados.id=1
    AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL
    ORDER BY sch_senres.srht_estructuras_organicas.codigo

So the idea was to create a NativeQuery like this:

    Query query=entityManager.createNativeQuery("SELECT * from  sch_senres.srht_estructuras_organicas,"+                                                    "sch_senres.srht_estatutos,sch_senres.srht_instituciones,"+
                                                "sch_senres.srht_estados "+
                                                "WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id "+
                                                "AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id "+
                                                "AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id "+
                                                "AND   sch_senres.srht_instituciones.id= :institucionId "+
                                                "AND   sch_senres.srht_estados.id=1 "+
                                                "AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL "+
                                                "ORDER BY sch_senres.srht_estructuras_organicas.codigo", EstructuraOrganica.class);
    query.setParameter("institucionId", institucionId);

However I got no result... hibernate continues doing like 50 calls to the database. Does anybody know why is this happening, and how could I avoid so many calls?. Thanks a lot.

Body:
I'd suggest to have a close look at when exactly the DB calls happen, and what exactly is queried in them.

If you haven't already done this, I'd suggest to activate logging of SQL statements by hibernate:

You have to set logging like this:

org.hibernate.type to TRACE level.

org.hibernate.SQL to DEBUG level.

This will show/log all the SQL statements and parameters that hibernate is using for your persistence.

In Log4J the above loggin would be configured like this...

<category name="org.hibernate.type">
  <priority value="TRACE"/>
  <appender-ref ref="[..whatever appender you want..]"/>
</category>
<category name="org.hibernate.SQL">
  <priority value="DEBUG"/>
  <appender-ref ref="[..whatever appender you want..]"/>
</category>


问:
Why is my css not working on v-checkbox's icon?
I have two icons and I'm trying to customize them

```<code><v-checbkox icon class="icons" off-icon="mdi-close" on-icon="mdi-mark"></v-checkbox>
</code>```

I want something like this :

And actually I have this :

I tried this (got it from css dev mode of the first icon)  :

```<code>.icons {
    background-color: red;
    color:green !important;
    font-weight: 200;
    border-radius: 2px;
}
</code>```

And the font-weight doesn't change, the color don't change the icon but the hover color and the background color is a (way) too big square.

What I am doing wrong?

Update

Background-color gaves me this :

Ok this almost worked :

```<code>    <v-checkbox
      v-model="answer.correct"
      on-icon="mdi-check"
      off-icon="mdi-close"
      color="white"
      style="border-radius:6px; width:40px; height:40px"
      :class="{ 'success': answer.correct, 'red': !answer.correct}"
      class="answer-toggle icons mr-3 pl-2 pt-2"
    ></v-checkbox>
</code>```

But the white only works for mdi-check not mdi-close

How can I give it the same condition as the class and make the icon larger.

答:
You probably already solved this, but gonna answer here in case this can help anyone.
Instead of using the 'mdi-check' and 'mdi-close' you should be using:

```<code><v-checkbox
  v-model="answer.correct"
  on-icon="mdi-checkbox-marked"
  off-icon="mdi-close-box"
  :color="answer.correct ? 'green' : 'red'"
></v-checkbox>
</code>```

These icons already have the box, so you don't have to create a box around your icons.
And set the color according to you logic.
For more icons: https://materialdesignicons.com/

Body:
I have two icons and I'm trying to customize them

<v-checbkox icon class="icons" off-icon="mdi-close" on-icon="mdi-mark"></v-checkbox>

I want something like this :

And actually I have this :

I tried this (got it from css dev mode of the first icon)  :

.icons {
    background-color: red;
    color:green !important;
    font-weight: 200;
    border-radius: 2px;
}

And the font-weight doesn't change, the color don't change the icon but the hover color and the background color is a (way) too big square.

What I am doing wrong?

Update

Background-color gaves me this :

Ok this almost worked :

    <v-checkbox
      v-model="answer.correct"
      on-icon="mdi-check"
      off-icon="mdi-close"
      color="white"
      style="border-radius:6px; width:40px; height:40px"
      :class="{ 'success': answer.correct, 'red': !answer.correct}"
      class="answer-toggle icons mr-3 pl-2 pt-2"
    ></v-checkbox>

But the white only works for mdi-check not mdi-close

How can I give it the same condition as the class and make the icon larger.

Body:
You probably already solved this, but gonna answer here in case this can help anyone.
Instead of using the 'mdi-check' and 'mdi-close' you should be using:

<v-checkbox
  v-model="answer.correct"
  on-icon="mdi-checkbox-marked"
  off-icon="mdi-close-box"
  :color="answer.correct ? 'green' : 'red'"
></v-checkbox>

These icons already have the box, so you don't have to create a box around your icons.
And set the color according to you logic.
For more icons: https://materialdesignicons.com/


问:
React JSX file giving error "Cannot read property 'createElement' of undefined"
I have a file test_stuff.js that I am running with npm test

It pretty much looks like this:

```<code>import { assert } from 'assert';
import { MyProvider } from '../src/index';
import { React } from 'react';

const myProvider = (
  <MyProvider>
  </MyProvider>
);

describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});
</code>```

Unfortunately, I get the error

```<code>/Users/me/projects/myproj/test/test_stuff.js:11
var myProvider = _react.React.createElement(_index.MyProvider, null);
                             ^

TypeError: Cannot read property 'createElement' of undefined
    at Object.<anonymous> (/Users/me/projects/myproj/test/test_stuff.js:7:7)
</code>```

What does that mean? I am importing React from 'react' successfully, so why would React be undefined? It is _react.React, whatever that means...

答:
This error can be occured due to carelessness. Please add

```<code>import React from 'react'

</code>```

It will be resolved after that

Body:
I have a file test_stuff.js that I am running with npm test

It pretty much looks like this:

import { assert } from 'assert';
import { MyProvider } from '../src/index';
import { React } from 'react';

const myProvider = (
  <MyProvider>
  </MyProvider>
);

describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});

Unfortunately, I get the error

/Users/me/projects/myproj/test/test_stuff.js:11
var myProvider = _react.React.createElement(_index.MyProvider, null);
                             ^

TypeError: Cannot read property 'createElement' of undefined
    at Object.<anonymous> (/Users/me/projects/myproj/test/test_stuff.js:7:7)

What does that mean? I am importing React from 'react' successfully, so why would React be undefined? It is _react.React, whatever that means...

Body:
This error can be occured due to carelessness. Please add

import React from 'react'

It will be resolved after that


问:
Convert regular lat/lon grid to polygons using R sf
I'm trying to convert a regular 1-degree by 1-degree geographic grid to polygons while maintaining the data associated with each grid point using the R sf package.

Example code:

```<code>library(tidyverse)
library(sf)
library(sfheaders)
library(sfheaders)

# latitude
lldata <- tibble(lat=as.numeric(rep(seq(40,49.5),10)))

# Longitude + add data
lldata <- lldata %>%
          group_by(lat) %>%
          mutate(lon = -90 + row_number()-1,
                 data = runif(1))

#Plot the grid as points
lldata %>%
  ggplot() +
  geom_point(aes(x=lon,y=lat,color=data))
</code>```

This yields:

```<code># Attempt #1
#https://stackoverflow.com/questions/48383990/convert-sequence-of-longitude-and-latitude-to-polygon-via-sf-in-r

lldata %>% arrange(lat,-lon)  %>%
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  summarise(geometry = st_combine(geometry)) %>%
  st_cast("POLYGON") %>%
  ggplot() +
  geom_sf()
</code>```

Which yields

```<code># Also tried
poly <- st_sf(st_sfc(st_make_valid(st_polygon(list(as.matrix(lldata))))), crs = 4326)
# error that the polygon is not closed

# Attempt #2
# https://stackoverflow.com/questions/52669779/convert-sets-of-spatial-coordinates-to-polygons-in-r-using-sf/52671103

sf <- sfheaders::sf_polygon(
  obj = lldata
  , x = "lon"
  , y = "lat"
)

# Same result as above
sf %>%
  ggplot() +
  geom_sf()
</code>```

I'm expecting a polygon whose boundaries are defined by the regular grid but the boundaries of each polygon are not being closed.   Is there a simple solution in the SF package I'm missing?

Also, when creating the polygon, I'd like for the variable "data" to be associated with each polygon.  I have not made it that far, however.

答:
Probably the most convenient way to do this is to use stars, stars objects can be plotted directly with ggplot or you can make spatial polygons out of it:

library(tidyverse)
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
library(sfheaders)
require(stars)
#> Loading required package: stars
#> Loading required package: abind
# latitude
lldata <- tibble(lat=as.numeric(rep(seq(40,49.5),10)))

# Longitude + add data
lldata <- lldata %>%
  group_by(lat) %>%
  mutate(lon = -90 + row_number()-1,
         data = runif(1))
ggplot()+geom_stars(data=st_as_stars(lldata, dims  = c('lon','lat')))
```
<p><img src="https://i.imgur.com/jq8srMx.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code>st_as_stars(lldata, dims  = c('lon','lat')) %>% st_as_sf(as_points=F)
#> Simple feature collection with 100 features and 1 field
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: -90.5 ymin: 39.5 xmax: -80.5 ymax: 49.5
#> CRS:           NA
#> First 10 features:
#>         data                       geometry
#> 1  0.5560062 POLYGON ((-90.5 49.5, -89.5...
#> 2  0.5560062 POLYGON ((-89.5 49.5, -88.5...
#> 3  0.5560062 POLYGON ((-88.5 49.5, -87.5...
#> 4  0.5560062 POLYGON ((-87.5 49.5, -86.5...
#> 5  0.5560062 POLYGON ((-86.5 49.5, -85.5...
#> 6  0.5560062 POLYGON ((-85.5 49.5, -84.5...
#> 7  0.5560062 POLYGON ((-84.5 49.5, -83.5...
#> 8  0.5560062 POLYGON ((-83.5 49.5, -82.5...
#> 9  0.5560062 POLYGON ((-82.5 49.5, -81.5...
#> 10 0.5560062 POLYGON ((-81.5 49.5, -80.5...
</code>```

Created on 2022-02-08 by the reprex package (v2.0.1)

Body:
I'm trying to convert a regular 1-degree by 1-degree geographic grid to polygons while maintaining the data associated with each grid point using the R sf package.

Example code:

library(tidyverse)
library(sf)
library(sfheaders)
library(sfheaders)

# latitude
lldata <- tibble(lat=as.numeric(rep(seq(40,49.5),10)))

# Longitude + add data
lldata <- lldata %>%
          group_by(lat) %>%
          mutate(lon = -90 + row_number()-1,
                 data = runif(1))

#Plot the grid as points
lldata %>%
  ggplot() +
  geom_point(aes(x=lon,y=lat,color=data))

This yields:

# Attempt #1
#https://stackoverflow.com/questions/48383990/convert-sequence-of-longitude-and-latitude-to-polygon-via-sf-in-r

lldata %>% arrange(lat,-lon)  %>%
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  summarise(geometry = st_combine(geometry)) %>%
  st_cast("POLYGON") %>%
  ggplot() +
  geom_sf()

Which yields

# Also tried
poly <- st_sf(st_sfc(st_make_valid(st_polygon(list(as.matrix(lldata))))), crs = 4326)
# error that the polygon is not closed

# Attempt #2
# https://stackoverflow.com/questions/52669779/convert-sets-of-spatial-coordinates-to-polygons-in-r-using-sf/52671103

sf <- sfheaders::sf_polygon(
  obj = lldata
  , x = "lon"
  , y = "lat"
)

# Same result as above
sf %>%
  ggplot() +
  geom_sf()

I'm expecting a polygon whose boundaries are defined by the regular grid but the boundaries of each polygon are not being closed.   Is there a simple solution in the SF package I'm missing?

Also, when creating the polygon, I'd like for the variable "data" to be associated with each polygon.  I have not made it that far, however.

Body:
Probably the most convenient way to do this is to use stars, stars objects can be plotted directly with ggplot or you can make spatial polygons out of it:

library(tidyverse)
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
library(sfheaders)
require(stars)
#> Loading required package: stars
#> Loading required package: abind
# latitude
lldata <- tibble(lat=as.numeric(rep(seq(40,49.5),10)))

# Longitude + add data
lldata <- lldata %>%
  group_by(lat) %>%
  mutate(lon = -90 + row_number()-1,
         data = runif(1))
ggplot()+geom_stars(data=st_as_stars(lldata, dims  = c('lon','lat')))

st_as_stars(lldata, dims  = c('lon','lat')) %>% st_as_sf(as_points=F)
#> Simple feature collection with 100 features and 1 field
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: -90.5 ymin: 39.5 xmax: -80.5 ymax: 49.5
#> CRS:           NA
#> First 10 features:
#>         data                       geometry
#> 1  0.5560062 POLYGON ((-90.5 49.5, -89.5...
#> 2  0.5560062 POLYGON ((-89.5 49.5, -88.5...
#> 3  0.5560062 POLYGON ((-88.5 49.5, -87.5...
#> 4  0.5560062 POLYGON ((-87.5 49.5, -86.5...
#> 5  0.5560062 POLYGON ((-86.5 49.5, -85.5...
#> 6  0.5560062 POLYGON ((-85.5 49.5, -84.5...
#> 7  0.5560062 POLYGON ((-84.5 49.5, -83.5...
#> 8  0.5560062 POLYGON ((-83.5 49.5, -82.5...
#> 9  0.5560062 POLYGON ((-82.5 49.5, -81.5...
#> 10 0.5560062 POLYGON ((-81.5 49.5, -80.5...

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
How to access inner array in out side of nestes for loop
I want make code in which we have to add inputs and it show output at very after all inputs are performed.
But i don't know how can i access the contents of variable in for loop in outer side.

My code is given below

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

public class App {
    public static void main(String[] args) throws Exception {

        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case?
        for(int i=0;i<T;i++)
        {
            int N=sc.nextInt();        //How many items in each cases?
            for(int j=0;j<N;j++)
            {
                int C=sc.nextInt();   //How much cost of each items?
            }
        }
        int [][]A =new int[T][N];

        //I know here No issue with T but how can i acces N and C?

        //here code to show output of given inputs.....
....
..

    }
}

</code>```

Ex:-

```<code>Input:--

2 //test cases

3  //items

1  2  3  //costs

4  //items

1 2 3 4  //costs

Ouput:---perfectly as in input.
</code>```

答:
I don't understand the question, but in any case your variables (except T) are out of scope. Should be something like (psueo-code)</p>
```<code>import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {

        int [][][] A;
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case? say 3
        for(int i=0;i<T;i++)
        {
            int N=sc.nextInt();        //How many items in each cases? say 14
            for(int j=0;j<N;j++)
            {
                int C=sc.nextInt();   //How much cost of each items? say 2
                A =new int[T][N][C]; // ok, you got a 3x14X2 array
                // now do here or outside what you want with it
            }
        }

        //I know here No issue with T but how can i acces N and C?
        // you can use A 3 dimensional array  here

        //here code to show output of given inputs.....
....
..

    }
}
</code>```

Body:
I want make code in which we have to add inputs and it show output at very after all inputs are performed.
But i don't know how can i access the contents of variable in for loop in outer side.

My code is given below

import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {

        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case?
        for(int i=0;i<T;i++)
        {
            int N=sc.nextInt();        //How many items in each cases?
            for(int j=0;j<N;j++)
            {
                int C=sc.nextInt();   //How much cost of each items?
            }
        }
        int [][]A =new int[T][N];

        //I know here No issue with T but how can i acces N and C?

        //here code to show output of given inputs.....
....
..

    }
}

Ex:-

Input:--

2 //test cases

3  //items

1  2  3  //costs

4  //items

1 2 3 4  //costs

Ouput:---perfectly as in input.

Body:
I don't understand the question, but in any case your variables (except T) are out of scope. Should be something like (psueo-code)

import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {

        int [][][] A;
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case? say 3
        for(int i=0;i<T;i++)
        {
            int N=sc.nextInt();        //How many items in each cases? say 14
            for(int j=0;j<N;j++)
            {
                int C=sc.nextInt();   //How much cost of each items? say 2
                A =new int[T][N][C]; // ok, you got a 3x14X2 array
                // now do here or outside what you want with it
            }
        }

        //I know here No issue with T but how can i acces N and C?
        // you can use A 3 dimensional array  here

        //here code to show output of given inputs.....
....
..

    }
}


问:
How can I use a SystemAssigned identity when pulling an image from Azure Container Registry into Azure Container Instances?
I want to create a container (or container group) in Azure Container Instances, pulling the image(s) from Azure Container Registry - but with using a SystemAssigned identity. With that I want to avoid using ACR login credentials, a service principal or a UserAssigned identity.

When I run this script (Azure CLI in PowerShell) ...

```<code>$LOC = "westeurope"
$RG = "myresourcegroup"
$ACRNAME = "myacr"

az configure --defaults location=$LOC group=$RG

$acr = az acr show -n $ACRNAME -o json | ConvertFrom-Json -Depth 10

az container create --name app1 --image $($acr.loginServer+"/app1") `
    --assign-identity --role acrpull --scope $acr.id `
    --debug
</code>```

... ACI does not seem to recognize that it should be already authorized for ACR and shows this prompt:

```<code>Image registry username:
</code>```

Azure CLI version: 2.14.0

Does this make sense? Is the ACI managed identity supported for ACR?

答:
@minus_one -solution do not work in my case. Runbook to make container registry. It does need more priviledges than stated in here...
https://github.com/Azure/azure-powershell/issues/3215</p>

Body:
I want to create a container (or container group) in Azure Container Instances, pulling the image(s) from Azure Container Registry - but with using a SystemAssigned identity. With that I want to avoid using ACR login credentials, a service principal or a UserAssigned identity.

When I run this script (Azure CLI in PowerShell) ...

$LOC = "westeurope"
$RG = "myresourcegroup"
$ACRNAME = "myacr"

az configure --defaults location=$LOC group=$RG

$acr = az acr show -n $ACRNAME -o json | ConvertFrom-Json -Depth 10

az container create --name app1 --image $($acr.loginServer+"/app1") `
    --assign-identity --role acrpull --scope $acr.id `
    --debug

... ACI does not seem to recognize that it should be already authorized for ACR and shows this prompt:

Image registry username:

Azure CLI version: 2.14.0

Does this make sense? Is the ACI managed identity supported for ACR?