Debugar Proc no banco de dados sql server 2014

Question: Uso o Sql Server 2014. Estou com problemas em Stored procedure, pois ao executar com determinados filtros, me dispara esse erro:

Mensagem 512, Nível 16, Estado 1, Procedimento
  SP_CMO_SEL_PORTARIA_INATIVOS, Linha 485 Subquery returned more than 1
  value. This is not permitted when the subquery follows =, !=, <, <= ,> >, >= or when the subquery is used as an expression.

Pelo erro, dá para ver que uma subquery está retornando mais de uma registro e isso pode ser um Where mal formado e etc...
Como eu faço para quando eu executar essa proc, eu consigo parar exatamente na linha do erro. Aí diz linha 485, mas ao ir até a linha 485, parece que está tudo ok e pode ser mais em cima e veio estourar nessa linha um erro que aconteceu antes, sei lá, não sei se isso é possível.
Fiz conforme o colega Ismael orientou e me retornou isso:

Err Nº: 512 | Severidade: 16 | Estado: 1 | Procedure:
  SP_CMO_SEL_PORTARIA_INATIVOS | Linha: 389 | Erro: Subquery returned
  more than 1 value. This is not permitted when the subquery follows =,
  !=, <, <= , >, >= or when the subquery is used as an expression.
  Mensagem 50000, Nível 1, Estado 16

Só que a linha 389 não tem nada nela, está em branco e ela está em cima do BEGIN TRY.
Meu bloco de código da Proc está assim:
........
BEGIN TRY
                            IF @ID_XFC_GRP <> '' OR @ID_XFC_Inicial <> 0
                                BEGIN
                                    SELECT  #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_UNI_EMP,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.RAM_ATV,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DT_LAU_PER,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DT_NASC_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_MAE_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.IR_SEX_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SUS_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_RG_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_CPF_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DS_END,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_CID_END,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.SG_UF_END,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_FUN_ULT,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_SET_ULT,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_PER_CPC_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_ADM_PER_CPC_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_DMS_PER_CPC_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_PER_FUN_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_EMP,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_UNI_EMP,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_SET_UNI,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.NM_SET_UNI,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.NM_FUN,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DT_INI_PER_FUN_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DT_FNL_PER_FUN_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DS_MAT_CTO,
                                            isNull( OIT1980LEITURA.DT_RX, EXAME_RAIOX.DT_EXM_REA ) DT_RX,
                                            OIT1980LEITURA.RX_NUM,
                                            EXAME_RAIOX.DS_OBS_EXM_REA AS DS_RAIOX,
                                            ESPIROMETRIA.CVF_PRE,
                                            ESPIROMETRIA.CVF_MED,
                                            Replace(Cast(ESPIROMETRIA.CVF_POR as varchar(7)), '.', ',') as CVF_POR,
                                            ESPIROMETRIA.CVF_LMT,
                                            ESPIROMETRIA.VEF_PRE,
                                            ESPIROMETRIA.VEF_MED,
                                            Replace(Cast(ESPIROMETRIA.VEF_POR as varchar(7)), '.', ',') as VEF_POR,
                                            ESPIROMETRIA.VEF_LMT,
                                            ESPIROMETRIA.VEF_CVF_PRE,
                                            ESPIROMETRIA.VEF_CVF_MED,
                                            ESPIROMETRIA.VEF_CVF_POR,
                                            ESPIROMETRIA.VEF_CVF_LMT,
                                            ESPIROMETRIA.FEF_PRE,
                                            ESPIROMETRIA.FEF_MED,
                                            Replace(Cast(ESPIROMETRIA.FEF_POR as varchar(7)),'.', ',') as FEF_POR,
                                            ESPIROMETRIA.FEF_LMT,
                                            EXAME.DS_OBS_EXM_REA AS DS_ESPIROMETRIA,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DS_DTLH_CLSS,
                                            CIDADE_UNIDADE.NM_CID_END AS CIDADE
                                            , EXAME.DT_EXM_REA DT_EXA_EXP
                                            , NM_EMP,
                                            (   Select NO_TEL_UNI_EMP From t_cmo_unidade
                                                Where ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP ) Telefone,
                                            (   Select DS_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) Endereco,
                                            (   Select NM_BRR_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) Bairro,
                                            (   Select CD_CEP From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) CEP,
                                            (   Select NM_CID_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) Cidade,
                                            (   Select SG_UF_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) UF

                                       FROM #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO
                                            LEFT OUTER JOIN #T_SP_CMO_SEL_REL_FICHA_ADMISSAO
                                            ON #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC = #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_XFC

                                            LEFT OUTER JOIN #T_SP_CMO_SEL_REL_FICHA_FUNCAO
                                            ON #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC = #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_XFC

                                            LEFT OUTER JOIN T_CMO_OIT1980_LEITURA OIT1980LEITURA
                                            ON OIT1980LEITURA.ID_OIT_LET = 1
                                            AND OIT1980LEITURA.ID_OIT = (SELECT ID_OIT FROM T_CMO_OIT1980
                                                                                WHERE ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   ID_EXM = 3936
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0)--NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                                                    )
                                            LEFT OUTER JOIN T_CMO_EXAME_REALIZADO AS EXAME_RAIOX
                                                                                ON  EXAME_RAIOX.NO_SEQ_AVA_LAU_PER = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER
                                                                                AND EXAME_RAIOX.ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND EXAME_RAIOX.ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   ID_EXM = 3936
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0)--NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                            LEFT OUTER JOIN T_CMO_ESPIROMETRIA ESPIROMETRIA
                                                             ON  ESPIROMETRIA.ID_EXP = (SELECT ID_EXP FROM T_CMO_ESPIROMETRIA
                                                                                WHERE ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   (ID_EXM = 1514 OR ID_EXM = 3136)
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0) --NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                                                                )
                                            --PARA PEGAR A OBS DA ESPIROMETRIA
                                            LEFT OUTER JOIN T_CMO_EXAME_REALIZADO AS EXAME
                                            ON  EXAME.NO_SEQ_AVA_LAU_PER = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER
                                            AND EXAME.ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                            AND EXAME.ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   (ID_EXM = 1514 OR ID_EXM = 3136)
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0) --NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                            left outer join T_CMO_ENDERECO AS CIDADE_UNIDADE
                                                ON  CIDADE_UNIDADE.id_emp = @ID_EMP
                                                and CIDADE_UNIDADE.id_uni_emp = @ID_UNI_EMP
                                                and CIDADE_UNIDADE.IR_TIP_END = 'U'

                                     WHERE  #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP = @ID_EMP
                                        AND #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP = @ID_UNI_EMP
                                        AND #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC in(SELECT ID_XFC FROM #FUNCIONARIOS_INATIVOS)

                                        --AND YEAR(EXAME.DT_EXM_REA) BETWEEN @DT_DE_LAUDO AND @DT_ATE_LAUDO

                                        ORDER BY #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC,
                                                 #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_ADM_PER_CPC_XFC,
                                                 #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DT_INI_PER_FUN_XFC

                                END
                            ELSE
                                BEGIN
                                    SELECT  #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_UNI_EMP,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.RAM_ATV,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DT_LAU_PER,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DT_NASC_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_MAE_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.IR_SEX_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SUS_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_RG_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_CPF_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DS_END,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_CID_END,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.SG_UF_END,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_FUN_ULT,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_SET_ULT,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_PER_CPC_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_ADM_PER_CPC_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_DMS_PER_CPC_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_PER_FUN_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_EMP,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_UNI_EMP,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_SET_UNI,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.NM_SET_UNI,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.NM_FUN,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DT_INI_PER_FUN_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DT_FNL_PER_FUN_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DS_MAT_CTO,
                                            OIT1980LEITURA.DT_RX,
                                            OIT1980LEITURA.RX_NUM,
                                            EXAME_RAIOX.DS_OBS_EXM_REA AS DS_RAIOX,
                                            ESPIROMETRIA.CVF_PRE,
                                            ESPIROMETRIA.CVF_MED,
                                            Replace(Cast(ESPIROMETRIA.CVF_POR as varchar(7)), '.', ',') as CVF_POR,
                                            ESPIROMETRIA.CVF_LMT,
                                            ESPIROMETRIA.VEF_PRE,
                                            ESPIROMETRIA.VEF_MED,
                                            Replace(Cast(ESPIROMETRIA.VEF_POR as varchar(7)), '.', ',') as VEF_POR,
                                            ESPIROMETRIA.VEF_LMT,
                                            ESPIROMETRIA.VEF_CVF_PRE,
                                            ESPIROMETRIA.VEF_CVF_MED,
                                            ESPIROMETRIA.VEF_CVF_POR,
                                            ESPIROMETRIA.VEF_CVF_LMT,
                                            ESPIROMETRIA.FEF_PRE,
                                            ESPIROMETRIA.FEF_MED,
                                            Replace(Cast(ESPIROMETRIA.FEF_POR as varchar(7)),'.', ',') as FEF_POR,
                                            ESPIROMETRIA.FEF_LMT,
                                            EXAME.DS_OBS_EXM_REA AS DS_ESPIROMETRIA,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DS_DTLH_CLSS,
                                            CIDADE_UNIDADE.NM_CID_END AS CIDADE
                                            , EXAME.DT_EXM_REA DT_EXA_EXP
                                            , NM_EMP,
                                            (   Select NO_TEL_UNI_EMP From t_cmo_unidade
                                                Where ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP ) Telefone,
                                            (   Select DS_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) Endereco,
                                            (   Select NM_BRR_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) Bairro,
                                            (   Select CD_CEP From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) CEP,
                                            (   Select NM_CID_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) Cidade,
                                            (   Select SG_UF_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) UF

                                       FROM #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO
                                            LEFT OUTER JOIN #T_SP_CMO_SEL_REL_FICHA_ADMISSAO
                                            ON #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC = #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_XFC

                                            LEFT OUTER JOIN #T_SP_CMO_SEL_REL_FICHA_FUNCAO
                                            ON #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC = #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_XFC

                                            LEFT OUTER JOIN T_CMO_OIT1980_LEITURA OIT1980LEITURA
                                            ON OIT1980LEITURA.ID_OIT_LET = 1
                                            AND OIT1980LEITURA.ID_OIT = (SELECT ID_OIT FROM T_CMO_OIT1980
                                                                                WHERE ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   ID_EXM = 3936
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0)--NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                                                    )
                                            LEFT OUTER JOIN T_CMO_EXAME_REALIZADO AS EXAME_RAIOX
                                                                                ON  EXAME_RAIOX.NO_SEQ_AVA_LAU_PER = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER
                                                                                AND EXAME_RAIOX.ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND EXAME_RAIOX.ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   ID_EXM = 3936
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0)--NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                            LEFT OUTER JOIN T_CMO_ESPIROMETRIA ESPIROMETRIA
                                                             ON  ESPIROMETRIA.ID_EXP = (SELECT ID_EXP FROM T_CMO_ESPIROMETRIA
                                                                                WHERE ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   (ID_EXM = 1514 OR ID_EXM = 3136)
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0) --NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                                                                )
                                            --PARA PEGAR A OBS DA ESPIROMETRIA
                                            LEFT OUTER JOIN T_CMO_EXAME_REALIZADO AS EXAME
                                            ON  EXAME.NO_SEQ_AVA_LAU_PER = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER
                                            AND EXAME.ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                            AND EXAME.ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   (ID_EXM = 1514 OR ID_EXM = 3136)
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0) --NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                             left outer join T_CMO_ENDERECO AS CIDADE_UNIDADE
                                                ON  CIDADE_UNIDADE.id_emp = @ID_EMP
                                                and CIDADE_UNIDADE.id_uni_emp = @ID_UNI_EMP
                                                and CIDADE_UNIDADE.IR_TIP_END = 'U'

                                     WHERE  #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP = @ID_EMP
                                        AND #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP = @ID_UNI_EMP
                                        AND #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC  IN (SELECT ID_XFC FROM #FUNCIONARIOS_INATIVOS)
                                        --AND EXISTS(SELECT ID_XFC FROM #T_SP_CMO_SEL_REL_FICHA_ADMISSAO
                                                                --WHERE #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_ADM_PER_CPC_XFC < @DT_ADM
                                                            --AND #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                    --)

                                        --AND YEAR(EXAME.DT_EXM_REA) BETWEEN @DT_DE_LAUDO AND @DT_ATE_LAUDO

                                        ORDER BY #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC,
                                                 #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_ADM_PER_CPC_XFC,
                                                 #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DT_INI_PER_FUN_XFC
                                END
                            END TRY
                            BEGIN CATCH

                                DECLARE @_ERROR_PROCEDURE VARCHAR(MAX)
                                SET @_ERROR_PROCEDURE = 'Err Nº: ' + CAST(ERROR_NUMBER() AS VARCHAR(10)) +
                                     ' | Severidade: '+ CAST(ERROR_SEVERITY() AS VARCHAR(10)) +
                                     ' | Estado: ' + CAST(ERROR_STATE() AS VARCHAR(10)) +
                                     ' | Procedure: '+ ISNULL(ERROR_PROCEDURE(),'') +
                                     ' | Linha: '+ CAST(ERROR_LINE() AS VARCHAR(10)) +
                                     ' | Erro: '+ ERROR_MESSAGE()

                                RAISERROR(@_ERROR_PROCEDURE,1,16)

                            END CATCH
........

Setei uma variável do tipo int assim:
declare
@Contador int = 0

IF @ID_XFC_GRP <> '' OR @ID_XFC_Inicial <> 0
                                BEGIN
                                set @Contador = 8
                                    SELECT  #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_UNI_EMP,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.RAM_ATV,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DT_LAU_PER,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DT_NASC_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_MAE_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.IR_SEX_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SUS_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_RG_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_CPF_XFC,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DS_END,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_CID_END,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.SG_UF_END,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_FUN_ULT,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NM_SET_ULT,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_PER_CPC_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_ADM_PER_CPC_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_DMS_PER_CPC_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_PER_FUN_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_EMP,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_UNI_EMP,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_SET_UNI,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.NM_SET_UNI,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.NM_FUN,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DT_INI_PER_FUN_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DT_FNL_PER_FUN_XFC,
                                            #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DS_MAT_CTO,
                                            isNull( OIT1980LEITURA.DT_RX, EXAME_RAIOX.DT_EXM_REA ) DT_RX,
                                            OIT1980LEITURA.RX_NUM,
                                            EXAME_RAIOX.DS_OBS_EXM_REA AS DS_RAIOX,
                                            ESPIROMETRIA.CVF_PRE,
                                            ESPIROMETRIA.CVF_MED,
                                            Replace(Cast(ESPIROMETRIA.CVF_POR as varchar(7)), '.', ',') as CVF_POR,
                                            ESPIROMETRIA.CVF_LMT,
                                            ESPIROMETRIA.VEF_PRE,
                                            ESPIROMETRIA.VEF_MED,
                                            Replace(Cast(ESPIROMETRIA.VEF_POR as varchar(7)), '.', ',') as VEF_POR,
                                            ESPIROMETRIA.VEF_LMT,
                                            ESPIROMETRIA.VEF_CVF_PRE,
                                            ESPIROMETRIA.VEF_CVF_MED,
                                            ESPIROMETRIA.VEF_CVF_POR,
                                            ESPIROMETRIA.VEF_CVF_LMT,
                                            ESPIROMETRIA.FEF_PRE,
                                            ESPIROMETRIA.FEF_MED,
                                            Replace(Cast(ESPIROMETRIA.FEF_POR as varchar(7)),'.', ',') as FEF_POR,
                                            ESPIROMETRIA.FEF_LMT,
                                            EXAME.DS_OBS_EXM_REA AS DS_ESPIROMETRIA,
                                            #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.DS_DTLH_CLSS,
                                            CIDADE_UNIDADE.NM_CID_END AS CIDADE
                                            , EXAME.DT_EXM_REA DT_EXA_EXP
                                            , NM_EMP,
                                            (   Select NO_TEL_UNI_EMP From t_cmo_unidade
                                                Where ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP ) Telefone,
                                            (   Select DS_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) Endereco,
                                            (   Select NM_BRR_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) Bairro,
                                            (   Select CD_CEP From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) CEP,
                                            (   Select NM_CID_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) Cidade,
                                            (   Select SG_UF_END From t_cmo_endereco
                                                Where IR_TIP_END = 'U' and ID_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP and ID_UNI_EMP = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP    ) UF

                                       FROM #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO
                                            LEFT OUTER JOIN #T_SP_CMO_SEL_REL_FICHA_ADMISSAO
                                            ON #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC = #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.ID_XFC

                                            LEFT OUTER JOIN #T_SP_CMO_SEL_REL_FICHA_FUNCAO
                                            ON #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC = #T_SP_CMO_SEL_REL_FICHA_FUNCAO.ID_XFC

                                            LEFT OUTER JOIN T_CMO_OIT1980_LEITURA OIT1980LEITURA
                                            ON OIT1980LEITURA.ID_OIT_LET = 1
                                            AND OIT1980LEITURA.ID_OIT = (SELECT ID_OIT FROM T_CMO_OIT1980
                                                                                WHERE ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   ID_EXM = 3936
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0)--NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                                                    )
                                            LEFT OUTER JOIN T_CMO_EXAME_REALIZADO AS EXAME_RAIOX
                                                                                ON  EXAME_RAIOX.NO_SEQ_AVA_LAU_PER = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER
                                                                                AND EXAME_RAIOX.ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND EXAME_RAIOX.ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   ID_EXM = 3936
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0)--NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                            LEFT OUTER JOIN T_CMO_ESPIROMETRIA ESPIROMETRIA
                                                             ON  ESPIROMETRIA.ID_EXP = (SELECT ID_EXP FROM T_CMO_ESPIROMETRIA
                                                                                WHERE ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   (ID_EXM = 1514 OR ID_EXM = 3136)
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0) --NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                                                                )
                                            --PARA PEGAR A OBS DA ESPIROMETRIA
                                            LEFT OUTER JOIN T_CMO_EXAME_REALIZADO AS EXAME
                                            ON  EXAME.NO_SEQ_AVA_LAU_PER = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER
                                            AND EXAME.ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                            AND EXAME.ID_EXM_REA = (SELECT MAX(ID_EXM_REA) FROM T_CMO_EXAME_REALIZADO
                                                                                WHERE ID_XFC = #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC
                                                                                AND   (ID_EXM = 1514 OR ID_EXM = 3136)
                                                                                AND   NO_SEQ_AVA_LAU_PER = ISNULL(#T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.NO_SEQ_AVA_LAU_PER, 0) --NO_SEQ_AVA_LAU_PER, para filtro por avaliação
                                                                                )
                                            left outer join T_CMO_ENDERECO AS CIDADE_UNIDADE
                                                ON  CIDADE_UNIDADE.id_emp = @ID_EMP
                                                and CIDADE_UNIDADE.id_uni_emp = @ID_UNI_EMP
                                                and CIDADE_UNIDADE.IR_TIP_END = 'U'

                                     WHERE  #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_EMP = @ID_EMP
                                        AND #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_UNI_EMP = @ID_UNI_EMP
                                        AND #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC in(SELECT ID_XFC FROM #FUNCIONARIOS_INATIVOS)

                                        --AND YEAR(EXAME.DT_EXM_REA) BETWEEN @DT_DE_LAUDO AND @DT_ATE_LAUDO

                                        ORDER BY #T_SP_CMO_SEL_PORTARIA_FUNCIONARIO.ID_XFC,
                                                 #T_SP_CMO_SEL_REL_FICHA_ADMISSAO.DT_ADM_PER_CPC_XFC,
                                                 #T_SP_CMO_SEL_REL_FICHA_FUNCAO.DT_INI_PER_FUN_XFC

                                END
                            ELSE
                                BEGIN
                                set @Contador = 9

No catch fiz isso:
BEGIN CATCH

                                DECLARE @_ERROR_PROCEDURE VARCHAR(MAX)
                                SET @_ERROR_PROCEDURE = 'Err Nº: ' + CAST(ERROR_NUMBER() AS VARCHAR(10)) +
                                     ' | Severidade: '+ CAST(ERROR_SEVERITY() AS VARCHAR(10)) +
                                     ' | Estado: ' + CAST(ERROR_STATE() AS VARCHAR(10)) +
                                     ' | Procedure: '+ ISNULL(ERROR_PROCEDURE(),'') +
                                     ' | Linha: '+ CAST(ERROR_LINE() AS VARCHAR(10)) +
                                     ' | Erro: '+ ERROR_MESSAGE() +
                                     ' | Contador: ' + CAST(@Contador AS VARCHAR(10))

                                RAISERROR(@_ERROR_PROCEDURE,1,16)

                            END CATCH

O valor impresso para Contador foi o 8, então acho que o problema está no select abaixo dele.
Answer: Uma forma de realizar o debug que normalmente utilizo em minhas Store Procedures é com o uso do TRY / CATCH. Veja um exemplo:
Observe que o SQL inicia a contagem conforme a query que você criou.
Sempre vai incluir todas as linhas em branco do início ou após o GO.
DROP PROCEDURE TESTE_PRO   --outra query
GO                         --separador
                           --LINHA 1 -> mesmo em branco já faz parte da procedure
                           --LINHA 2
CREATE PROCEDURE TESTE_PRO --LINHA 3
AS
BEGIN TRY
                           --LINHA 6
                           --LINHA 7
    DECLARE @TE1 INT;
    DECLARE @TE2 INT;

    SET @TE1 = 0

    SET @TE2 = 1/0;        --LINHA 13
END TRY

BEGIN CATCH
    DECLARE @_ERROR_PROCEDURE VARCHAR(MAX)
    SET @_ERROR_PROCEDURE = 'Err Nº: ' + CAST(ERROR_NUMBER() AS VARCHAR(10)) +
                            ' | Severidade: '+ CAST(ERROR_SEVERITY() AS VARCHAR(10)) +
                            ' | Estado: ' + CAST(ERROR_STATE() AS VARCHAR(10)) +
                            ' | Procedure: '+ ISNULL(ERROR_PROCEDURE(),'') +
                            ' | Linha: '+ CAST(ERROR_LINE() AS VARCHAR(10)) +
                            ' | Erro: '+ ERROR_MESSAGE()

    RAISERROR(@_ERROR_PROCEDURE,1,16)
END CATCH

GO
EXEC TESTE_PRO

O RAISERROR vai retornar os dados que escolhi, inclusive o número da linha que ocorreu a exceção pelo comando ERROR_LINE().

Err Nº: 8134 | Severidade: 16 | Estado: 1 | Procedure: TESTE_PRO | Linha: 13 | Erro: Erro de divisão por zero.
  Msg 50000, Level 1, State 16

Obs: Eu coloquei todos esses dados no catch porque depois eu o salvo em um log.
Atualização da resposta
Execute um sp_helptext teste_pro  e veja exatamente como o SQL fará a enumeração das linhas.
Comment: Tem como colocar parte da sua proc? Recrie a procedure em uma nova query. Somente a procedure, de forma que a primeira linha na IDE seja o `create proc`.
Comment: Coloquei o código referente ao retorno da Proc na edição do post.
Comment: Você tem que postar o código desde o início, pq de lá que iremos contar as linhas.
Comment: Fiz um debug tipo javascript com `Alert()`. Criei uma variável do tipo int e fui setando a variável em cada bloco. A última Impressão que eu peguei no catch, foi 8, isso quer dizer que o erro aconteceu logo a seguir, senão teria imprimido 9 e não 8.
Comment: @pnet Atualizei a resposta com um comando que vai te ajudar.
Comment: @pnet Todos os *subselects* internos que são utilizados como coluna ou nos `where` onde a sintaxe é **campo = subconsulta** (desde que não use qualquer função de agregação como o sum, max etc) poderiam ser garantidos com um `TOP 1`.
Comment: Entendi. O insert que dei no banco, é que quebrou tudo, mas vou considerar, só que não posso alterar muito essa proc. Não fui quem fiz e tá osso entender o negócio aqui.


How to migrate a .NET PCL Project to .NET Standard 2.0

Question: I have a solution with PCL and .NET Core 1.0 projects.
Once updated to VS 2017 15.3, when I navigate to the project properties I have a "Application" page for .NET Core 1.0 Projects where I can change from 1.0 to 2.0. Unfortunately the PCL projects only shows the standard "Library" page with an extra "Learn More" link that navigates me to a ".NET Standard" web page but no option to migrate to .NET Standard 2.0. All the rest is the same and it only allows me to change the usual Targets. No reference to anything else related to .NET Standard.
Do I have to recreate the projects as .NET Standard 2.0 myself?
Comment: Isn't recreating a way to go?
Answer: For pcl:

Create .Net Standard library project
Modify the csproj file manually  to Multi Target:
Suppose that your pcl is: portable-net45+win8+wpa81+wp8
<code> <Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
     <TargetFrameworks>netstandard2.0;portable-net45+win8+wpa81+wp8</TargetFrameworks>
   </PropertyGroup>
</code>
note TargetFrameworks  by s not  TargetFramework
Copy past your source
Install nuget packages, or reference them manually in csproj, example:
<code><ItemGroup>
   <PackageReference Include="Microsoft.CSharp" Version="4.3.0" />
</ItemGroup>
</code>
It's supposed that pcl is compiled without errors, in netstandrd2 you may find errors, modify your source as needed.
Modify Unit test projects and be sure that  you passed all tests in both environment.


Can someone please explain the following code? to retrieve the diagonal of a matrix using haskell?

Question: mainDiag :: [[a]] -> [a]
mainDiag x = zipWith (!!) x [0..]

Can someone please explain this code (particularly zipWith (!!)) and how it returns the diagonal of the matrix?
Comment: Hello, welcome to Stack Overflow! Could you please [edit] your question to give some more details of what parts you don't understand? For example, do you understand what `zipWith` does? Since this is your first Haskell question, it's hard for us to know your skill level.
Answer: Using informal notation, you can visualize zipWith as this:
zipWith f [x0,x1,x2,...] [y0,y1,y2,...] = [f x0 y0, f x1 y1, f x2 y2, ...]

In your case, zipWith (!!) x [0..] we have
x = [x0,x1,x2,...]
[0,1,2,...] = [y0,y1,y2]  (that is yn=n for all natural n)
(!!) = f

Hence, the result is
[(!!) x0 0, (!!) x1 1, (!!) x2 2, ...]

which is also written as
[x0 !! 0, x1 !! 1, x2 !! 2, ...]

This list contains the element in position 0 from the list x0, the one in position 1 from list x1, and so on. This is, therefore, the diagonal of the original list-of-lists x.
Answer: zipWith takes a two parameter function and two list. Returns the list of the results of applying the function to each pair of arguments comming from each list. Example:
zipWith (+) [1,2,3] [4,5,6] = [5,7,9] -- [1 + 4, 2 + 5, 3 + 6]

Using your example
mainDiag :: [[a]] -> [a]
mainDiag x = zipWith (!!) x [0..]

mainDiag [[1,2,3],[4,5,6], [7,8,9]] = [[1,2,3] !! 0, [4,5,6] !! 1, [7,8,9] !! 2] -- expanding the expresion
                                    = [1, 5, 9]


Is System.Threading.Tasks available in Visual Studio 2010 Express?

Question: Recently i start to learn about parallel programming. In that i like to apply parallel for so i need System.Threading.Tasks namespace. Now i am using Visual Studio 2010 Express edition. Is this option available in that edition?I tried in this edition but it not come.but i used another option of .netframework like ZIP method in that same edition.
Comment: yes i tried but unable to use that namespace
Answer: The namespace was introduced in the .NET 4.0 framework, so unless you target an earlier framework, it will be available.
Answer: Yes. It's avaiable in all versions of Visual Studio 2010, because it it part of the .NET-Framework
Answer: you can use system.threading.tasks but with Visual Studio Express there is no support for multi-thread debugging i believe
Answer: Yes.  It is part of the .Net 4 framework.


Find the coefficient of Taylor series

Question: What is the coefficient of $x^n$ for the Taylor series $(1+x)^p$? What is the interval of convergence (R)?
I can write the Taylor series as-
$$f(x) = 1+px+\frac{p(p-1)}{2!}x^2 +\frac{p(p-1)(p-2)}{3!}x^3 +... $$
But I can't find the general formula $(a_n)$ for the coefficient of $x^n$.
Comment: Hint: Binomial coefficient.
Comment: I tried the formula $a_n=\frac{p!}{n!(p-n)!}$ but it does not produce correct answer when $n=p+1$. For example, when $p=2$ and $n=3$, the formula gives $-\frac13$ while the coefficient is $a_3=0$.
Comment: The Taylor series in this case is a polynomial of degree $p$.  $\binom{p}{n}=0 \text{ for } n >p.$  Also, $(-1)! \ne -1$
Comment: That's where I got confused. So n>p terms are undefined for that particular Taylor series?
Answer: We recall the Taylor series expansion of $f$ around $x=0$ is given as
\begin{align*}
f(x)=\sum_{n=0}^\infty \frac{f^{(n)}(0)}{n!}x^n\tag{1}
\end{align*}

We assume $p$ is a non-negative integer. In this case the function $f(x)=(1+x)^p$ can be written according to the binomial theorem as
  \begin{align*}
f(x)&=(1+x)^p=\sum_{n=0}^p\binom{p}{n}x^n\\
&=\sum_{n=0}^{p}\frac{p!}{(p-n)!n!}x^n\tag{2}
\end{align*}
Comparison of (1) and (2) shows that (2) is already the Taylor expansion of $(1+x)^p$ around $x=0$ with coefficients
  \begin{align*}
\frac{f^{(n)}(0)}{n!}=\begin{cases}
\binom{p}{n}&0\leq n\leq p\\
0&n>p
\end{cases}
\end{align*}
  Since $(1+x)^p$ is a polynomial of degree $p$ it converges for each $x\in\mathbb{R}$, so $R=\infty$.

Hint: The more general framework of binomial series expansion and especially the regions of convergence might be interesting.

Find the coefficient of Taylor series


Accessibility NVDA Screen reader issue - Switching between anchor tag reading both the label

Question: Accessibility NVDA Screen reader issue - Switching between anchor tag reading both the label

             Knowledge

             Knowledge

             Support

            Support

Toggle button Image
I have to use NVDA for accessibility screen reader. When I toggle between the anchor tag, it reads both label as "Knoweledge support". Lets' say Knowledge is active and I am switching to Support or the reverse way. It should only read one. Normally when I am pressing tab or shift+tab, it is reading as expected.

I tried with different screen reader - chrome extension.
Tried by adding TabIndex
Tried using aria-labelledBy....etc
Comment: Do I understand correctly that your script is actually removing these anchor elements from the DOM? If so, that's pretty bad for accessibility. You must not remove an element that has focus, or you have to set the focus elsewhere before removing it. [Links are for navigation between pages](https://w3c.github.io/aria/#link), they should not toggle between states. You should use radio buttons for that.
Answer: There's an easier way of going about toggle switches. The author here has implemented several ways of doing so accessibly, which looks similar to your design. https://www.smashingmagazine.com/2017/09/building-inclusive-toggle-buttons/#auxiliary-labeling
Having some sort of aria-checked/pressed/selected state will help the screen reader identify the active state.
On another note, the aria-label should match the visible label (2.5.3: Label in Name). You can provide additional guidance with aria-labelledby.


enum class ambiguous overload for 'operator=='

Question: enum class A
  { W };
bool operator==( const A &a, const A &b )
  { return true; }

int main()
{
  ( A::W == A::W );
}

error: ambiguous overload for 'operator==' (operand types are 'A' and 'A')
note: candidate: operator==(A, A) built-in
note: candidate: bool operator==(const A&, const A&)
Comment: Your compiler is reporting the problem.   enum types implicitly have an `operator==()` that allows comparing two values of that type.   Your `operator==()` has a signature consistent with that but not quite the same, so the compiler sees two overloads versions of `operator==()` and has no reason to prefer one over the other.   Either remove your overload of `operator==()`, or changes its arguments to be passed by value (which will suppress the implicitly generated one).
Comment: It is perhaps worth noting that passing primitives by const reference is a pessimization.
Answer: You can fix your issue with
bool operator==(A, A) { return true; }

Demo


how to share the variable in chains of function calls python

Question: I have a fast API server in python. There are multiple layers for an API like one file call the function of other package and so on.
I generate request id for every request, at the top layer, now i want to share this id with evert chains of functions without passing it to the function.
In the NodeJs there is a library for the same, but how can i do the same in the python?
Comment: what do you do with request id in each function call? is it just used for logging purposes or as part of theinput ?
Comment: @ChrisDoyle for the time being logging purpose
Answer: This is a workaround which I used in a similar scenario.
Create a python file, say sess.py, in which you can have a variable request_id defined as below.
request_id=""

Now, you can import sess.py as below in any file in you application.
import sess
sess.request_id=1

And use this anywhere in your application.


Does the condition ${(n +1)^2} |x_n - x_{n+1}| \to 0$ imply that $\lim x_n$ exists?

Question: Does the following condition imply the convergence of the sequence ${(x_n)}$ ?
Given $ε > 0$ there exists an $n_0 \in \mathbf{N}$ such that $n > n_0$, ${(n +1)^2} |x_n - x_{n+1}| < \epsilon$.
If the question were as follows:
If for an arbitrary $ε > 0$, there exists an $n_0 \in $ N such that $n > n_0$.
$$\frac{1}{(n +1)^2}|x_n - x_{n+1}| < ε$$then taking $x_n = n$ suffices the assumption, and it is a non convergent sequence. So the answer would have been in a negation. But I could not find any way for the former case.
Comment: Take $x_n=n^2$. This provides a counter-example to your first statement.
Comment: @frog in fact his counterexample works for his first statement.
Comment: Sorry for the mistake. I have edited. @llham. Thanx
Comment: If you write the inequality as $$\lvert x_n - x_{n+1}\rvert < \frac{\varepsilon}{(n+1)^2},$$ does that give you an idea?
Comment: No @ Daniel. The main problem to me is that the terms in the modulus are consecutive.
Comment: It is enough to take $\epsilon=1$. From the convergence of $\sum \frac{1}{(n+1)^2}$, show that the sequence $(x_n)$ is  a **Cauchy sequence**.
Comment: @AndréNicolas You mean to say that the terms of the sequence can be taken as $x_n = \sum \frac{1}{(n+1)^2}$ without loss of generality???
Comment: No, I certainly do not!  More hint. Let $m, n$ be big, with $n\gt m$. Then by the triangle inequality $|x_n-x_m|\le  |x_{m+1}-x_m| +|x_{m+2}=x_{m+1}|+\cdots+|x_n-x_{n-1}|$.  Now use the condition $|x_{k+1}-x_k|$ small if $k$ is big.  Look at the hint of Daniel Fischer.
Comment: Got it @AndréNicolas Thanx...
Comment: You are welcome.  Note that for all $\epsilon$ there is an $n_0$ such that past it we have $|x_{n+1}-x_n|\lt \frac{\epsilon}{n+1}$ would not be good enough to prove convergence.
Answer: The series $\sum \frac{1}{(n+1)^2}$ is convergent. Let it converge to a number, say to $S$. Clearly $S > 0$.
Let $ε > 0$ be arbitrary. Then for $\frac{ε}{S}$, by our assumption, there exists an $n_0 \in $ N , such that
$|x_n - x_{n + 1}| < \frac{ε}{S}.\frac{1}{(n + 1)^2}$ for all $n > n_0$.
Now by triangle inequality, for $n > n_0$, we have $|x_n - x_{n_0}| \leq |x_n - x_{n - 1}| + |x_{n - 1} - x_{n - 2}| + . . . + |x_{n_0 + 1} - x_{n_0}|$
$$\lt \frac{ε/S}{(n)^2} + \frac{ε/S}{(n - 1)^2} + \frac{ε/S}{(n - 2)^2} + . . . + \frac{ε/S}{(n_0 + 1)^2}
 \leq \frac{ε}{S} \sum \frac{1}{(n)^2} = ε.$$
Thus for an arbitrary $ε > 0$, there exists an $n_0 \in$ N, such that
$|x_n - x_{n_0}| \lt ε$ for each $n > n_0$


Wolfram: How to create a list of pie charts for the sequence of digits in 10, 20 , 30

Question:
I want to be able to create multiple piecharts in a list. Each pie
  chart is an representation of the sequence of each argument.

Example: arguments -> 10, 20
arguments gets compiled into a sequence of numbers:
10 -> {1,2,3,4,5,6,7,8,9,10} and 20 -> {1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20}
Now i need to create a list of piecharts that was formulated by those sequences.
i tried something and it worked but what if there were to be more arguments. How long would my solving code have to be to solve it:
List[PieChart[Range[10]], PieChart[Range[20]]]

Please help me or give me references on how to do this in a smarted way preparing for more arguments.
Comment: If you study *An Elementary Introduction to the Wolfram Language* up to part 4 you will learn all you need to answer this questions for yourself.  SO generally expects people to have made a serious attempt at answering their own questions, asking a question here should be your last resort.  In the absence of any code you wrote this looks as if you expect (or just wish) someone to write code for you.  That's not how this site works.
Comment: @Phillip Jacobs ... Please help
Comment: @DavidBullock  ... Please help
Comment: @HighPerformanceMark, Thanks for your comment. I did in fact try out the question and passed but passing is not all i want to do. I want to make sure that i do stuff in the best possible way. But i updated my question so you can see what i've tried.

If you have a better way, please let me know
Comment: I'll try and keep you posted. Thank you @HighPerformanceMark
Comment: @HighPerformanceMark , I didn't fin help looking at Table but thanks anyway.
Answer: You should take a look at Map - Wolfram
So lets imagine you have more arguments: {10,20,48,4.2}
What you want to do is Map each function you want to use, on each one of them.
So the functions you used was List, PieChart & Range

soooo....
Map Range to each argument to turn each of them into a sequence of 1 to 'argument' :
Map[Range, {10,20,48,4.2}]

Then map all those lists created by 'Range' to the function PieChart
Map[PieChart, Map[Range, {10,20,48,4.2}]]

Comment: This works, but `Table[PieChart[Range[n]], {n, 10, 30, 10}]` would be simpler.
Comment: @HighPerformanceMark That's a nice answer. Why don't you answer or edit my answer ?
Comment: @HighPerformanceMark, Just had some nesting `{}` error on your last argument but i just tried it out and i love it. Tx bro bro !
`Table[PieChart[Range[n]], {n, {10, 20, 48, 4.2}}]`
Comment: The expression I posted works for me (MMA 11.something on MacOS).
Comment: Oh that's strange. Interesting though. I using MacOS as weel but I'm running 12.0 Through Parallels Desktop for Mac Business Edition
14.1.3 (45485)
Comment: @HighPerformanceMark i'm also busy with the  *Elementary Introduction to the Wolfram Language* ... Do you know of any course i can take after that ?


Creating density plots from two different data-frames using ggplot2

Question: My goal is to compare the distribution of various socioeconomic factor such as income over multiple years to see how the population has evolved in particular region in say, over 5 years. The primary data for this comes from the Public Use Microdata Sample. I am using R + ggplot2 as my preferred tool.
When comparing two years worth of data (2005 and 2010) I have two data frames hh2005 and hh2010 with the household data for the two years. The income data for the two years are stored in the variable hincp in both data frames. Using ggplot2 I am going about creating the density plot for individual years as follows (example for 2010):
    p1 <- ggplot(data = hh2010, aes(x=hincp))+
      geom_density()+
      labs(title = "Distribution of income for 2010")+
      labs(y="Density")+
      labs(x="Household Income")
    p1

How do I overlay the 2005 density over this plot? I am unable to figure it out as having read data in as hh2010 I am not sure how to proceed. Should I be processing the data in a fundamentally different way from the very beginning?
Answer: You can pass data arguments to individual geoms, so you should be able to add the second density as a new geom like this:
p1 <- ggplot(data = hh2010, aes(x=hincp))+
  geom_density() +
  # Change the fill colour to differentiate it
  geom_density(data=hh2005, fill="purple") +
  labs(title = "Distribution of income for 2010")+
  labs(y="Density")+
  labs(x="Household Income")

Answer: This is how I would approach the problem:

Tag each data frame with the variable of interest (in this case, the year)
Merge the two data sets
Update the 'fill' aesthetic in the ggplot function

For example:
# tag each data frame with the year^
hh2005$year <- as.factor(2005)
hh2010$year <- as.factor(2010)

# merge the two data sets
d <- rbind(hh2005, hh2010)
d$year <- as.factor(d$year)

# update the aesthetic
p1 <- ggplot(data = d, aes(x=hincp, fill=year)) +
  geom_density(alpha=.5) +
  labs(title = "Distribution of income for 2005 and 2010") +
  labs(y="Density") +
  labs(x="Household Income")
p1

^ Note, the 'fill' parameter seems to work best when you use a factor, thus I defined the years as such.  I also set the transparency of the overlapping density plots with the 'alpha' parameter.


GoogleAdView - can't install in Eclipse

Question: I'm confused with advertisements in android application. There is Adsense, AdMob, AdWhirl... Which should I use to show ads in my android application? Somwhere I read that Adsense is in beta, somewhere that Admob is deprecated and should use Adsense, and somewhere that I should use Admob because it is rewritten and is using Adsense background now.
So I finally use this solution:
https://developers.google.com/adsense-for-mobile-apps/docs/android/?hl=pl
But can't find link to GoogleAdView.jar (I have sdk android-sdk_r18-linux). So I downloaded from: http://www.java2s.com/Code/Jar/g/DownloadGoogleAdViewjar.htm . I created folder "libs" in my project, and added it in project properties -> java build path -> libraries -> Add external jar. I clean up project. Java code is compiling but layout preview can't load this control, I get error "The following classes could not be instantiated: com.google.ads.GoogleAdView". But when I run my application on emulator, I see ad and when I send my app to friend, he see it on his smartphone too.
So my questions are:
1. Is this tutorial current?
2. Why eclipse doesn't load GoogleAdView in layout preview?
Regards
Answer:
No the current way to do it is to use the AdMob SDK https://developers.google.com/mobile-ads-sdk/
Here is the answer from google product forums for the xml view part http://productforums.google.com/forum/#!category-topic/adsense/i-have-an-active-account-working-with-adsense/295ohH_m8jc

GoogleAdView - can't install in Eclipse


Is it possible to determine the major/minor key of a song by just looking at the chords?

Question: I play the piano and I'm new to musical theory but I have a basic understanding of chords and keys. At the moment I'm looking at pop songs and trying to analyse the chords of the songs, determine the key for a song, and then try to determine the chord progression.
So for example I've got these songs
1) Rihanna - Stay,         chords in the chorus:  C  Dm Am F
2) ATC - Around The World, chords in the chorus:  Am Em F  G

From listening and looking at the chords, I "know" (guessing really) that the first song is in C Major and the second is in A Minor, so then in Roman numerals you can write it like this (correct me if I'm wrong):
Rihanna - Stay         -> chord progression I - ii – vi - IV
ATC - Around The World -> chord progression i -  v - VI - VII

I've collected a list of pop songs in a file and I'm working on a Python script to analyse the songs. So far the script combines all the notes from the chords, and uses that to determine the key. Also see illustration below:

However, for these two songs in both cases it can be either C Major or A Minor because they use the same notes. So how can I determine which key it really is? How can you say if a song is in a major or a minor key? From this example it looks like you can examine the very first chord used, but is that a good way?
Comment: A lot of songs in A minor will use G sharp and sometimes F sharp instead of or in addition to F natural.  But then again, some songs in C major will do that too (especially F sharp).
Comment: My previous comment should have said "...instead of or in addition to G natural and F natural."
Answer: I'd actually still maintain that yes, it is possible to determine whether a piece is in a major or minor key - or no key at all - just by looking at the chords, but with the major caveat that the order and proportions of the chords can determine whether the piece is in a major key or its relative minor.
The I-V-vi-IV chord progression, depending on which of its chords plays first, lends itself particularly well to being interpreted as being in a major key or a minor key. This is because vi-IV-I-V can and will often be reinterpreted as i-VI-III-VII in the key of vi - the relative minor. In https://en.wikipedia.org/wiki/I%E2%80%93V%E2%80%93vi%E2%80%93IV_progression, note how consistently pieces with the vi-IV-I-V chord progression have minor keys for their "Recorded Key" and pieces with the I-V-vi-IV chord progression have major keys for their "Recorded Key".
Yes, this means that there can be two pieces that use the exact same set of chords (e.g. Dm, B♭ F, and C) such that one of them is in a major key and the other is in a minor key, and the only thing making one of them in a major key and the other in a minor key is the order of those chords or how often each chord is used.
Sadly, it turns out that as long as you do not know how long each chord goes for at all, you cannot unambiguously determine whether a piece is in a major or minor key. Take pieces consisting of only the chord progressions C-Dm-Am-F (all for one measure each) vs. C-Dm-Am-Am-Am-F (all for one measure each), for example. Due to how much the Am chord is stressed in the second piece, it's fairly easy to say that piece is in a minor key (A minor, in this case). However, with the first piece having all 4 of its chords in equal proportions and starting and ending with major chords (with a rough IV-I cadence to boot), the first piece is probably in a major key instead (I'd say C major). Chord progressions often repeat chords if they go on for multiple measures (a typical notation of the 12-bar blues is "I-I-I-I-IV-IV-I-I-V-IV-I-I", for example), thus often rendering concerns about the proportions of each chord moot.
The above applies more to pop music; determining the keys of classical music from their chord progressions alone actually often gives you the luxury of ignoring the end of the piece. Examples of classical music that begin in a minor key and end in their tonic major, yet are still labelled as being in that minor key, are plentiful. (One such example is Ludwig van Beethoven's Egmont Overture, which is in F minor but ends in F major. Note that IMSLP labels it as being in F minor in https://imslp.org/wiki/Egmont,Op.84(Beethoven,_Ludwig_van).) In fact, when determining the keys of classical music - or, rather, confirming the key labels of classical music - whole sections must often be ignored, such as the trios/middle sections of pieces in minuet and trio or scherzo and trio form and most of sonata-allegros (specifically, the second theme groups of the exposition and recapitulation sections along with the entire development section).
19th-20th-century marches are even worse in that regard. You often have to ignore the entire second half of the march, which possibly takes up more than 50% of the chord progression, when determining the march's key. For example, IMSLP labels John Philip Sousa's "The Stars and Stripes Forever" as being in E flat major in https://imslp.org/wiki/The_Stars_and_Stripes_Forever_(Sousa%2C_John_Philip) despite it ending in A flat major. Pieces ending in their subdominant keys is, in fact, a common feature of 19th-20th-century American marches...and 19th-20th century American ragtime. (See Scott Joplin's "Elite Syncopations" for such a ragtime example.)
Determining cadences and musical points of rest, along with which chords should end them, is a good idea, with the major caveat that you should not always rely on this.
Comment: This answer seems to imply that as long as C - Dm - Am - F is a correct transcription of a song's backing chords and it starts with C, then it will be impossible to make the song be perceived in any other key than C major, regardless of melody, rhythm, performance, or any other aspect. Or as an extension, as long as the backing chords and their order are known, there would only be one possible key for the song, and the key could even be unambiguously calculated without needing to know any other aspects of the song. And that just cannot be true.
Comment: @piiperiReinstateMonica - Just tried forcing the Am chord to take up 3 measures and the rest of the chords to take up 1 measure each - you're right, that made the piece shift to A minor. Guess I'll need to change my answer as a result.
Comment: Perception of music varies greatly between individuals. I added one more song at the end of my answer.
Comment: I still find this wrong. The order and duration of chord symbols on a backing chord chart cannot be the sole deciding factors in how a section of actual sound can affect a listener's perception of harmony. A backing chord chart is a grossly approximated abstract description of only a part of a musical performance. The OP can figure out a key from a full performance, but wants an algorithm that takes a chord chart and prints out an unambiguous key specification that is agreed on by the whole mankind for all possible songs having that chord chart.
Comment: @piiperiReinstateMonica - I'm still trying to think of a definitive counterexample where the melody pushes a chord progression I'd think of as being in one key (if played alone) into a different key, preferably major instead of minor or vice versa, but the closest I'm getting is that the melody consistently "plays outside" throughout and therefore both implies a different chord progression being played on top and **shades doubt that the notated chord progression is correct in the first place**. Think figuring that the correct chord progression is made of polychords instead.
Answer: Let's see what the music21 Python library thinks about the example chord progressions.
from music21 import stream, harmony

def guess_key(chords_string):
  s = stream.Stream()
  for d in chords_string.replace('b', '-').strip().split():
      s.append(harmony.ChordSymbol(d, quarterLength=4))
  return s.analyze('key')

print(guess_key('C Dm Am F'))
print(guess_key('Am Em F G'))

The output of our program:

F major
a minor

For the A minor song, music21 agreed with you, but what's with the other one? Did the computer make a mistake, is F major wrong? Are you wrong and is Rihanna wrong? No, nobody is wrong. F major is one possible guess out of many, based on too little information.
Using different rhythmic emphasis, and the melody and depending on the listener, and even the mixing of the song, it is possible to use that exact chord sequence in a song that gets perceived by someone as being in C major or F major, and their relative minor keys Am and Dm as well.
Counter-examples that show it is not possible to determine a key from chord and pitch lists
Here is an example song with C - Dm - Am - F in F or Dm.

And here's another song with C - Dm - Am - F, but this time in C.

I deliberately avoided using the giveaway notes B and Bb anywhere in the melodies. And it's still a subjective issue. Maybe you hear those in a different key than I did. At least Dekkadeci felt the key was still C even with this melody. I certainly didn't. But from what I can see, with this counter-example, I demonstrated that in the general case, it is not possible to "correctly" determine a key from a chord sequence. And it doesn't help even if you're given the sets of all pitches in the songs. The pitch sets are the same in both songs: C, D, E, F, G, A.
But how then do you know what key you should say the song is in?
Just like you already did - it is what it feels like to you. Saying that a song is in a key is a subjective statement. If you say "this is in A minor", it means that you personally and subjectively feel that A minor is the most prominent center-of-balance of that song's harmony, and it's the least misleading thing to say. For a lot of songs it's a compromise anyway, and in a lot of Western pop music the center of balance is not very strongly on either the major key or its relative minor key.
Personally, for most intents and purposes, I consider A minor and C major to be the same key. A person standing on two feet, sometimes their weight is slightly more on the left foot, sometimes on the right. But our language for talking about music has evolved in old times where people could only afford to wear a shoe in one foot at a time, so when we say that a person is standing, it is not possible to say that without specifying either the left or the right foot as the one that the person is standing on.
You have this question because of limitations of our language conventions. If there was an established and known way for saying "the key with C and Am being the joint center of balance without either being significantly more dominant", you would use that idiom. But there isn't, so you don't, and you have this problem.
To develop a sensitivity to this major-or-minor aspect, play existing songs and see how they have been categorized to either major or minor by more experienced people. You can only learn this by doing. It is about skill and experience, not knowledge and logic that you could calculate.
To address the literal question in the title: Is it possible to determine the major/minor key of a song by just looking at the chords?
Sometimes yes, sometimes no. If you see things like Am - Dm - B7 - E7 - Am, you can be pretty sure that it's in A minor. But even the existence of E7 - Am somewhere doesn't mean it's in A minor. Sometimes it is completely ambiguous. Sometimes the tonic chord is not even included in the song at all, the harmony goes around it without ever going "home". You have to listen to it. Here's a song that's clearly in A minor, but there is no Am chord in the whole song, not even once.

(Some theory purist / language correctness police might insist that it must be not said to be in a minor key because there's no leading tone. I say that languages evolve, and the modern de-facto meaning of "key" doesn't require a leading tone.)
Algorithms can do more, if they have more information
All that said, it is possible to get better guesses with algorithms, but you'll have to give them more than just a list of chords and a set of pitches. I took my example songs above and exported them from Sibelius a MIDI files, in different key signatures to demonstrate that Music21 is not just looking at the given key signature (in the MIDI metadata event).
The new program
from music21 import midi

def guess_midi_file_key(midi_file_name):
  mf = midi.MidiFile()
  mf.open(midi_file_name)
  mf.read()
  mf.close()
  return midi.translate.midiFileToStream(mf).analyze('key')

print(guess_midi_file_key('example_song_1.mid'))
print(guess_midi_file_key('example_song_1_key_signature_D#_minor.mid'))
print(guess_midi_file_key('example_song_2.mid'))
print(guess_midi_file_key('example_song_2_key_signature_G_minor.mid'))

And the output of the program is:

F major
F major
C major
C major

Here's one of the songs imported to GuitarPro:

So, Music21 is able to figure out that the song is in F, despite the deceptive key signature meta data. But only if it has the melody as well as the chords. I don't know what the key-guessing is based in, maybe some statistical calculation, i.e. how many times each pitch is used. I haven't tried, but I'm pretty sure it wouldn't place the Santrofi song in A minor.
By popular request, here's one more song that starts with a C chord, does not use a Bb note anywhere, and is solidly in F or Dm.
Comment: I'd argue that song's in C rather than Am, but maybe more accurately, in E Phrygian, but that's just me! The pedant rises again..!
Comment: Maybe that Em could sound like Cmaj7. There is a B played by tpt, as the last note. But, as you say, and I quite agree, deciding on a key - especially by listening, is a subjective thing, and ambiguous, and maybe many more adjectives too. I guess even composers sometimes had a hard time with it. Except maybe Bartok... But OP wants to determine merely from the notes involved, a non-starter, I reckon.
Comment: @Tim It's not in E Phrygian, the Em chord does not sound like a resting place at all, it sounds like being away from home, it's longing to go home to mama A minor. Adding an Am at the end of the song resolves that longing, but playing a C major is a sarcastic ending which ridicules the whole story that was told before. But then again, specifying a key is a subjective statement, which is what I tried to say.
Comment: Regarding the latest/current version of your answer, doesn't the chord progression of a full song already contain the order of the chords and, therefore, enough information to determine its key? Again, I mention in my answer that https://en.wikipedia.org/wiki/I%E2%80%93V%E2%80%93vi%E2%80%93IV_progression has some stunning consistencies between what order the same 4 chords are in (I, V, vi, IV) and whether the piece is in a major or minor key.
Comment: @Dekkadeci It's not about the order as such - I gave two example songs in different keys, but both songs having the exact same chords in the exact same order. It's about what notes get what kind of rhythmic importance, in the whole of the song. In my examples the rhythmic importance is set by the melody, and the melody also slightly modifies the relative weights of chord tones and adds extra notes to the total chords. For example adding D and E to an F major. But the OP's question starts from a written backing chord progression as the only source of information.
Comment: @piiperiReinstateMonica - I tried both of your example songs, where you claimed that the first is in F major or D minor and the second is in C major, and **they actually both sounded like they were in C major** to me. I think this is because neither of them have any V-I mini-chord progressions in them, so the strongest remaining mini-chord progression left is the IV-I one, and that's F-C for both.
Comment: @Dekkadeci I and the Music21 library disagree with you. ;) How about if you change the last melody note from A to F, does it change it for you? I don't know how you played it, but when I play that on the guitar and sing it, it's in F, clear as daylight. I am my own ultimate authority about my feelings and key is a feeling. Like I said, making a claim about key is a subjective statement.
Comment: @piiperiReinstateMonica - Tried changing that last melody note to F. Same result - **the melody and backing chords combined still sound like they are in C major**.
Comment: No problem, you have just demonstrated and confirmed what I'm saying - that key is a subjective feeling. When a C chord comes in the first example song, it is not a home chord for me, not at all. It ends on F, maybe it could end on a Dm if added after the final F.
Comment: Tried your Song 3 just now. Half the time, it sounds like it's in F major, and half the time, the Am-F chord progression sounds *really* unconvincing and makes me think the song is in C major instead.
Comment: @Dekkadeci yes, the last F chord is surprising, to say the least. But to me the Am-F transition feels like it's in D minor, but instead of giving the Dm it's doing a final ending repeat of the last 4 bars. The F moves it abruptly to F instead of Dm in a jump-start smash-in-the-head way. But my point was just to construct different melodies to show how they change the perception of the backing chords. The C chord in the beginning is only playing an assisting role IMO.
Comment: @piiperiReinstateMonica - Honestly, my experience is that the melody actually contributes less to what key the piece/excerpt is in than the backing chord progression, to the point that you can re-harmonize the same melody into a different (but related) key. My favourite example of that has to be *Dance Dance Revolution: Mario Mix*'s "In the Whirlpool", which re-harmonizes a familiar D-major melody from Elgar's *Pomp and Circumstance March No. 1 in D Major* into B minor instead.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/137718/discussion-between-piiperi-reinstate-monica-and-dekkadeci).
Answer: The very first chord (not any anacrucis) may give the key, and often does. The very last chord usually does. (Not a lot of help for songs which fade...). But listening for cadences helps. Just examining the notes often does for major, and for minor, which generally doesn't use quite the same set as its relative counterpart. As in C major, CDEFGAB, whereas A  minor ABCDEFG♯. So it's not that cut and dried.
There's the most used criterion of where does it feel 'at rest' - as if the song could finish at that point, and not give the feeling that it's just a temporary rest. But you're not going to get that neccessarily from examining notes involved. The raised leading note in a minor key is a really good clue (see G♯ in key Am). But a lot of songs may well modulate for a little while into the relative (or parallel), which throws us off the scent.
So, ears work best (as usual), except that's not what you want to use for your analysis. Thus there's often going to be that 50:50, which isn't a lot of help with the diagnosis! And that's before 'stray' notes creep in due to momentary modulation, which happens in so many songs. By the time you've tried to analyse a few hundred songs - and got 80% correct - you'll appreciate there's no particular scientific way to determine. Sorry!
One that always gets me is Fly Me To the Moon: starts off with Am, but ends on C major - so is it in A minor or C major? And I guess it's purely academic, as the same key signature is used for both. The jury's still out...
Answer: "Is it possible to determine the major/minor key of a song by just looking at the chords?"
Sometimes 'what scale includes the notes of all the chords, is the first/last chord major or minor' will give a useful answer.
But I'm afraid that a WHOLE LOT of times it won't.   And if I tried to list all the ways a piece of music might not derive all its chords from just one scale, or might not even be firmly in any particular major or minor key at alland , we'd be here for the rest of our lives!
Sorry.