Problemas com Rotina para identificar Versão do Windows

Question: Estou com problema em uma rotina que identifica a versão do windows.
No caso estou utilizando Delphi 7, coloquei a rotina em um programa que resolve e coloca em um textbox, beleza funcionou, fiz algumas alterações e perfeito a respota confere com o sistema operacional windows que estou utilizando 'WINSEVEN00PRO2610000000000' porém quando copio a rotina inteira e a coloco no sistema que dou manutenção a resposta da execução é WINXP00000PRO2510000000000, diferente, como explicar e como solucionar.
Agradeço a colaboração:
const
  VER_NT_WORKSTATION    :Integer = 1;
  VER_SUITE_ENTERPRISE  :Integer = 2;
  VER_NT_SERVER         :Integer = 3;
  VER_SUITE_DATACENTER  :Integer = 128;
  VER_SUITE_PERSONAL    :Integer = 512;
  vSONAOIDENTIFICADO    :String = 'WINDOWS';
  vSOWIN9X              :String = 'WIN9X';
  vSOWIN2000            :String = 'WIN2K';
  vSOWINXP              :String = 'WINXP';
  vSOWINXPpro           :String = 'WINXPPRO';
  vSOWIN7               :String = 'WINSEVEN';
  vSOWIN8               :String = 'WINEIGHT';
  vSOVISTA              :String = 'WINVISTA';
  vULTIMATE             :String = 'ULT';
  vHOMEPREMIUM          :String = 'HPR';
  vHOMEBASIC            :String = 'HBS';
  vPROFESSIONAL         :String = 'PRO';
  vSTANDARD             :String = 'STD';

function TForm1.GetSO: string;
    function CompletarZeros(sString: string; iTamanho: Integer): String;
    begin
        Result := sString;
        while Length(Result) < iTamanho do
            Result := Result+'0';
    end;
var
    NTBres, BRes: Boolean;
    verInfo: TOSVersionInfo;
    verInfo_NT: TOSVersionInfoW;
    i: word;
    str, ProductName, ProductNameEx, VersionL : string;
    pdwReturnedProductType : DWORD;
begin
    Result := 'Error';
    NTBres := False;
    try
        verInfo_NT.dwOSVersionInfoSize := SizeOf(TOSVERSIONINFOEX);
        NTBRes := GetVersionEx(verInfo);
        verInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
        BRes := GetVersionEx(verInfo);
    except
        verInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
        BRes := GetVersionEx(verInfo);
    end;
    if (not BRes) and (not NTBres) then
        Exit;
    Move( verInfo, verInfo_NT, SizeOf(TOSVersionInfo) );

    verInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
    if GetVersionEx(verInfo) then
        VersionL := IntToStr(verInfo.dwPlatformId)+IntToStr(verInfo.dwMajorVersion) + IntToStr(verInfo.dwMinorVersion);

    case verInfo.dwPlatformId of
        VER_PLATFORM_WIN32s : ProductName := vSOWIN9X;
        VER_PLATFORM_WIN32_WINDOWS : ProductName := vSOWIN9X;
        VER_PLATFORM_WIN32_NT:
            begin
                case verInfo.dwMajorVersion  of
                    0..4: ProductName := vSONAOIDENTIFICADO;
                    5:  begin
                            case verInfo.dwMinorVersion of
                                0: ProductName := vSOWIN2000;//;//'Windows 2000';
                                1: ProductName := vSOWINXP;//'Windows XP';
                                2: productName := vSOWINXPpro;//'Windows XP Prof';
                            else
                                Result := IntToStr(verInfo.dwMajorVersion)+IntToStr(verInfo.dwMinorVersion)+ vSONAOIDENTIFICADO;
                            end;
                        end;
                    6:  begin
                            case verInfo.dwMinorVersion of
                                0:ProductName := vSOVISTA ;//'Windows Vista';
                                1:ProductName := vSOWIN7;//'Windows 7';
                                2:ProductName := vSOWIN8;//'Windows 8';
                            else
                                ProductName := IntToStr(verInfo.dwMajorVersion)+IntToStr(verInfo.dwMinorVersion)+ vSONAOIDENTIFICADO;
                            end;
                        end;
                else
                    ProductName := IntToStr(verInfo.dwMajorVersion)+IntToStr(verInfo.dwMinorVersion)+vSONAOIDENTIFICADO;
                end;
            end;
    ELSE
        ProductName := IntToStr(verInfo.dwMajorVersion)+IntToStr(verInfo.dwMinorVersion)+vSONAOIDENTIFICADO
    end;
    str := '';
    ProductNameEx :=IntToStr(verInfo.dwMajorVersion)+IntToStr(verInfo.dwMinorVersion)+vSONAOIDENTIFICADO+IntToStr(-1);
    if Assigned ( GetProductInfo) then
    begin
        ProductNameEx :='';
        GetProductInfo(verInfo.dwMajorVersion, verInfo.dwMinorVersion, 0,0, pdwReturnedProductType);
        case pdwReturnedProductType of
          0:    begin
                    if (verInfo.dwMajorVersion = 5) and (verInfo.dwMinorVersion=1) then
                        ProductNameEx := vPROFESSIONAL //'Professional'
                    else
                        ProductNameEx := vSTANDARD;//'Standard';
                end;
          1: ProductNameEx:=  vULTIMATE;
          2: ProductNameEx:=  vHOMEBASIC;
          3: ProductNameEx:=  vHOMEPREMIUM;//'Home Premium';
          5: ProductNameEx:=  vHOMEBASIC;// 'Home Basic'  ;
          28: ProductNameEx:= vULTIMATE;//  'Ultimate';
          48,49: ProductNameEx:= vPROFESSIONAL;// 'Professional' ;
          68: ProductNameEx:= vHOMEPREMIUM;// 'Home Premium';
          69: ProductNameEx:= vPROFESSIONAL;// 'Professional';
          71: ProductNameEx:= vULTIMATE;// 'Ultimate';
        else ;
            ProductNameEx :=IntToStr(verInfo.dwMajorVersion)+IntToStr(verInfo.dwMinorVersion)+vSONAOIDENTIFICADO+IntToStr(pdwReturnedProductType);
        end;
    end;
    for I := 0 to 127 do
        str := str + verInfo.szCSDVersion[i];
//    STR := StringReplace(UpperCase(str), 's', 'S', [rfReplaceAll]);
//    STR := StringReplace(UpperCase(str), 'p', 'P', [rfReplaceAll]);
    STR := StringReplace(UpperCase(str), ' ', '', [rfReplaceAll]);
    STR := Trim(str);
    if Length(Version) < 4 then
        VersionL := CompletarZeros(VersionL, 4);
    if Length(str) < 3 then
        str := CompletarZeros(str, 3);
    str := str+' >'+IntToStr(pdwReturnedProductType);
    Result := CompletarZeros(ProductName,10)+CompletarZeros(ProductNameEx+VersionL,16); //+ Version + str;
end;

Comment: Qual é a versão do outro S.O?
Comment: WINDOWS 7 PROFESSIONAL 32
Answer: Um tempo atrás encontrei no Google uma biblioteca (unit) específica para isso, que é uma das mais completas que vi até hoje. Estou lhe enviando abaixo. Copie e salve em um arquivo com o nome GetWinVersionInfo.pas, dentro da pasta do seu projeto, depois basta adicionar "GetWinVersionInfo" na clausula "Uses". Espero ter ajudado!
unit GetWinVersionInfo;

interface

uses
  Windows,
  Registry,
  SysUtils;

function GetOSInfo: string;

implementation

type
  _OSVERSIONINFOEX = record
    dwOSVersionInfoSize : DWORD;
    dwMajorVersion      : DWORD;
    dwMinorVersion      : DWORD;
    dwBuildNumber       : DWORD;
    dwPlatformId        : DWORD;
    szCSDVersion        : array[0..127] of AnsiChar;
    wServicePackMajor   : WORD;
    wServicePackMinor   : WORD;
    wSuiteMask          : WORD;
    wProductType        : BYTE;
    wReserved           : BYTE;
  end;
  TOSVERSIONINFOEX = _OSVERSIONINFOEX;

  function GetVersionExA(var lpVersionInformation: TOSVersionInfoEX): BOOL;
        stdcall; external kernel32;

const
  VER_NT_WORKSTATION    :Integer = 1;
  VER_SUITE_ENTERPRISE  :Integer = 2;
  VER_NT_SERVER         :Integer = 3;
  VER_SUITE_DATACENTER  :Integer = 128;
  VER_SUITE_PERSONAL    :Integer = 512;

const
  PRODUCT_BUSINESS                      = $00000006; {Business Edition}
  PRODUCT_BUSINESS_N                    = $00000010; {Business Edition}

  PRODUCT_CLUSTER_SERVER                = $00000012; {HPC Edition}
  PRODUCT_CLUSTER_SERVER_V              = $00000040; {Server Hyper Core V Edition}

  PRODUCT_CORE                          = $00000065; {Windows 8}
  PRODUCT_CORE_N                        = $00000062; {Windows 8 N}
  PRODUCT_CORE_COUNTRYSPECIFIC          = $00000063; {Windows 8 China}
  PRODUCT_CORE_SINGLELANGUAGE           = $00000064; {Windows 8 Single Language}

  PRODUCT_DATACENTER_EVALUATION_SERVER  = $00000050; {Server Datacenter (evaluation installation)}
  PRODUCT_DATACENTER_SERVER             = $00000008; {Server Datacenter Edition (full installation)}
  PRODUCT_DATACENTER_SERVER_CORE        = $0000000C; {Server Datacenter Edition (core installation)}
  PRODUCT_DATACENTER_SERVER_CORE_V      = $00000027; {Server Datacenter without Hyper-V (core installation)}
  PRODUCT_DATACENTER_SERVER_V           = $00000025; {Server Datacenter without Hyper-V (full installation)}

  PRODUCT_ENTERPRISE                    = $00000004; {Enterprise Edition}
  PRODUCT_ENTERPRISE_E                  = $00000046; {Not supported}
  PRODUCT_ENTERPRISE_N_EVALUATION       = $00000054; {Enterprise N (evaluation installation)}
  PRODUCT_ENTERPRISE_N                  = $0000001B; {Enterprise N Edition}
  PRODUCT_ENTERPRISE_EVALUATION         = $00000048; {Server Enterprise (evaluation installation)}
  PRODUCT_ENTERPRISE_SERVER             = $0000000A; {Server Enterprise Edition (full installation)}
  PRODUCT_ENTERPRISE_SERVER_CORE        = $0000000E; {Server Enterprise Edition (core installation)}
  PRODUCT_ENTERPRISE_SERVER_CORE_V      = $00000029; {Server Enterprise without Hyper-V (core installation)}
  PRODUCT_ENTERPRISE_SERVER_IA64        = $0000000F; {Server Enterprise Edition for Itanium-based Systems}
  PRODUCT_ENTERPRISE_SERVER_V           = $00000026; {Server Enterprise without Hyper-V (full installation)}

  PRODUCT_ESSENTIALBUSINESS_SERVER_MGMT = $0000003B; {Windows Essential Server Solution Management}
  PRODUCT_ESSENTIALBUSINESS_SERVER_ADDL = $0000003C; {Windows Essential Server Solution Additional}
  PRODUCT_ESSENTIALBUSINESS_SERVER_MGMTSVC = $0000003D; {Windows Essential Server Solution Management SVC}
  PRODUCT_ESSENTIALBUSINESS_SERVER_ADDLSVC = $0000003E; {Windows Essential Server Solution Additional SVC}

  PRODUCT_HOME_BASIC                    = $00000002; {Home Basic Edition}
  PRODUCT_HOME_BASIC_E                  = $00000043; {Not supported}
  PRODUCT_HOME_BASIC_N                  = $00000005; {Home Basic Edition}
  PRODUCT_HOME_PREMIUM                  = $00000003; {Home Premium Edition}
  PRODUCT_HOME_PREMIUM_E                = $00000044; {Not supported}
  PRODUCT_HOME_PREMIUM_N                = $0000001A; {Home Premium Edition}
  PRODUCT_HOME_PREMIUM_SERVER           = $00000022; {Windows Home Premium Server 2011}
  PRODUCT_HOME_SERVER                   = $00000013; {Windows Home Server 2011}

  PRODUCT_HYPERV                        = $0000002A; {Microsoft Hyper-V Server}

  PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT = $0000001E; {Windows Essential Business Server Management Server}
  PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING = $00000020; {Windows Essential Business Server Messaging Server}
  PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY = $0000001F; {Windows Essential Business Server Security Server}

  PRODUCT_MULTIPOINT_STANDARD_SERVER    = $0000004C; {Windows MultiPoint Server Standard (full installation)}
  PRODUCT_MULTIPOINT_PREMIUM_SERVER     = $0000004D; {Windows MultiPoint Server Premium (full installation)}

  PRODUCT_PROFESSIONAL                  = $00000030; {Professional}
  PRODUCT_PROFESSIONAL_E                = $00000045; {Not supported}
  PRODUCT_PROFESSIONAL_N                = $00000031; {Professional N}
  PRODUCT_PROFESSIONAL_WMC              = $00000067; {Professional with Media Center}

  PRODUCT_SB_SOLUTION_SERVER_EM         = $00000036; {Server For SB Solutions EM}
  PRODUCT_SERVER_FOR_SB_SOLUTIONS       = $00000033; {Server For SB Solutions}
  PRODUCT_SERVER_FOR_SB_SOLUTIONS_EM    = $00000037; {Server For SB Solutions EM}

  PRODUCT_SERVER_FOR_SMALLBUSINESS      = $00000018; {Windows Server 2008 for Windows Essential Server Solutions}
  PRODUCT_SERVER_FOR_SMALLBUSINESS_V    = $00000023; {Windows Server 2008 without Hyper-V for Windows Essential Server Solutions}

  PRODUCT_SERVER_FOUNDATION             = $00000021; {Server Foundation}
  PRODUCT_SB_SOLUTION_SERVER            = $00000032; {Windows Small Business Server 2011 Essentials}

  PRODUCT_SMALLBUSINESS_SERVER          = $00000009; {Small Business Server}
  PRODUCT_SMALLBUSINESS_SERVER_PREMIUM  = $00000019; {Small Business Server Premium Edition}
  PRODUCT_SMALLBUSINESS_SERVER_PREMIUM_CORE = $0000003F; {Small Business Server Premium (core installation)}

  PRODUCT_SOLUTION_EMBEDDEDSERVER       = $00000038; {Windows MultiPoint Server}

  PRODUCT_STANDARD_EVALUATION_SERVER    = $0000004F; {Server Standard (evaluation installation)}
  PRODUCT_STANDARD_SERVER               = $00000007; {Server Standard Edition (full installation)}
  PRODUCT_STANDARD_SERVER_CORE          = $0000000D; {Server Standard Edition (core installation)}
  PRODUCT_STANDARD_SERVER_V             = $00000024; {Server Standard without Hyper-V}
  PRODUCT_STANDARD_SERVER_CORE_V        = $00000028; {Server Standard without Hyper-V (core installation)}
  PRODUCT_STANDARD_SERVER_SOLUTIONS     = $00000034; {Server Solutions Premium}
  PRODUCT_STANDARD_SERVER_SOLUTIONS_CORE = $00000035; {Server Solutions Premium (core installation)}

  PRODUCT_STARTER                       = $0000000B; {Starter Edition}
  PRODUCT_STARTER_E                     = $00000042; {Not supported}
  PRODUCT_STARTER_N                     = $0000002F; {Starter N Edition}

  PRODUCT_STORAGE_ENTERPRISE_SERVER     = $00000017; {Storage Server Enterprise Edition}
  PRODUCT_STORAGE_ENTERPRISE_SERVER_CORE = $0000002E; {Storage Server Enterprise (core installation)}
  PRODUCT_STORAGE_EXPRESS_SERVER        = $00000014; {Storage Server Express Edition}
  PRODUCT_STORAGE_EXPRESS_SERVER_CORE   = $0000002B; {Storage Server Express (core installation)}
  PRODUCT_STORAGE_STANDARD_EVALUATION_SERVER = $00000060; {Storage Server Standard (evaluation installation)}
  PRODUCT_STORAGE_STANDARD_SERVER       = $00000015; {Storage Server Standard Edition}
  PRODUCT_STORAGE_STANDARD_SERVER_CORE  = $0000002C; {Storage Server Standard (core installation)}
  PRODUCT_STORAGE_WORKGROUP_EVALUATION_SERVER = $0000005F; {Storage Server Workgroup (evaluation installation)}
  PRODUCT_STORAGE_WORKGROUP_SERVER      = $00000016; {Storage Server Workgroup Edition}
  PRODUCT_STORAGE_WORKGROUP_SERVER_CORE = $0000002D; {Storage Server Workgroup (core installation)}

  PRODUCT_UNDEFINED                     = $00000000; {An unknown product}

  PRODUCT_ULTIMATE                      = $00000001; {Ultimate Edition}
  PRODUCT_ULTIMATE_N                    = $0000001C; {Ultimate Edition}

  PRODUCT_WEB_SERVER                    = $00000011; {Web Server Edition}
  PRODUCT_WEB_SERVER_CORE               = $0000001D; {Web Server (core installation)}
  PRODUCT_UNLICENSED                    = $ABCDABCD; {Unlicensed product}

var
  GetProductInfo: function (dwOSMajorVersion, dwOSMinorVersion,
                            dwSpMajorVersion, dwSpMinorVersion: DWORD;
                            var pdwReturnedProductType: DWORD): BOOL stdcall = NIL;

function GetOSInfo: string;
var
  NTBres, BRes: Boolean;
  OSVI: TOSVERSIONINFO;
  OSVI_NT: TOSVERSIONINFOEX;
  tmpStr: string;
  dwOSMajorVersion, dwOSMinorVersion,
  dwSpMajorVersion, dwSpMinorVersion,
  pdwReturnedProductType : DWORD;
begin
  Result := 'Error';
  NTBRes := FALSE;
  try
    OSVI_NT.dwOSVersionInfoSize := SizeOf(TOSVERSIONINFOEX);
    NTBRes := GetVersionExA(OSVI_NT);
    OSVI.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
    BRes := GetVersionEx(OSVI);
  except
    OSVI.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
    BRes := GetVersionEx(OSVI);
  end;
  if (not BRes) and (not NTBres) then
    Exit;
  Move( OSVI, OSVI_NT, SizeOf(TOSVersionInfo) );

  case OSVI_NT.dwPlatformId of
     VER_PLATFORM_WIN32_NT:
       begin
         if OSVI_NT.dwMajorVersion <= 4 then
           Result := 'Windows NT ';
         if (OSVI_NT.dwMajorVersion = 5) and (OSVI_NT.dwMinorVersion = 0) then
           Result := 'Windows 2000 ';
         if  (OSVI_NT.dwMajorVersion = 5) and (OSVI_NT.dwMinorVersion = 1) then
           Result := 'Windows XP ';
         if (OSVI_NT.dwMajorVersion = 6) {and (OSVI_NT.dwMinorVersion = 0)} then
         begin
           if (OSVI_NT.dwMinorVersion = 0) then
           begin
               if (OSVI_NT.wProductType = VER_NT_WORKSTATION) then
                   Result := 'Windows Vista '
               else
                   Result := 'Windows Server 2008 ';

           end;

           if (OSVI_NT.dwMinorVersion = 1) then
           begin
               if (OSVI_NT.wProductType = VER_NT_WORKSTATION) then
                   Result := 'Windows 7 '
               else
                   Result := 'Windows Server 2008 R2 ';

           end;

           if (OSVI_NT.dwMinorVersion = 2) then
           begin
               if (OSVI_NT.wProductType = VER_NT_WORKSTATION) then
                   Result := 'Windows 8 '
               else
                   Result := 'Windows Server 2012 ';

           end;

           if Assigned(GetProductInfo) then
           begin
             GetProductInfo( dwOSMajorVersion, dwOSMinorVersion,
                             dwSpMajorVersion, dwSpMinorVersion,
                             pdwReturnedProductType );
             case pdwReturnedProductType of
               PRODUCT_BUSINESS://
                 tmpStr := 'Business Edition';
               PRODUCT_BUSINESS_N:
                 tmpStr := 'Business Edition';

               PRODUCT_CLUSTER_SERVER://
                 tmpStr := 'Cluster Server Edition';
               PRODUCT_CLUSTER_SERVER_V://
                 tmpStr := 'Server hyper Core V Edition';

               PRODUCT_CORE://
                 tmpStr := 'Windows 8';
               PRODUCT_CORE_N://
                 tmpStr := 'Windows 8 N';
               PRODUCT_CORE_COUNTRYSPECIFIC://
                 tmpStr := 'Windows 8 China';
               PRODUCT_CORE_SINGLELANGUAGE://
                 tmpStr := 'Windows 8 Single Language';

               PRODUCT_DATACENTER_EVALUATION_SERVER://
                 tmpStr := 'Server Datacenter Edition (Evaluation installation)';
               PRODUCT_DATACENTER_SERVER://
                 tmpStr := 'Server Datacenter Edition (full installation)';
               PRODUCT_DATACENTER_SERVER_CORE://
                 tmpStr := 'Server Datacenter Edition (core installation)';
               PRODUCT_DATACENTER_SERVER_CORE_V://
                 tmpStr := 'Server Datacenter without Hyper-V (core installation)';
               PRODUCT_DATACENTER_SERVER_V://
                 tmpStr := 'Server Datacenter without Hyper-V (full installation)';

               PRODUCT_ENTERPRISE://
                 tmpStr := 'Enterprise Edition';
               PRODUCT_ENTERPRISE_E://
                 tmpStr := 'Not supported';
               PRODUCT_ENTERPRISE_N_EVALUATION:
                 tmpStr := 'Enterprise N (evaluation installation) Edition';
               PRODUCT_ENTERPRISE_N:
                 tmpStr := 'Enterprise N Edition';
               PRODUCT_ENTERPRISE_EVALUATION:
                 tmpStr := 'Enterprise (evaluation installation) Edition';
               PRODUCT_ENTERPRISE_SERVER://
                 tmpStr := 'Server Enterprise Edition (full installation)';
               PRODUCT_ENTERPRISE_SERVER_CORE://
                 tmpStr := 'Server Enterprise Edition (core installation)';
               PRODUCT_ENTERPRISE_SERVER_CORE_V://
                 tmpStr := 'Server Enterprise without Hyper-V Edition (core installation)';
               PRODUCT_ENTERPRISE_SERVER_IA64://
                 tmpStr := 'Server Enterprise Edition for Itanium-based Systems';
               PRODUCT_ENTERPRISE_SERVER_V://
                 tmpStr := 'Server Enterprise without Hyper-V Edition (full installation)';

               PRODUCT_ESSENTIALBUSINESS_SERVER_MGMT://
                 tmpStr := 'Windows Essential Server Solution Management';
               PRODUCT_ESSENTIALBUSINESS_SERVER_ADDL://
                 tmpStr := 'Windows Essential Server Solution Additional';
               PRODUCT_ESSENTIALBUSINESS_SERVER_MGMTSVC://
                 tmpStr := 'Windows Essential Server Solution Management SVC';
               PRODUCT_ESSENTIALBUSINESS_SERVER_ADDLSVC://
                 tmpStr := 'Windows Essential Server Solution Additional SVC';

               PRODUCT_HOME_BASIC://
                 tmpStr := 'Home Basic Edition';
               PRODUCT_HOME_BASIC_E://
                 tmpStr := 'Not supported';
               PRODUCT_HOME_BASIC_N:
                 tmpStr := 'Home Basic N Edition';
               PRODUCT_HOME_PREMIUM://
                 tmpStr := 'Home Premium Edition';
               PRODUCT_HOME_PREMIUM_E://
                 tmpStr := 'Not supported';
               PRODUCT_HOME_PREMIUM_N:
                 tmpStr := 'Home Premium N Edition';
               PRODUCT_HOME_PREMIUM_SERVER:
                 tmpStr := 'Home Premium Server Edition';
               PRODUCT_HOME_SERVER:
                 tmpStr := 'Home Server Edition';

               PRODUCT_HYPERV:
                 tmpStr := 'Microsoft Hyper-V Server Edition';

               PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT:
                 tmpStr := 'Windows Essential Business Server Management Edition';
               PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING:
                 tmpStr := 'Windows Essential Business Server Messaging Edition';
               PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY:
                 tmpStr := 'Windows Essential Business Server Security Edition';

               PRODUCT_MULTIPOINT_STANDARD_SERVER:
                 tmpStr := 'Windows Multipoint Server Standard (full installation) Edition';
               PRODUCT_MULTIPOINT_PREMIUM_SERVER:
                 tmpStr := 'Windows Multipoint Server Premium (full installation) Edition';

               PRODUCT_PROFESSIONAL://
                 tmpStr := 'Professional Edition';
               PRODUCT_PROFESSIONAL_E://
                 tmpStr := 'Not Supported';
               PRODUCT_PROFESSIONAL_N://
                 tmpStr := 'Professional N Edition';
               PRODUCT_PROFESSIONAL_WMC://
                 tmpStr := 'Professional with Media Center Edition';

               PRODUCT_SB_SOLUTION_SERVER_EM://
                 tmpStr := 'Server For SB Solutions EM Edition';
               PRODUCT_SERVER_FOR_SB_SOLUTIONS://
                 tmpStr := 'Server For SB Solutions Edition';
               PRODUCT_SERVER_FOR_SB_SOLUTIONS_EM://
                 tmpStr := 'Server For SB Solutions EM Edition';

               PRODUCT_SERVER_FOR_SMALLBUSINESS:
                 tmpStr := 'Windows Server 2008 for Small Business Edition';
               PRODUCT_SERVER_FOR_SMALLBUSINESS_V:
                 tmpStr := 'Windows Server 2008 without Hyper-V for Small Business Edition';

               PRODUCT_SERVER_FOUNDATION:
                 tmpStr := 'Windows Server Foundation Edition';
               PRODUCT_SB_SOLUTION_SERVER://
                 tmpStr := 'Windows Small Business Server 2011 Essentials Edition';

               PRODUCT_SMALLBUSINESS_SERVER://
                 tmpStr := 'Small Business Server';
               PRODUCT_SMALLBUSINESS_SERVER_PREMIUM://
                 tmpStr := 'Small Business Server Premium Edition';
               PRODUCT_SMALLBUSINESS_SERVER_PREMIUM_CORE://
                 tmpStr := 'Small Business Server Premium (Core installation) Edition';

               PRODUCT_SOLUTION_EMBEDDEDSERVER://
                 tmpStr := 'Windows Multipoint Server';

               PRODUCT_STANDARD_EVALUATION_SERVER://
                 tmpStr := 'Server Standard Edition (evaluation installation)';
               PRODUCT_STANDARD_SERVER://
                 tmpStr := 'Server Standard Edition (full installation)';
               PRODUCT_STANDARD_SERVER_CORE://
                 tmpStr := 'Server Standard Edition (core installation)';
               PRODUCT_STANDARD_SERVER_V://
                 tmpStr := 'Server Standard without Hyper-V Edition';
               PRODUCT_STANDARD_SERVER_CORE_V://
                 tmpStr := 'Server Standard without Hyper-V Edition (core installation)';
               PRODUCT_STANDARD_SERVER_SOLUTIONS://
                 tmpStr := 'Server Solutions Premium';
               PRODUCT_STANDARD_SERVER_SOLUTIONS_CORE://
                 tmpStr := 'Server Solutions Premium (core installation)';

               PRODUCT_STARTER://
                 tmpStr := 'Starter Edition';
               PRODUCT_STARTER_E://
                 tmpStr := 'Not supported';
               PRODUCT_STARTER_N://
                 tmpStr := 'Starter N Edition';

               PRODUCT_STORAGE_ENTERPRISE_SERVER:
                 tmpStr := 'Storage Server Enterprise Edition';
               PRODUCT_STORAGE_ENTERPRISE_SERVER_CORE:
                 tmpStr := 'Storage Server Enterprise Edition (core installation)';
               PRODUCT_STORAGE_EXPRESS_SERVER:
                 tmpStr := 'Storage Server Express Edition';
               PRODUCT_STORAGE_EXPRESS_SERVER_CORE:
                 tmpStr := 'Storage Server Express Edition (core installation)';
               PRODUCT_STORAGE_STANDARD_EVALUATION_SERVER:
                 tmpStr := 'Storage Server Standard Edition (evaluation installation)';
               PRODUCT_STORAGE_STANDARD_SERVER:
                 tmpStr := 'Storage Server Standard Edition';
               PRODUCT_STORAGE_STANDARD_SERVER_CORE:
                 tmpStr := 'Storage Server Standard Edition (core installation)';
               PRODUCT_STORAGE_WORKGROUP_EVALUATION_SERVER:
                 tmpStr := 'Storage Server Workgroup Edition (evaluation installation)';
               PRODUCT_STORAGE_WORKGROUP_SERVER:
                 tmpStr := 'Storage Server Workgroup Edition';
               PRODUCT_STORAGE_WORKGROUP_SERVER_CORE:
                 tmpStr := 'Storage Server Workgroup Edition (core installation)';

               PRODUCT_UNDEFINED:
                 tmpStr := 'An unknown product';

               PRODUCT_ULTIMATE://
                 tmpStr := 'Ultimate Edition';
               PRODUCT_ULTIMATE_N:
                 tmpStr := 'Ultimate N Edition';

               PRODUCT_WEB_SERVER://
                 tmpStr := 'Web Server Edition';
               PRODUCT_WEB_SERVER_CORE://
                 tmpStr := 'Web Server Edition (core installation)';

               PRODUCT_UNLICENSED:
                 tmpStr := 'Unlicensed product';

             else
               tmpStr := '';
             end;{ pdwReturnedProductType }
             Result := Result + tmpStr;
             NTBRes := FALSE;
           end;{ GetProductInfo<>NIL }
         end;{ Vista }
         if NTBres then
         begin
           if OSVI_NT.wProductType = VER_NT_WORKSTATION then
           begin
             if OSVI_NT.wProductType = VER_NT_WORKSTATION then
             begin
               case OSVI_NT.wSuiteMask of
                 512: Result := Result + 'Personal';
                 768: Result := Result + 'Home Premium';
               else
                 Result := Result + 'Professional';
               end;
             end
             else if OSVI_NT.wProductType = VER_NT_SERVER then
             begin
               if OSVI_NT.wSuiteMask = VER_SUITE_DATACENTER then
                 Result := Result + 'DataCenter Server'
               else if OSVI_NT.wSuiteMask = VER_SUITE_ENTERPRISE then
                 Result :=  Result + 'Advanced Server'
               else
                 Result := Result + 'Server';
             end;
           end{ wProductType=VER_NT_WORKSTATION }
           else
           begin
             with TRegistry.Create do
               try
                 RootKey := HKEY_LOCAL_MACHINE;
                 if OpenKey{ReadOnly}('SYSTEM\CurrentControlSet\Control\ProductOptions', false) then
                   try
                     tmpStr := UpperCase(ReadString('ProductType'));
                     if tmpStr = 'WINNT' then
                       Result := Result + 'Workstation';
                     if tmpStr = 'SERVERNT' then
                       Result := Result + 'Server';
                   finally
                     CloseKey;
                   end;
               finally
                 Free;
               end;
             end;{ wProductType<>VER_NT_WORKSTATION }
           end;{ NTBRes }
         end;{ VER_PLATFORM_WIN32_NT }
     VER_PLATFORM_WIN32_WINDOWS:
       begin
         if (OSVI.dwMajorVersion = 4) and (OSVI.dwMinorVersion = 0) then
         begin
           Result := 'Windows 95 ';
           if OSVI.szCSDVersion[1] = 'C' then
             Result := Result + 'OSR2';
         end;
         if (OSVI.dwMajorVersion = 4) and (OSVI.dwMinorVersion = 10) then
         begin
           Result := 'Windows 98 ';
           if OSVI.szCSDVersion[1] = 'A' then
             Result := Result + 'SE';
         end;
         if (OSVI.dwMajorVersion = 4) and (OSVI.dwMinorVersion = 90) then
           Result := 'Windows Me';
       end;{ VER_PLATFORM_WIN32_WINDOWS }
     VER_PLATFORM_WIN32s:
       Result := 'Microsoft Win32s';
  else
    Result := 'Unknown';
  end;{ OSVI_NT.dwPlatformId }
end;{ GetOSInfo }

initialization
   @GetProductInfo := GetProcAddress(GetModuleHandle('KERNEL32.DLL'),
                                     'GetProductInfo');

end.

Comment: Por favor, arrume os erros de digitação e explique melhor. Sinceramente não entendi nada...
Comment: Nesse caso você pode tentar obter a versão do Windows pelo prompt de comando. Veja esse link http://www.windows-commandline.com/find-windows-os-version-from-command/  e também esse https://pablosoares.wordpress.com/2011/09/28/trabalhando-com-comandos-dos-no-delphi/
Comment: Olá Paruba! Obrigado, está função é a porém, o que ocorre é que o programa está marca omo compatibilidade, então a resposta da função não corresponde ao SO e sim a compatibilidade.
Comment: Perdoe. É a pressa. A função que passou foi a mesma que eu coloquei no início. O que ocorre para o programa responder o SO diferente no programa onde utilizo a função, é porque marco a compatibilidade no programa. Sabendo disto, se o meu sistema operacional é Windows 7 32 bits e o programa está marcado a compatibilidade com o Windows XP , a função irá retornar o 'Windows XP' utilizando está função. De qualquer forma obrigado. Abraços LMV


Select recursivo em hierarquia de dados mysql

Question: Como construir uma função mysql ou consulta recursiva para trazer o último descendente de um lado específico de uma árvore binária?
Satisfazendo uma árvore binária, cada nó pode ter apenas dois ramos, um a esquerda e outro a direita.
Como fazer para pegar em uma consulta o último descendente de um ramo do lado direito?
Por exemplo:
           a
     b           c
  d     e     f     g
 h     j k         z x

Neste conjunto de dados, o último descendente de "a", á direita é a letra "x", e na esquerda a letra "h".
Para chegar até 'h', passou por 'b' e 'd', partindo de 'a' e 'lft'.
O último descendente de "b" á direita é a letra "k", a esquerda é a letra "h".
Assim como, o último descendente de "e" á direita é a letra "k", mas a esquerda é a letra "j".
Cada letra(nó) desta árvore tem a estrutura normal de uma árvore em conjuntos aninhados ou Nested Set Model, para satisfazer outras necessidades do sistema.
Ou seja, os campos id, parent_id, left, right.
E além destes, o campo tipo enum: growth_to('lft','rgt'), para indicar se o filho foi criado a esquerda ou a direita.
Por exemplo:
b.growth_on = lft
c.growth_on = rgt

Com relação a seu pai("a"), o nó "b" cresceu para esquerda, e o nó "c" para direita.
Eu preciso criar uma função recursiva mysql aonde eu informe o id do pai, e o lado(lft ou rgt) que eu quero buscar o ultimo descendente e ele me retorne a letra correspondente e suas propriedades, ou até mesmo somente o id.
Eu sei que eu poderia controlar o posicionamento do nó abaixo de seu pai, apenas movendo os indices corretos, porém quando um nó tem apenas um filho, eu necessito saber se ele é da direita ou esquerda, mesmo que existindo um só, ele precisa possuir um "lado".
Eu penso que a lógica seria, criar uma condição recursiva dentro da função mysql.
Para buscar o último nó descendente de "a" á direita, informaria o id de "a" e growth_on = 'lft'
Então dentro de um loop: (que é a parte que eu não sei fazer com funções mysql)
where children.parent_id = a.id && children.growth_on = 'lft'

Comment: Você realmente precisa fazer isso no MySQL? E por que nessa exata representação (ela pode ser trivialmente convertida em outras, veja [esse artigo](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/))? Acredito que você acabará com uma solução razoavelmente complexa e com baixa performance. Eu traria isso para uma linguagem de programação. Se forem muitos dados utilizaria um bando de dados baseado em grafos (e.g. [Neo4j](http://neo4j.com/)).
Comment: A falta que um "connect by" faz ...
Comment: Eu já uso o Nested Set Model, ou "conjuntos aninhados", mas os meios normais, consideram que a árvore cresce equilibradamente, o que no meu caso, pode não ocorrer, digamos que "b" possa ter 34 filhos, enquanto "c", nenhum, então para este problema não imagino como resolver usando os meios normais. Alterar tipo de banco de dados não é uma opção no momento, realmente preciso de uma função mysql ou query recursiva, que atravesse a linha dos descendentes do lado selecionado.
Comment: @MarceloAymone eu concordo com a parte que o Anthony fala sobre fazer o trabalho usando uma linguagem de programação, no seu caso acho que deve ser PHP.
Comment: O que me incomoda nesta solução, é que teria que trazer toda a árvore para realizar a operação, se tiver mais de 100 níveis, ficaria absurdamente grande para calcular.
Comment: Por isso tem que ser com função...
Comment: Esse cara fez uma pergunta semelhante, já viu isso? Não pode lhe ajudar em algo? http://dba.stackexchange.com/questions/7147/find-highest-level-of-a-hierarchical-field-with-vs-without-ctes
Comment: Andei olhando já, vou tentar. Se conseguir posto a resposta.
Answer: O seguinte procedure recebe a ID do nó inicial, o "lado" que você quer checar e te retorna a id do último descendente encontrado, ou do próprio nó inicial caso este não possua descendentes no lado especificado :
DELIMITER //
CREATE PROCEDURE find_leaf(IN n_id VARCHAR(10), IN side VARCHAR(10), OUT child VARCHAR(10))
BEGIN
  IF side = 'left' THEN
    SET child = (SELECT leftN FROM node WHERE id=n_id);
  ELSE
    SET child = (SELECT rightN FROM node WHERE id=n_id);
  END IF;

  IF child IS NOT NULL THEN
    CALL find_leaf(child, side, child);
  ELSE
    SET child = n_id;
  END IF;
END //

Você pode ver o procedure funcionando aqui http://sqlfiddle.com/#!2/be812/3
Note que essa não é a melhor solução possível, apenas um esboço (funcional) da ideia. Além disso recursão de procedures é desabilitada por default no mysql (e não é possível em funções, apenas procedures), logo a invocação deve ser algo similar a isso:
SET max_sp_recursion_depth=255; -- habilita recursão, 255 é o nível máximo permitido
CALL find_leaf('a', 'rigth', @leaf);
SELECT @leaf;
CALL find_leaf('e', 'left', @leaf);
SELECT @leaf;

Obs: o schema que utilizei pode estar um pouco diferente do seu, mas deve ser simples adaptar:
CREATE TABLE node(
id VARCHAR(10) PRIMARY KEY,
parent_id VARCHAR(10) DEFAULT NULL,
leftN VARCHAR(10) DEFAULT NULL,
rightN VARCHAR(10) DEFAULT NULL,
growth_on ENUM('left', 'right') DEFAULT NULL
) ENGINE=INNODB;


What method should I use instead of Drupal\Core\Entity\Query\Sql\Query::addExpression()?

Question: I am using Entity Query to select nodes of two different types. The fetching seems to be working, but I want to sort the returned values. Both the content types have different date fields. I know I could do this with
$query->addExpression('COALESCE( field_date_1, field_date_2)', 'Date');
$query->sort('Date', 'DESC');

but addExpression() isn't an existing method, and the code throws this exception.

Error: Call to undefined method Drupal\Core\Entity\Query\Sql\Query::addExpression()

How can I sort on two or more date fields?
Answer: Entity queries don't support expressions. To get it around it, add a tag to the query:
$query->addTag('mymodule');

Then implement hook_query_alter(), check for the tag, and add the expression there instead:
function mymodule_query_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  if ($query instanceof Drupal\Core\Database\Query\SelectInterface && $query->hasTag('mymodule')) {
    $query->addExpression('...');
  }
}

Comment: Thanks, it worked and hook_query_TAG_alter() too works here. Adding for future references.


I want to store different categories of data in the 1 gb text file??(data in the sense,Input data(Plain text))I want to store that and access it

Question: Our project is to make Discussion Forum like stack overflow web site.But it is a command line application in python.We have to use only text file of 1 gigabyte space to store all the information(I do not want to use outer dependencies).Our discussion forum contains 6 categories. so i had got an idea that If i divide the file into blocks then i can store the each categories data in each block.If i store like that how to access it.if i went wrong lead me to the correct way please and be fast.
Comment: @user1922399 "if i went wrong lead me to the correct way" - So as Ashwini mentioned, correct way is to use a database.
Comment: Any code? What do you have so far?
Comment: No we had a constraint that not to use database.@AshwiniChaudhary
Comment: @PeterVaro I tried to keep delimiter at the start index and end of the each index using seek() function. If i do like that ,from start to end it is reading whole data as a single line
My code:
f=open("test1.txt",'wb')
f.write("@users@")
u_space=100*1024*1024
f.seek((u_space)-14)
f.write("@users@\n")

I don't want to use database. :(
Comment: I understand the reasons to not use a database. @user1022399 said verbosely that database is not an option. I guess he is expecting tips for search lookup on large file.
Answer: I suggest to create one more file for index - for quick access to specific post. The index entry should have constant length in bytes and entries should be sorted for fast lookup. For each entry in index file you need: unique identifier, offset (to simply do good old fseek on data file), and length of post. Because there will be no complex search performed on data file, just fseek X bytes and read Y bytes, you can safely have each post compressed (e.g. with gzip) in data file.
Another thing you have to consider - are the posts likely to change or are they immutable after posted? If they can be changed/edited/deleted, you have to implement defragmenting and reindexing of data file, because:

Length of specific post may get increased, requiring to shift all the posts stored after it.
Length of specific post may get decreased, leaving small gap in data file.
Post may be deleted, leaving big gap in data file.

It is up to you to choose strategy:

Growing post may be left in place, triggering immediate shift of posts stored after it and at least partial reindexing OR it may be moved to the end of the file, temporarily leaving a gap on it's former location.
Gaps may be removed by defragmenting and reindexing immediately or this task can be scheduled regularly.

About 6 categories of your forum: Category can be distinguished by first 3 bits (can distinguish max. 8 categories) or more safely 4 bits (max. 16 categories). Constant length of blocks in data file is not a good idea because categories are likely to hold very different amount of content. Furthermore it doesn't really help much in lookup.


How are the Ballon d'Or scores determined?

Question: The Ballon d'Or is presented by France Football and honours the male player deemed to have performed the best over the previous year. I've read that it is based on voting by football journalists but I haven't been able to find out

Who are the voting journalists and which countries are they from?
Whether the system is based on one vote per journalist, or are the votes weighted in any way?
Answer: First of all, let's look at the rules and regulation of Ballon d'Or published in 2016(Not able to find 2017 rules),

Only respected football Journalists will take part in the voting process (most of the Journalists will be from France, England, Spain, Germany and France Football media outlets.)

France Football article shows different jurors from France, Argentina, Japan, Mexico and Algeria who voted in favor of Cristiano Ronaldo, winner of Ballon d'Or 2017.

France Football will use a pool of 30 top players who Journalists can vote for.
The scoring system is likely to be the same. Every Journalists will pick his top three in preferred order. No.1 pick has 5 points, No.2 has 3 followed by 1 point for no.3 pick.

Article published by France Football shows few jurors vote which indicates they choose their first five pick.

France Football won't be revealing any top 3 finalists before the ceremony. Which means it will be a total surprise from voting process to announcement.
France Football has announced they will be revealing the winner in December every year. unlike the FIFA Ballon d'Or ceremony which took place on second Monday of January.

So,

Who are the voting journalists and which countries are they from?
Respected football journalists predominantly from France, England, Spain, Germany and France Football media outlets are the ones to take part in voting process.
Whether the system is based on one vote per journalist, or are the votes weighted in any way?
Jurors will pick their top players with different points per their order of selection (See rules above), which will be totaled to decide the eventual winner. For 2017 Ballon d'Or Cristiano won with 946 points with 176 jurors voting. See: The complete classification of the Ballon d'Or 2017
Answer: I just wanted to include a summary of the actual Jurors in the 2018 Ballon D'or Selection Process. I was not able to get this until this year.
You can see the jurors (each of whom is a respected sports journalist) and their ranking of the 5 best players.


add notty to authorized users

Question: I miss to understand the topic: a request from my corp's sec team.
while setting up an sftp with chroot they insist I've to (quoting) "add notty to authorized users".
to my knowledge the notty is the outcome of a login made by a user with no shell (e.g. an ssh user whose config bind her to sftp only and -to-say- has /usr/sbin/nologin configured).
what am I missing? any pointer on the openssh docs (redhat version 7)?
thank you
Answer: This looks like it's what you want: https://serverfault.com/a/354618/230046
It'll mean users in the sftponly group can only SFTP, not SSH.
Comment: Yep this is what we have setup... But sec in my company seems to not be happy until a mystic notty user will be added to some group... I start thinking they simply don't know what a sftp setup is...
Comment: I think they want you to add the option `notty` to the users? I'm sure if you show them the config and speak to your local friendly security person, you'll get it sorted!

add notty to authorized users


Finding the maximum likelihood estimate

Question: Currently, I have a likelihood function in the following form:
$$L(\lambda|\mathbf{x})=\prod_{i=1}^{n}(x_i+(-1)^{x_i}e^{-\lambda})$$
with $x_i$ taking on values of $0$ or $1$, $\lambda>0$.
I have tried taking $log$ and differentiating the likelihood function, but have been unable of finding the maximum likelihood estimate of $\lambda$, as the result becomes
$$\frac\partial{\partial\lambda}log(L(\lambda|\mathbf{x}))=\sum_{i=1}^n\frac{-1}{1-x_ie^\lambda}$$
Can anyone give me some hints on how to do that?
Answer: Assume that the number of $x_i=0$ in your dataset is $n_0$ and the number of $x_i=1$ is $n_1$. Your likelihood function is:
$$L(\lambda)=(e^{-\lambda})^{n_0}(1-e^{-\lambda})^{n_1}$$
and the log-likelihood is:
$$l(\lambda)=-\lambda n_0+n_1 \ln (1-e^{-\lambda})$$
It is easy to differentiate this function to obtain the following MLE:
$$\lambda = \ln \frac{n_0+n_1}{n_0}$$

Finding the maximum likelihood estimate


How to group by 3 columns and given count in Python DataFrames

Question: I have 3 columns, I want to do a count based on the common values in the 3 columns for eg
Dataframe is
Date     Name    SoldItem
15-Jul    Joe     TV
15-Jul    Joe     Fridge
15-Jul    Joe     Washing Machine
15-Jul    Joe     TV
15-Jul    Joe     Fridge
15-Jul    Mary    Chair
15-Jul    Mary    Fridge
16-Jul    Joe     Fridge
16-Jul    Joe     Fridge
16-Jul    Tim     Washing Machine
17-Jul    Joe     Washing Machine
17-Jul    Jimmy   Washing Machine
17-Jul    Joe     Washing Machine
17-Jul    Joe     Washing Machine

And final output should be

Date      Name   SoldItem       Count
15-Jul     Joe    TV              2
           Joe    Fridge          2
           Joe    Washing Machine 1
          Mary    Chair           1
          Mary    Fridge          1
16-Jul     Joe    Fridge          2
           Tim    Washing Machine 1
17-Jul     Joe    Washing Machine 3
         Jimmy    Washing Machine 1

I tried below code, but it works only on 2 columns
df.groupby(["Date", "Name"]).size()

provides like

Date      Name
15-Jul     Joe    5
          Mary    2
16-Jul     Joe    2
           Tim    1
17-Jul     Joe    3
         Jimmy    1
When i use the below
df.groupby(["Date", "Name", "SoldItem"]).size()

it throws the error

ValueError: Length of passed values is xx, index implies 0

This is how i load the dataframe

   fields = ['Date', 'Name', 'SoldItem']
   df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
   df_grp = df.groupby(["Date", "Name"]).size()
print df_grp

So would appreciate if you could kindly advise how I can group based on 3 values and provide the count. Much appreciated in advance. Also am new to Python.
Comment: do you have any missing values in your dataset ?
Answer: @user3423407
I saved your data as csv file and processed it as below.
import pandas as pd
fields = ['Date', 'Name', 'SoldItem']
df = pd.read_csv('PathToCSVFile.csv', skipinitialspace=True, usecols=fields)
df_grp = df.groupby(["Date", "Name", "SoldItem"]).size()
print(df_grp)

Got the output as below. I did not do any changes in your code. For the example dataset it works. Is it that it does not work for larger dataset?
Answer: I think you have some missing data in your dataset and that's why you are getting that Error. you probably want to look if there are any missing values because your code should be fine.
The problem are the NA (missing values) entries in your dataset. Each row in your dataset has at least one NA in that Column ( that's my own opinion). When you apply .groupby to NA entries, it wouldn't know how to group NAs so it removes them, leaving an empty result (length 0).
take a look here for References: https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html
https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html
below are examples that I copied from this Github link
https://github.com/pandas-dev/pandas/issues/23050
Example of simple Code which will produce the same Error
>>> df = pd.DataFrame({'A': ['x', 'y'], 'B': [np.nan, np.nan]})
>>> df.groupby(['A', 'B']).size()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.7/site-packages/pandas/core/groupby/groupby.py", line 1227, in size
    result = self.grouper.size()
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.7/site-packages/pandas/core/groupby/ops.py", line 233, in size
    dtype='int64')
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.7/site-packages/pandas/core/series.py", line 249, in __init__
    .format(val=len(data), ind=len(index)))
ValueError: Length of passed values is 2, index implies 0

Comment: Thanks this comment pointed me in the right direction. I replaced the null values with N.A and my code worked. Thanks guys
Comment: If you are going to copy someone's answer at least give them credit: [answer](https://github.com/pandas-dev/pandas/issues/23050#issuecomment-428002681). Your answer is not quite appropriate as the situation is different. But you are right that this is probably due to NA values.
Comment: I already copied all the references here.If I want to stole an answer than I wouldnt post here a reference from where i took that


Extreme Value Distribution

Question: I would appreciate a lead\tip on the next one:
Z is a standard random variable from the extreme value distribution.
I need to show that $Y=\sigma \cdot Z+\mu$ is an extreme value variable with parameters - $\sigma$ and $\mu$.
Answer: Assuming $\sigma > 0$, you could start with finding an expression for the $Y$'s cumulative distribution function:
$$
   F_Y(y) = \Pr\left(Y \leqslant y\right) = \Pr\left(\sigma Z + \mu \leqslant y\right) = \Pr\left(Z \leqslant \frac{y-\mu}{\sigma}\right) = F_Z\left(\frac{y-\mu}{\sigma}\right)
$$
By definition of the probability density function:
$$
    f_Y(y) = F_Z^\prime(y) = \frac{\mathrm{d}}{\mathrm{d}y} F_Z\left(\frac{y-\mu}{\sigma}\right) = f_Z\left(\frac{y-\mu}{\sigma}\right) \frac{1}{\sigma}
$$
Now use definition of $f_Z(z)$ and compare the so obtained density function $f_Y(y)$ with that of the extreme value distribution with parameters $\mu$ and $\sigma$.

Extreme Value Distribution


Manage event for recent app hardware button

Question: I want to handle hardware button for recent application button. I have tried with onUserLeaveHint() method, but it will call for both home button and recent app button. But, I don't want to override home button event. Any help appreciated.
Comment: Please add comment for down voting
Answer: You have to override first onKeyDown then write your code like below:-
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_HOME)) {
        System.out.println("KEYCODE_HOME");
        showDialog("'HOME'");
        return true;
    }
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        System.out.println("KEYCODE_BACK");
        showDialog("'BACK'");
        return true;
    }
    if ((keyCode == KeyEvent.KEYCODE_MENU)) {
        System.out.println("KEYCODE_MENU");
        showDialog("'MENU'");
        return true;
    }
    return false;
}

You can read this link
Comment: This is not working with a higher version. I have tried this solution.
Comment: what do you means by higher version?
Comment: Above 5.0. i have tested it on 7.0


Javascript function to create multi-dimensional arrays

Question: Haii
I want a function (pure javascript) (no jQuery) that creates multi-dimensional arrays.
I've made one that is completely hard-coded, and that limit the number of dimensions which I can dive deep.
function nestTriArray(first, second, third){
  const arr = new Array(first);
  for(let i=0; i<first; i++){
    arr[i] = new Array(second);
    for(let j=0; j<second; j++){
      arr[i][j] = new Array(third);
    }
  }
  return arr;
}

const test = nestTriArray(3,2,3);
console.log(test);

Outputs the CORRECT result:
//[[[undefined, undefined, undefined], [undefined, undefined, undefined]], [[undefined, undefined, undefined], [undefined, undefined, undefined]], [[undefined, undefined, undefined], [undefined, undefined, undefined]]]

I had another attempt to try and make it multi-dimensional in one function (rather than hard-coding a standalone function for fourth-dimension, fifth-dimension...) where I pass to the function an array, the length of the array is the number of dimensions, and each element represents the length of each sub-array.
It uses a recursive function.
And it outputs wrong.
That's the try:
function nestArray(conf_array/*first, second, third*/){
  conf_array = [1].concat(conf_array);
  const arr = [];

  let last_in_ref = arr;
  function re(index){
    last_in_ref[conf_array[index]] = new Array(conf_array[index+1]);
    for(let i=0; i<conf_array[index]; i++){
      last_in_ref[i] = new Array(conf_array[index+1]);
    }
    last_in_ref = last_in_ref[index];
    console.log(arr);
    index++;
    if(index < conf_array.length){re(index);}
  }

  re(0);

  return arr;
}

const test = nestArray([3,2,3]);
console.log(test);

Outputs WRONG:
//[[[undefined, undefined], [[undefined, undefined, undefined], [undefined, undefined, undefined], [[undefined], [undefined], [undefined], [undefined]]], [undefined, undefined], [undefined, undefined]], [undefined, undefined, undefined]]

Thanks in advance!!
Comment: Hey guys thanks alot really appreciate all the answers!!
Comment: So to sum it up, there's lots of ways to do it (Thankss!!). But outside of conciseness, which one will execute the fastest???
Answer: Here is a recursive implementation that accomplishes what you want:

function nestArray(arrDims) {
    const [head, ...tail] = arrDims;
    const arr = new Array(head);
    return tail.length > 0 ? arr.fill(0).map(() => nestArray(tail)) : arr;
}

console.log(nestArray([5]));
console.log(nestArray([4, 3, 2]));
Comment: Thans a lot. Plus it's so concise. Just perfect.
Answer: In the unlikely event you need these optimizations: Performance Tips
If you are trying to optimize by pre-initializing the arrays, read Avoid Creating Holes
reduceRight approach:

const nestedArray = (...args) => args.reduceRight((arr, length, i) =>
      Array.from({length}, _ => i ? arr : arr.map(x=>[...x])), Array(args.pop()))

let x
console.log(
    x=nestedArray(3,2,4)
)

x[0][0][0]=123

console.log(
    x
)

recursive approach:

const nestTriArray = (length, ...args) => {
  if(!args.length) return Array(length)
  return Array.from({length}, _=>[...nestTriArray(...args)])
}

const test = nestTriArray(3,2,1);
console.log(test);

test[0][0][0]=123
console.log(test);
Comment: thanks for the 2 approaches !! which one will perform faster?
Comment: In a micro-benchmark with very large arrays, for loop using only push and Array() constructor will probably be the fastest.  recursion approach of the above next.  fill-map will probably be better than Array.from.  In reality the difference is most of the time negligible and probably won't matter.
Comment: recursion without tail recursion runs the risk of a stack overflow if the amount of nesting is excessive
Answer: Here is variant with reduce
[Edit] fixed with shallow copy and reduceRight from comments.
const nestArray = arr =>
  arr.reduceRight((acc, v) => {
    return new Array(v).fill(null).map(()=> acc ? [...acc] : acc);
  }, undefined);

console.log(nestArray([2, 5, 7, 10]));
Comment: This is not correct.  You need to shallow clone [...acc] to avoid reusing the same reference.
Comment: FYI: you can use reduceRight instead of reverse.  Also, it's still pointing to the same reference on each iteration, just this time they're pointing to a clone.
Comment: It's telling me it contains a "circular object array" which I don't know what it is.
Comment: @user120242 you are right, tried to make it too concise.


Statistics question to apply bell curve to formula

Question: I am trying to write a formula that would give a person a score, based on a formula.
It's for a video game, and I have worked up a formula using aggregate stats like total kills divided by total deaths, win percentage, etc. They are all ratios.
I also would like to multiply this by the number of games that they have played, but I am finding this dramatically effects the score when people have massive amounts of games.
How would I normalize this over my population?
For instance:
Score = (Kills / Deaths) * (Wins / Games) * ( Games )
Is there anyway to give people credit for doing well over many games? I have people with 5000 games that have a massive score, even though the stats used in the rest of the formula are very bad.  I don't want to do 5000 / 2 or 5000 / .1 because the problem persists. I'd like to somehow apply a normal distribution
Thanks
Comment: Note that (Kills / Deaths) * (Wins / Games) * Games = (Kills / Deaths) * Wins.  If you first divide and then multiply by Games, they cancel out (assuming Games ≠ 0).
Comment: Just to clarify what you're asking for: would you prefer a player with 6000 wins out of 10000 games to have a significantly higher score than one with 600 wins out of 1000 games, or should their scores be about equal?  And what if the win counts were 2000 and 200 respectively?
Comment: The more games, their score would be slightly higher for holding such a good win percent.  But it's hard to find a formula to be 'slightly', it's a lot higher.  I need a way to slow down gain, but keep some gain, not nullify their efforts.
Comment: In that case, Gortaur's $G^\alpha$ solution looks good.  If you want even slower growth, you could also try $S = \frac K D \frac W G \log(G)$.
Answer: If you're worried about users with few games skewing your statistics (such as a user with one game and one win having a 100% wins-per-game ratio), part of the solution might be to use the rule of succession to estimate the "true" wins per game ratio as $$P_\text{win} = \frac{\text{Wins}+1}{\text{Games}+2}.$$
In effect, this is equivalent to adding one extra win and one extra loss to each player's statistics; from a Bayesian perspective, it is equivalent to assuming that any wins-per-game ratio is equally likely a priori (such that a random new player with no games would be expected to have a 50% wins-per-game ratio on average).  You can tweak the number of "extra" wins and losses (known as pseudocounts), possibly to fractional or even negative values, if you want to adopt some other beta distribution as the prior.
Comment: This was an issue, so we put a minimum games required for a score. My biggest problem is people with massive numbers of games.  I can't use a negative pseudocount because some people have min games, some people have had up to 10,000
Answer: So you would like to make a fair score. You're right, for a person who played too many games but still is not a good player, your score is not fair. This also depends on the information which you would like to store.

If you store only total of: $K$ (kills), $D$ (deaths), $W$ (wins) and $G$ Games then your current score $S_1$ is
$$
S_1 = \frac KD W
$$
so it does not depend on how often the player wins. I would advise to use here
$$
S_2 = \frac KD \frac WG
$$
which takes into account both personal-performance $\frac KD$ and team-performance $\frac WG$. What is the drawback of $S_2$ is that people who played couple of times but were lucky will have a high score, while good players with pure performance in the beginning will have the low score. Maybe that was the reason why you included $G$ in the formula. To avoid this situation you can also use
$$
S_3 = \frac KD \frac WG (G)^{\alpha} = \frac KD \frac {W}{G^{1-\alpha}}
$$
for $\alpha<1$. Then the overall number of games will still have the influence but less than the team-performance ratio $\frac WG$.
Finally, if you can also store the history of last $n$ games, where e.g. $n = \frac N2$ and $N$ is an average number of games for all players, then you can build up the score by
$$
S_4 = \frac{K_n}{D_n}\frac{W_n}{G_n}
$$
which takes into account only the last performance (e.g. here $K_n$ is the number of kills for the last $n$ games only).

Anyway, if you formulate what do you want to take into account, I hope the help will be more useful.
By the way, with regards to normal distribution: roughly speaking you use it to find an average accumulated over some "center" point. I do not think it's useful in you problem, you better can use Poisson-like distribution to assign less importance to the last games and more importance to new ones.
Comment: Noob Question: In your example, what is alpha? Is it a constant or a derived value?
Comment: @bladefist: $\alpha = 0.5$ for example. You can take whatever value you want in $[0,1)$. The bigger $\alpha$ the importance total number of games has.
Comment: Thanks for your help, I got some more to figure out but this has given me a great start


What is the difference between a floating point merge and an integer merge?

Question: In this paper, two cases have been considered for comparing algorithms - integers and floating points.
I understand the differences regarding these data types in terms of storage, but am not sure why there is a difference among these.
Why is there a difference in performance between the following two cases

Using merge sort on Integers
Using merge sort on Floating Points

I understand that it comes down to speed comparison in both the cases, the question is why these speeds might be different?
Answer: The paper states, in section 4, "Conclusion", "the execution time for merging integers on the CPU is 2.5X faster than the execution time for floating point on the CPU". This large a difference is surprising on the Intel Nehalem Xeon E5530 used in the measurements. However, the paper does not give information about source code, specific instructions or processor features used in the merge, compiler version, or other tools used. If the processor is used efficiently, there should be only very minor differences in the performance of an integer merge versus a floating-point merge. Thus, it seems likely that the floating-point code used in the test was inefficient and is an indicator of poor tools used rather than any shortcoming of the processor.
Answer: Merge sort has an inner loop of quite a bit of instructions. Comparing floats might be a little more expensive but only by 1-2 cycles. You will not notice the difference of that among the much bigger amount of merge code.
Comparing floats is hardware accelerated and fast compared to everything else you are doing in that algorithm.
Also, the comparison likely can overlap other instructions so the difference in wall-clock time might be exactly zero (or not).


Por que essa consulta retorna *?

Question: Por que essa consulta me retorna *?
select convert(varchar(2), 141)

Pensei que fosse a tabela ascii, porém o 141, não corresponde ao *.
Utilizo SQL Server 2008 R2
Comment: Qual é o banco que tu está usando?
Comment: Acho que depende do COLLATE. O * pode ser porque não tem um caractere válido para imprimir.
Comment: @JéfersonTavares SQL Server 2008 R2
Answer: Quando inteiros são convertidos implicitamente para um tipo de dados de caracteres, se o número inteiro for muito grande para caber no campo de caracteres, o SQL Server retorna o caractere 42 da Tabela ASCII, o asterisco (*).
Logo qualquer número com o tamanho maior que 2 caracteres irá retornar *. Caso você queira exibir o 141 é só aumentar a quantidade de caracteres:
select convert(varchar(3), 141)

Retorno: 141.
Fonte: Technet

Por que essa consulta retorna *?


Prove that $\frac{n}{2^n}$ is a null sequence from $\epsilon$ definition of limit

Question: I am trying to prove that $\frac{n}{2^n}$ is a null sequence using the $\epsilon$ definition of a limit. Now I chose to use the fact that $2^n  > n^2$ for $n > 4$. I said let $\epsilon > 0$ be given. Then for $n > 4$, $\vert\frac{n}{2^n}\vert < \vert\frac{n}{n^2}\vert = \vert\frac{1}{n}\vert.$ The value of $N$ that I chose in the definition of convergence was $[\frac{1}{\epsilon}]+4$. Would this value of $N$ work in this case? I obtained $[\frac{1}{\epsilon}]+1$ from rearranging $\vert\frac{1}{n}\vert < \epsilon$, but of course this would not necessarily guarantee that $n > 4$, which is what we need to produce the first inequality, hence why I added $3$ to this value.
Comment: What is $N$ in the definition of the limit?
Comment: Let $\varepsilon<\dfrac14$.
Comment: Since no one has decided to answer the question you asked, yes, that is a fine value of $N$ to choose.  As long as you explain in your formal proof why it is that you're adding $4$ as you did here, it should be fine.
Comment: Thank you, Bob. The other possibilities were also very insightful.
Answer: To show : $$ \forall \epsilon > 0, \exists X \in \mathbb{R}, \forall n>X : \left|\frac{n}{2^n}\right|< \epsilon.$$
Fix $\epsilon > 0$.
$$\left|\frac{n}{2^n}\right| < \epsilon \iff \frac{n}{2^n}< \epsilon   $$
$$~~~~~~~~~~~~~~~~~~~~~~ \iff \frac{n}{2^n} < \frac{n}{2} <\epsilon$$
This is for $n>1.$
Answer: A null sequence
eventually gets as small as you want.
Initial terms do not matter.
So you can start at $n=4$
or
$n=10000$
or
$n=10^{10^{10}}$.
All that matters is that,
for any $c > 0$,
there is a $N(c)$
such that
$|a_n| < c$
for $n > N(c)$.
Once you have shown that
there is a $m$ such that
$2^n > n^2$
for all $n > m$,
then,
since
$\dfrac{n}{2^n}
\lt \dfrac1{n}$
for $n > m$,
the rest is easy.


How to resize a W2003Srv basic partition in Vmvare player

Question: Environment
I have Windows 2003 server (XP)

Installed as virtual machine using Vmware Player 4.0.2
Primary partition is, as usual, C:-volume, where Windows is installed.
Partition type is basic, which cannot be resized with windows tools.

I don't want to convert the partition type to dynamic (can be laborious).

Question: What do I need to do to increase the size of C:-volume?
Comment: If you're going to post a Q/A in a single post, the correct procedure is to post a question and answer it yourself with the answer. Otherwise this "question" will just sit around forever in the un-answered list.
Comment: Seems that I can't answer my own question quite yet. When I tried to post an answer, I got this message: _Users with less than 100 reputation can't answer their own question for 8 hours after asking. You may self-answer in 7 hours. Until then please use comments, or edit your question instead._ I'll add my answer to the question section for now, and I'll add the answer later.
Comment: @Ciove, don't forget to approve your answer below.
Answer: Download SystemRescueCd ISO-image.
In Vmware player, when the virtual Windows 2003 server is not running:

increase the size of your disk: Virtual Machine / Virtual Machine settings / Hardware / Hard Disk / Utilities / Expand.
Change CD-drive to use the SystemRescueCd ISO-imagefile: Virtual Machine / Virtual Machine settings / Hardware / CD/DVD(IDE) / Use ISO image file / [browse to get the path to ISO-imagefile]
Edit your [computername].vmx -file (with notepad or similar), add this line:
<code>bios.bootDelay = "10000"
</code>

Start the virtual Windows 2003 server with SystemRescueCd

In virtual machine window hit the ESC -key (this may need some trickery: make sure the focus is in the virtual machine window, type Ctrl+G or click in the center of the window, when it goes black)
In Boot menu choose CD-ROM Drive
When SystemRescueCd asks for boot options choose default (first option).
When SystemRescueCd asks for keyboard language, type the number next to your keyboard language.
When SystemRescueCd has started type wizard (and hit Enter-key).

When wizard asks for graphic environment hit Enter.

When graphical desktop with Terminal window has opened type gparted (+Enter) in terminal window.
In gparted -window:

Wait for gparted to find partitions.
If the partition you need to change is not visible, click Gparted -menu and choose Devices
Click partition and click Partition -menu and Resize/Move.
In Resize/Move -window use slide control to resize your volume and click Resize/Move -button.
Back in gparted -window click green tick -icon to apply changes.
Close gparted -window.

In terminal window type shutdown now (+Enter).
Wait for "... or type Control-D to continue..." -text to appear.
In virtual machine window (type Ctrl+Alt to shift focus) click Virtual Machine / Power / Power off.


Nodejs Child Process on another server using server to server communication

Question: I want to run the child process using node js from one server to another. I have a too heavy process to run that causing my main server to work slowly so I want to run my heavy processes on another server that will perform heavy tasks like data modifications and return a buffer of that data but I could not find similar like this.
For example, I have server A that is running my website and users are sharing their content using this. When the users' traffic jumps to high my server will get slow because of data like images, videos upload, and pdf report generating on the basic images, videos and serving the site content. I want to perform these tasks on server B, so that server A will only work for data serving and traffic management.
Answer: Apparently at this point you probably need to split your webserver frontend routes into different worker servers.
Let's suppose you're using Nginx as a website frontend. If you're not, then your first step would be to setup an nginx webfront.
1 - If haven't done so, serve all public static content (like pdf files, videos, images, etc.) directly from nginx using different rules for static content and node server routes:
Something as basic as this:
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         http://127.0.0.1:5000;
    }

    location /static {
        root /dir/to/my/static/files; # here you have your videos, images, etc.
    }
}

2 - Now, if you need to separate your node server onto 2 services, you can just create 2 (or more) nginx proxy rules:
server {
    listen 80;
    server_name example.com;

    location /api {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         http://127.0.0.2:5000;  # server 2
    }

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         http://127.0.0.1:5000;  " server 1
    }

    location /static {
        root /dir/to/my/static/files;
    }
}

That way example.com/api/* routes will go to your secondary Node server (on ip 127.0.0.2), example.com/static will be served directly by Nginx at blazing fast speeds, while the non-mapped routes will be served by the default main node server on 127.0.0.1.
There are many ways to setup proxies and optimize Nginx so that it can, for instance, go through a pool of node servers in round-robin fashion, and you can also compress data and use protocols like HTTP/2 to take the load off the slower node-based webserver (ie. Express).
Comment: Okay, I know how to map static data like videos images pdf on another server but my question is regarding how to upload videos using a child process. I don't want to put a load on my server A.
Comment: Then just create a proxy in nginx for the upload server or process for the upload location path `location /my/upload/url` so that uploads go to a different server.


classpath file from maven dependency plugin for java command line

Question: I want to get the maven dependency of a project and use it as a classpath for my command line project (windows batch).
This is what I did as per the maven dependency plugin in my batch file.
call mvn dependency:build-classpath -Dmdep.outputFile=test.txt
java -cp `cat test.txt` com.hqly.main.Hqly

But the cat command is not getting executed and the classpath is not getting set correctly. Its not seeing my main class.
Am getting the below error while trying to execute
[INFO] --- maven-dependency-plugin:2.1:build-classpath (default-cli) @ hqly ---
[INFO] Skipped writing classpath file 'C:\Users\chandrans1\Desktop\GitHub\hqly\test.txt'.  No changes found.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.926s
[INFO] Finished at: Mon Jun 16 15:44:39 BST 2014
[INFO] Final Memory: 8M/109M
[INFO] ------------------------------------------------------------------------
Exception in thread "main" java.lang.NoClassDefFoundError: test/txt`
Caused by: java.lang.ClassNotFoundException: test.txt`
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: test.txt`.  Program will exit.

Answer: Unlike Linux, Windows does not use back-ticks as a way of passing the result of a command as a program argument.
You can check this question for some ideas on how to work around this limitation in Windows: Batch equivalent of Bash backticks. Something like this following should work:
for /f %%i in (test.txt) do set HSQLY_CLASSPATH=%%i
echo Classpath is "%HSQLY_CLASSPATH%"
java -cp %HSQLY_CLASSPATH% com.hqly.main.Hqly

Comment: Thanks @Duncan, edited your answer which worked for me.
Comment: @SajanChandran Ah yes, I left `cat` in there which won't really help on Windows :-)


Migrated content type fields not showing

Question: I'm trying to migrate custom content types with attached fields from Drupal 7 to Drupal 8. Using drush migrate commands I can successfully migrate all content types, but I have problem with fields.
First I run upgrade_d7_field migration, than upgrade_d7_field_instance and last migration is upgrade_d7_node_MY_CONTENT_TYPE_NAME_content.
If I go to Structure -> Content types and then open my custom content type (by pressing Manage fields) I can see all fields attached to it - everything is ok. If I choose Content from main menu and try to create new content for my content type I only see Title field, no more fields are displayed. Same are with migrated content - if I 'm trying to edit it, I see only title.
What I'm missing ? I have migrated data in Drupal 8 fields table - node_field_MY_FIELD_NAME. I am logged in as admin user, so I should have all permissions to view this fields.
Answer: It sounds like the fields might be disabled on the entity form.
Goto Structure -> YOUR CONTENT TYPE -> Manage form display
Then move the fields you are expecting to see in the form from Disabled (bottom) to Content.  You can also control the display order from there.
Answer: I had the same problem on a Drupal 8.9 site today. I went to Administration > Configuration > Content Authoring > Text formats and editors and clicked on Configure next to 'Full HTML.' That page showed an error that a null filter type would be deleted after I saved the current filter, so I clicked "Save" without making any other changes. The error was gone, and now my content is being displayed as expected.


'DecisionTreeClassificationModel' object has no attribute 'stages'

Question: tree = dtModel.stages[-1]
print(tree) #visualize the decision tree model

AttributeError                            Traceback (most recent call
last)
AttributeError: 'DecisionTreeClassificationModel' object has no
attribute 'stages'

Please click the picture link to see more details. Thanks
Answer: Stages are used for pipeline models, if you fit your model using pipeline you can call model.stages.
Here is one example.
For normal decision tree models you should just call model.toDebugString
Hope this answers your question.


Boolean Algebra POS of $F(A,B,C,D)=\bar{B}A(\bar{C}D+\bar{B})+(B\bigoplus C)$

Question: I need to find SOP and POS of: $F(A,B,C,D)=\bar{B}A(\bar{C}D+\bar{B})+(B\bigoplus C)$.
I found the SOP, but I struggle with the POS of this one.
Can anyone give me a clue on how to start?
Thanks, I appreciate that!
Comment: Once you have the SOP, you can always get the POS from that: keep distributing the OR over AND
Comment: Sure!  Simple example:  AB + CD = (A+CD)(B+CD) = (A+C)(A+D)(B+C)(B+D) .... which you can also do in just one step (it's really just the algebraic FOIL principle ... but it generalizes to any number of disjuncts with any number of conjuncts
Comment: @Bram28 I wondered what SOP and POS meant, but your comment clarified that they mean DNF and CNF, respectively.
Comment: @Bram28 Sounds good! DO you have an example so I can understand more? Thanks!
Comment: @Bram28 Great! Thank you for that! :)
Comment: @AndreasBlass What? I am teaching AndreasBlass something?  That's a first! :P   Anyway, yes, computer engineers like to use the + and . notation, and as such they talk about SOP (Sum of Products) and POS (Product of Sums) :)
Answer: $$F(A,B,C,D)=B'A(C'D+B')+(B\oplus C)\\
$$
$$
\Longrightarrow B'A(C'D+B')+B'C+BC'\\
\Longrightarrow B'(C+AB'+AC'D)+BC'\\
$$
Using elimination and a factoring theorem:
$$
(X+Y)(X'+Z)=XZ+X'Y
$$
we have
$$
\Longrightarrow (B+C+A+AC'D)(B'+C')\\
\Longrightarrow (A+B+C)(B'+C')\\
$$
Noting that $X+YY'=X$
$$
\Longrightarrow (A+B+C+DD')(AA'+B'+C'+DD')
$$
Also $(X+YZ)=(X+Y)(X+Z)$
$$
\Longrightarrow (A+B+C+D)(A+B+C+D')(A+B'+C'+D')(A+B'+C'+D)(A'+B'+C'+D')(A'+B'+C'+D)
$$
Comment: Thank you mate, unfortunately this is not POS you ended up with, but I will try take it from there, thanks!
Comment: @CalculusLover if you may, please point out my mistake, or can you send me the required POS ? I'd love to learn from it
Comment: Sure: $ ( +  +  + )( +  +  + ̅)( + ̅ + ̅+ )( + ̅ + ̅
+ ̅)(̅+ ̅ + ̅+ )(̅+ ̅ + ̅+ ̅)$
Comment: @CalculusLover oh is that what you meant, I earlier assumed that you want a minimal POS, I've edited the last part in regards to that


Bonferroni correction: Whats exactly is meant by "multiple tests"?

Question: The Bonferroni correction seems to be quite controversial. But I read again and again that it should be used for multiple tests. But what exactly are multiple tests? If I have three different data sets in the same study and run only one t-test on each data set, is that a multiple test and do I have to apply a Bonferroni correction?
Or am I only talking about multiple testing if I have one data set and do three tests on the same data set?
I find the statements when it comes to the Bonferroni correction very unclear and would be grateful for your expertise.
Comment: Related https://stats.stackexchange.com/questions/206592/why-arent-multiple-hypothesis-corrections-applied-to-all-experiments-since-the
Comment: Probably helpful too, although on a different level: https://xkcd.com/882/
Answer: The answer for almost all questions that I see here regarding multiple comparison 'corrections' such as Bonferroni is that the desirability of their application depends on things that are usually not mentioned in the question! That means that any really accurate and balanced answer has to be very long. I will not make this long enough, but will point you to my best attempt long-form answer: A Reckless Guide to P-values : Local Evidence, Global Errors
What is the nature of your study and what are your inferential objectives? Is the study a preliminary one that might be though of a 'hypothesis generating' or is it intended to be a standalone 'definitive' account? You might be more interested in the evidential meaning of the data more than the long run error rate consequences of your statistical procedures.
The controversy that you mention might well be a consequence of people being unwilling to imagine that not every user of statistical approaches share their particular purposes and circumstances.
Are the null hypotheses of the several tests the same, or related, or independent? Are any of the data shared across tests?
'Corrections' for multiplicity always come at the cost of reduced power. In other words, they trade off type II errors for extra protection against a category of type I errors. Given your inferential objectives, is that trade-off going to render your designed balance of false positive and false negative errors undesirable? Did you design that balance with the 'correction' in mind? Did you design that balance at all, or are you relying on the arbitrary p<0.05?


2 MX dns round robin for with same domain name for Exchange 2010

Question: I have an Exchange 2010 server that is visible under 2 MX records mx.acme.com and mx1.acme.com with 2 different IP addreses from 2 different network providers. They both report as mx.acme.com when someone is sending us an email and they both report as mx.acme.com when we send email. But for now the 2nd MX (and ip address that is sending the email has actually different domain name, reverse dns then the one it's reporting when it connects to other servers.
The problem is I don't know which IP Address will be used to send email out so I was thinking to setup same mx.acme.com record in DNS for both Ip addresses, and same Reverse DNS for both at both providers.
Will that work just fine or I'm missing something? I guess then I just have to add one MX record and not two as it would be meaningless to add 2nd.
Current setup looks more or less like this:
MX record: acme.com IN MX 5 mail1.acme.com
A record: mail1.acme.com IN A 192.168.10.17
MX record: acme.com IN MX 10 mail2.acme.com
A record: mail2.acme.com IN A 192.168.10.18

And I would like to change it to:
MX record: acme.com IN MX 5 mail.acme.com
A record: mail.acme.com IN A 192.168.10.17
A record: mail.acme.com IN A 192.168.10.18

As it's the only way I think this will go. The problem I can see is if one Ip address is down and dns will be pointing the server to it no matter what then some mails will bounce off. And I guess for that round-robin to work i will need TTL 0 so DNS (at hosting has to allow that).
Comment: What exactly do you want to achieve here?
Are there any problems with your current setup?
I think the 2x MX records is a better way of doing it, than the round-robin DNS.
Comment: The problem is that if mails go out thru 2nd ip address on one server they got: `4.7.1 Client host rejected: cannot find your hostname`. When actually i checked and the ip address resolves but it resolves just it doesn't match the name.
Comment: I guess it could be the other server but apparently (so says on Wiki) some servers report unknown host if the RevDNS doesn't match DNS,
Comment: So, the best thing would be to get both IP Addresses to resolve to mail.acme.com. I'm sure your provider can help you with that?
Comment: Yes and i will do that. But the question is should I change the DNS of those ip addresses as well to mail.acme.com or leave it as it is.. Because if i will change it I get Round Robin DNS
Comment: Come to think of it that mail servers won't be able to verify this anyways since DNS may respond with different IP per test so I guess just by fixing revdns to be on both ip's mail.acme.com should make it work even if DNS for 2nd ip will be something different.
Comment: Right, I think the target mailserver only does a RDNS lookup, which has to match what it gets from `EHLO`. I don't think the Round Robin DNS will help you in any way, as the MX entries are already supposed to provide failovering.
Comment: It's more to solve the problem then actually to have failover working. So I'll go with RevDns only. Thanks.
Comment: Please provide an answer so I can give you points.
Answer: You should change your Reverse DNS entries for both IP Addresses to match your EHLO domain mail.acme.com.
This should get rid of your problem :
4.7.1 Client host rejected: cannot find your hostname


How to evaluate an integral that comes out as undefined

Question: How do I evaluate $\int_0^{\pi}\frac{1}{5+3\cos{x}}dx$? Because for this type of integral I would normally use the substitution $t=\tan{\frac{x}{2}}$ but $\tan{\frac{\pi}{2}}$ is undefined. How can I evaluate this integral still using this method (I want to still use this method because it is the method my school expects me to use)?
Comment: @Quippy I'll have to think about this : I'm also thinking about whether the $+\infty$ causes a problem at all. You see, forgetting about the limits of the integral which are $0$ and $\pi$, the *indefinite* integral $\int \frac 1{5 + 3 \cos x}$ can be evaluated using the substitution $ u= \tan \frac x2$ to equal $\frac{-1}{2} \tan^{-1}(2 \cot(\frac x2))$. The point is that $0$ and $\pi$ can be substituted into this anti-derivative , even if there's infinities lurking, because $\tan^{-1}(\infty) = \frac \pi 2$. For a 2 mark question I'd say realizing this reflects the marking scheme better.
Comment: Break it in two and use limits...
Comment: Note that $\lim_{x\to\pi^-}t=+\infty$, so you get $\int_0^{+\infty}\dots\,\mathrm{d}t$, etc.
Comment: @TeresaLisbon If it helps, they gave you the graph of $y=\frac{1}{5+3\cos{x}}$, I tried to use symmetry by instead evaluating up to the limit of $2\pi$ then having it but when I substituted those limits it came out as $0$ because I left my indefinite form as $\frac12\tan^{-1}\left(\frac12\tan\left(\frac{x}{2}\right)\right)$.
Comment: @Quippy The graph doesn't help get the exact value, beyond the fact that it might show some symmetries (the same symmetries that I used to create my earlier decomposition, if you like). I think Jean-Claude's link is the key that explains why the $2 \pi$ issue arises. Basically, your substitution has to be a bijective substitution on the interval, and $\tan \frac x2$ has this property on $[0,\pi]$ but not $[0,2 \pi]$. So that's something to keep in mind. I think the hacky method, unfortunately, seems to be the 2-mark method here.
Comment: @TeresaLisbon Thanks for your help, yeah I think our school isn't looking for an extremely solid method so I'll just go with the inverse tan of infinity identity
Comment: @Quippy You're welcome! I would suggest that you self-answer your question, +1.
Comment: @abiessu Could you show me what using limits looks like in this case?
Comment: @Quippy Your integral seems to be having $dx$ missing.
Comment: @Quippy You can try evaluating yourself but I can tell you that the integrals value is $\frac{\pi}{4}$
Comment: [This](https://math.stackexchange.com/questions/1173023/integrate-a-rational-function-with-a-denominator-in-the-form-a-cosx) is how the tan method works with a cosine in the denominator. There should be no difference in the execution, I think.
Comment: @TeresaLisbon, I understand how the substitution works, it's only that when changing the limits, the top limit becomes $\tan{\frac{\pi}{2}}$ which is undefined
Comment: @Quippy Good point. To relieve ourselves of that, let's write it as $\int_0^{\frac \pi 2} \frac{1}{5+3 \cos x} dx + \int_{\frac \pi 2}^{\pi} \frac 1{5+3 \cos x} dx$. The second integral, by a change of variable $u = \pi - x$ becomes $-\int_{\frac \pi 2}^0 \frac{1}{5-3 \cos u}du$. Now, has the infinity problem vanished?
Comment: @TeresaLisbon Is there a way I can do this without evaluating a second integral? Because this question is worth only two marks in the past paper and the part beforehand asked me to find the indefinite integral.
Comment: Nevertheless, I will keep thinking about this, because even the above to me seems a little hacky. There must be a better way.
Comment: Are you familiar with some complex analysis/residue calculus? If so, there is a very nice solution to your problem this way.
Comment: @jasnee Unfortunately I'm not, if you have any alternative ways, as long as it's at a highschool level then it should be fine.
Answer: Use $\cos x=\frac{1-\tan^2(x/2)}{1+\tan^2(x/2)}$, then
$$I=\int_{0}^{\pi} \frac{dx}{5+3\cos x}=\int_{0}^{\pi}\frac{\sec^2(x/2) dx}{8+2\tan^2(x/2)}.$$
$\tan(x/2)=t \implies \sec^2(x/2)dx=2dt$
$$I=\int_{0}^{\infty} \frac{dt}{4+ t^2}=\frac{1}{2} \tan^{-1} t/2|_0^{\infty}=\frac{\pi}{4}.$$
Answer: Self answer after comment discussion;
$\int_0^{\pi}\frac{1}{5+3\cos{x}}dx=\int_0^{+\infty}\frac{1}{5+3\left(\frac{1-t^2}{1+t^2}\right)}\frac{2}{1+t^2}dt$ after the substitution of $t=\tan\left(\frac{x}{2}\right)$
$=\int_0^{+\infty}\frac{2}{8+2t^2}dt$
$=\sqrt{2}\int_0^{+\infty}\frac{\sqrt{2}}{(2\sqrt{2})^2+(\sqrt2t)^2}dt$
$=\frac{\sqrt{2}}{2\sqrt2}\tan^{-1}\left(\frac{\sqrt2\times\infty}{2\sqrt2}\right)-\frac{\sqrt{2}}{2\sqrt2}\tan^{-1}\left(\frac{\sqrt2\times0}{2\sqrt2}\right)$
$=\frac12\tan^{-1}{(+\infty)}$
$=\frac{\pi}{4}\because\tan^{-1}{(+\infty)}=\frac{\pi}{2}$


Mostrar um  ao clicar em um determinado

Question: Sou inexperiente em javascript, e gostaria de uma ajuda nesse caso:
Tenho dois selects em meu documento:
<select id="estado">
<option value="MG">MG</option>
<option value="SP">SP</option>
<option value="RJ">RJ</option>
<option value="RJ">BA</option>
</select>
<select id="cidade">
<option value="Belo Horizonte">Belo Horizonte</option>
<option value="Betim">Betim</option>
<option value="Contagem">Contagem</option>
</select>

O comportamento esperado é que, ao clicar em um option do estado, ele substitua o select de id=cidade. Acredito que document.write seja a solução, porém, o conteúdo a ser substituído deve ser levado em conta a ordem do option clicado no select id=estado e não seu value.
Por exemplo:
O primeiro option substitui o select cidade para:
<select id="cidade">
<option value="Sou o primeiro">Sou o primeiro</option>
</select>

O segundo option substitui o select cidade para:
<select id="cidade">
<option value="Sou o segundo">Sou o segundo</option>
</select>

O terceiro substitui o select cidade para:
<select id="cidade">
<option value="Sou o terceiro">Sou o terceiro</option>
</select>

O quarto substitui o select cidade para:
<select id="cidade">
<option value="Sou o quarto">Sou o quarto</option>
</select>

O problema maior é que estes valores a serem substituidos devem ter referência pela ordem no select estado, e não pelo seu value.
Ou seja, não importa o value do terceiro option do select #estado, não importa se será SP, RJ, MG ou BA, ele ao ser clicado, vai substituir o outro select com o terceiro código acima. Se clicar no segundo option, substitui pelo segundo código.
Bem é isso. Agradeço a todos que ajudarem.
Comment: Você quer substituir o `select#cidade` por inteiro ou somente o seu "Conteúdo", as ``? Acho que não entendi bem a sua pergunta
Comment: Você está usando alguma lib, como `jQuery` por exemplo?
Comment: Você quer que ao selecionar um estado, no select de cidades seja carregada uma lista das respectivas a aquele estado?
Comment: @RichardDias Não estou usando bibliotecas. A idéia é que, ao clicar no primeiro option do #estado, substitua a lista #cidade pela Lista referente ao primeiro option. Ou seja, não importa os values, a substituição é fixa pela ordem do primeiro, segundo, teceiro option. Pode ser somente o conteúdo das option, ou o que for mais fácil.
Comment: Boni, neste tipo de situação, te aconselho a fazer o carregamento do segundo select com AJAX. Caso tenha alguma dúvida de como fazê-lo, apenas me diga qual tecnologia está usando no Server-Side, PHP, Ruby, C#, etc. Se for apenas uma atividade acadêmica, você pode manter listas com as cidades, e apenas recarregar o conteúdo.
Comment: @TobyMosque É uma atividade bem simples, não precisa de AJAX não. Não é preciso levar em consideração as cidades. Como falei, os códigos da primeira, segunda, teceira opção são fixos, o código do primeiro option deve aparecer independente do value que possua. E assim vai para o segundo, terceiro, etc.
Comment: A pergunta e... qual a necessidade disso? Explique-nos, quem sabe não consigamos entender melhor e ajuda-lo
Answer: Como esclarecido pelo Autor da pergunta, o importante aqui é a obtenção do indice do option selecionado.
segue um novo exemplo:

//pre-consulta para obter os selects #master e #details
var master = document.getElementById("master");
var details = document.getElementById("details");

master.onchange = function () {
  //necessario para poder utilizar o método indexOf nos options de #master
  var options = master.querySelectorAll("option");
  options = Array.prototype.slice.call(options);

  //recuperando o option selecionado
  selected = Array.prototype.filter.call(options, function(option) {
      return option.selected;
  });

  //recuperando o indice do option selecionado, caso não exista uma option selecionado, atribuir 0.
  var indice = 0;
  if (selected != null && selected.length == 1)
      indice = options.indexOf(selected[0]);

  //caso nenhum option seja selecionado ou se o option default for selecionado, desativar #details.
  details.disabled = indice == 0;
  details.readOnly = indice == 0;

  //atualizando os valores de #details.
  details.innerHTML = '';
  if (indice != 0) {
    var option = document.createElement("option");
    option.innerHTML = "Indice Selecionado: " + indice;
    details.appendChild(option);
  }
};

  Master:
  <select id="master" >
    <option>Selecione um Valor</option>
    <option>Primeiro</option>
    <option>Segundo</option>
    <option>Terceiro</option>
    <option>Quarto</option>
  </select>

  Details:
  <select id="details" >
  </select>

Comment: Obrigado, mas não é isso o que queria. Não sei se expressei direito, mas esqueça as cidades. A questão é a seguinte: não importa o value do option que seja escolhido, se for o primeiro option, mostra no outro select uma lista de options pré-definida, independente se é MG ou CE. Se for o segundo option, aí mostrará outro select com outra lista. O que diferencia as listas de options geradas não é o value, e sim a ordem que estão os options do primeiro select.
Comment: Resposta atualizada.
Comment: Era isso mesmo. Obrigado.

Mostrar um  ao clicar em um determinado


Apply label to multiple files in the same folder

Question: I am using VS.NET 2012 and TFS 2013. I needed to apply label to multiple text files in the same folder. But "Apply Label" is disabled when multiple text files are selected.
It looks like label can be applied to the folder or to a single file but not multiple files in the same folder.
One option I see is to edit the label and add files later. Is there other way to apply label to multiple text files in the same folder?
Comment: I have edited your title. Please see, "[Should questions include "tags" in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not".
Comment: http://stackoverflow.com/questions/7691988/misunderstanding-labels-in-tfs-vs-2010
Answer: Using Visual Studio, labels can only be created against a single item in version control; i.e. a branch or folder (which includes all files under it automatically) or an individual file.
Using the command line you can select the files you want by supplying one or more item specs, something like this will work:
tf label MyLabel *.txt
Source: http://msdn.microsoft.com/en-us/library/9ew32kd1.aspx


How to use Regex pattern in HTML text input

Question: I would like to restrict a text input field in a HTML5 form. I need it only value from 1 to 5
My code is
 <input type="text" name="count" pattern="[1-5][0-9-.]{1,10}" value="1" required>

Do match (Expectation):
1
1.5
1.584
2
4.68756
5

Don't match (Expectation):
0
.5
0.99
01
05
5.1
6
[a-zA-Z] and other special characters

Now happened (the problem):

Not validate non decimal values (1,2,3,4 and 5).
Validates 5.1 to 5.9
Comment: @Wiktor Stribiżew .. where is my answer? please read question completely before mark as duplicate
Comment: @Wiktor Stribiżew now i edit my question
Comment: Try [`pattern="[1-4](?:\.\d+)?|5(?:\.0+)?"`](https://regex101.com/r/aYnU3Q/1)
Comment: Thanks.. its works perfectly
Answer: You may use
pattern="[1-4](?:\.\d+)?|5(?:\.0+)?"

It gets parsed as ^(?:[1-4](?:\.\d+)?|5(?:\.0+)?)$ by HTML5 engine. See the regex demo.
Details

^(?: - start of string and start of a non-capturing group
[1-4] - a digit from 1 to 4
(?:\.\d+)? - an optional sequence of . and 1+ digits (fractional part may contain any number of any digits)
| - or
5 - matches 5
(?:\.0+)? - an optional sequence of . and 1+ zeros (fractional part may contain any number of zeros if the whole part is 5)
)$ - end of the outer "container" group and end of string.

To allow leading zeros, use
pattern="0*(?:[1-4](?:\.\d+)?|5(?:\.0+)?)"
         ^^^^^                          ^