问:
we did not send a packet, disable method
I have tried to setup public key connection between AIX to AIX and that's working and I am facing problem while I setup same public key connection between AIX and DataPower appliance.

I could see in logs that's connection established but while using public I am not able to login and everytime expecting to enter password manually.

Can someone please help on this?

```<code>debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: ./***_rsa.pub
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,password
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
</code>```

答:
Check the ssh configuration on remote server to find if remote system is accepting type of key being passed.

Check the file /etc/ssh/sshd_config and look for property PubkeyAcceptedKeyTypes to confirm that it accepts key type being passed. For instance, here the key type seems to be ssh-rsa, so that should be added to the list of PubkeyAcceptedKeyTypes

(or for maximium compatibility PubkeyAcceptedKeyTypes *)

Once added, restart sshd daemon

EX:

```<code>sudo sed -i "/.*PubkeyAcceptedKeyTypes.*/d"     /etc/ssh/sshd_config
sudo sed -i "/.*RSAAuthentication.*/d"          /etc/ssh/sshd_config
sudo sed -i "/.*PubkeyAuthentication.*/d"       /etc/ssh/sshd_config
sudo sed -i "/.*PasswordAuthentication.*/d"     /etc/ssh/sshd_config
sudo sed -i "/.*PermitRootLogin.*/d"            /etc/ssh/sshd_config
echo "PubkeyAcceptedKeyTypes *"   | sudo tee -a /etc/ssh/sshd_config
echo "RSAAuthentication yes"      | sudo tee -a /etc/ssh/sshd_config
echo "PubkeyAuthentication yes"   | sudo tee -a /etc/ssh/sshd_config
echo "PasswordAuthentication no"  | sudo tee -a /etc/ssh/sshd_config
echo "PermitRootLogin no"         | sudo tee -a /etc/ssh/sshd_config
sudo systemctl restart sshd.service
sudo systemctl status  sshd.service | grep -i success
</code>```

Body:
I have tried to setup public key connection between AIX to AIX and that's working and I am facing problem while I setup same public key connection between AIX and DataPower appliance.

I could see in logs that's connection established but while using public I am not able to login and everytime expecting to enter password manually.

Can someone please help on this?

debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: ./***_rsa.pub
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,password
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password

Body:
Check the ssh configuration on remote server to find if remote system is accepting type of key being passed.

Check the file /etc/ssh/sshd_config and look for property PubkeyAcceptedKeyTypes to confirm that it accepts key type being passed. For instance, here the key type seems to be ssh-rsa, so that should be added to the list of PubkeyAcceptedKeyTypes

(or for maximium compatibility PubkeyAcceptedKeyTypes *)

Once added, restart sshd daemon

EX:

sudo sed -i "/.*PubkeyAcceptedKeyTypes.*/d"     /etc/ssh/sshd_config
sudo sed -i "/.*RSAAuthentication.*/d"          /etc/ssh/sshd_config
sudo sed -i "/.*PubkeyAuthentication.*/d"       /etc/ssh/sshd_config
sudo sed -i "/.*PasswordAuthentication.*/d"     /etc/ssh/sshd_config
sudo sed -i "/.*PermitRootLogin.*/d"            /etc/ssh/sshd_config
echo "PubkeyAcceptedKeyTypes *"   | sudo tee -a /etc/ssh/sshd_config
echo "RSAAuthentication yes"      | sudo tee -a /etc/ssh/sshd_config
echo "PubkeyAuthentication yes"   | sudo tee -a /etc/ssh/sshd_config
echo "PasswordAuthentication no"  | sudo tee -a /etc/ssh/sshd_config
echo "PermitRootLogin no"         | sudo tee -a /etc/ssh/sshd_config
sudo systemctl restart sshd.service
sudo systemctl status  sshd.service | grep -i success


来源: stackexchange

问:
multiple IF else conditions issue
I have an issue where I want to segregate / split file based on search item into multiple files.

if I see add I want to put that line to addfile.
similar to changeprop, insert and if I cannot find any match then to otherfile.   I'm unable to process the if else conditions.

```<code>FOR /F "tokens=* delims=" %%a in ('TYPE "%File%"') DO (
    SET "eachline=%%a"
    IF /i "!eachline:~0,3!" == "ADD " (ECHO !eachline!>>"%ADDActionScriptsMergedFile%")
    ELSE ( IF /i "!eachline:~0,9!" == "ADDINSERT" (ECHO !eachline!>>"%ADDINSERTActionScriptsMergedFile%")
        ELSE ( IF /i "!eachline:~0,3!" == "MOV" (ECHO !eachline!>>"%MOVEActionScriptsMergedFile%")
            ELSE ( IF /i "!eachline:~0,6!" == "INSERT" (ECHO !eachline!>>"%INSERTPROPActionScriptsMergedFile%")
                ELSE ( IF /i "!eachline:~0,10!" == "CHANGEPROP" (ECHO !eachline!>>"%CHANGEPROPActionScriptsMergedFile%")
                    ELSE (ECHO !eachline!>>"%OTHERPROPActionScriptsMergedFile%")
                )
            )
        )
    )
)
</code>```

答:
Give this a try. It is based on my previous answer, but changed a bit to avoid writing the same code several times (two times was ok, but now, that it's 5 (or maybe even more), it makes sense to use a for loop):

```<code>@echo off
setlocal
set "File=.\WorkFlow_Action_Script_Merged_Folder\All_WorkFlows_Merged_File.txt"
set "Dest=.\WorkFlow_Action_Script_Merged_Folder\@_WorkFlows_Merged_File.txt"
for %%a in ("Add " Addinsert Mov Insert Changeprop) do (
  type "%File%" | findstr /bic:"%%~a" > "%Dest:@=%%~a%"
)
type "%File%" |findstr /bivc:"Addinsert" /bivc:"Mov" /bivc:"Insert" /bivc:"Changeprop" /bivc:"Add " > "%Dest:@=OTHERPROP%"
</code>```

(untested, as I don't have your files or folderstructure)

ContentLicense: CC BY-SA 4.0

Title: multiple IF else conditions issue

Body:
I have an issue where I want to segregate / split file based on search item into multiple files.

if I see add I want to put that line to addfile.
similar to changeprop, insert and if I cannot find any match then to otherfile.   I'm unable to process the if else conditions.

FOR /F "tokens=* delims=" %%a in ('TYPE "%File%"') DO (
    SET "eachline=%%a"
    IF /i "!eachline:~0,3!" == "ADD " (ECHO !eachline!>>"%ADDActionScriptsMergedFile%")
    ELSE ( IF /i "!eachline:~0,9!" == "ADDINSERT" (ECHO !eachline!>>"%ADDINSERTActionScriptsMergedFile%")
        ELSE ( IF /i "!eachline:~0,3!" == "MOV" (ECHO !eachline!>>"%MOVEActionScriptsMergedFile%")
            ELSE ( IF /i "!eachline:~0,6!" == "INSERT" (ECHO !eachline!>>"%INSERTPROPActionScriptsMergedFile%")
                ELSE ( IF /i "!eachline:~0,10!" == "CHANGEPROP" (ECHO !eachline!>>"%CHANGEPROPActionScriptsMergedFile%")
                    ELSE (ECHO !eachline!>>"%OTHERPROPActionScriptsMergedFile%")
                )
            )
        )
    )
)

Body:
Give this a try. It is based on my previous answer, but changed a bit to avoid writing the same code several times (two times was ok, but now, that it's 5 (or maybe even more), it makes sense to use a for loop):

@echo off
setlocal
set "File=.\WorkFlow_Action_Script_Merged_Folder\All_WorkFlows_Merged_File.txt"
set "Dest=.\WorkFlow_Action_Script_Merged_Folder\@_WorkFlows_Merged_File.txt"
for %%a in ("Add " Addinsert Mov Insert Changeprop) do (
  type "%File%" | findstr /bic:"%%~a" > "%Dest:@=%%~a%"
)
type "%File%" |findstr /bivc:"Addinsert" /bivc:"Mov" /bivc:"Insert" /bivc:"Changeprop" /bivc:"Add " > "%Dest:@=OTHERPROP%"

(untested, as I don't have your files or folderstructure)


问:
Unity IAP | In App Purchase | Unknown Error
I want to implement IAP in my android game.

This is my code, it is from the official unity website:

```<code>using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.UI;

public class Purchaser : MonoBehaviour, IStoreListener {
private static IStoreController m_StoreController;          // The Unity Purchasing system.
private static IExtensionProvider m_StoreExtensionProvider; // The store-specific Purchasing subsystems.

public Text text;

public static string kProductIDConsumable = "pile_shadycoin";

void Start() {
    if (m_StoreController == null) {
        InitializePurchasing();
    }
}

public void InitializePurchasing() {
    if (IsInitialized()) {
        return;
    }

    var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());

    builder.AddProduct(kProductIDConsumable, ProductType.Consumable);

    UnityPurchasing.Initialize(this, builder);
}

private bool IsInitialized() {
    return m_StoreController != null && m_StoreExtensionProvider != null;
}

public void BuyConsumable() {
    BuyProductID(kProductIDConsumable);
}

void BuyProductID(string productId) {
    if (IsInitialized()) {
        Product product = m_StoreController.products.WithID(productId);

        if (product != null && product.availableToPurchase) {
            text.text = "Purchasing product asychronously: '{0}'";
            m_StoreController.InitiatePurchase(product);
        } else {
            text.text = "BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase";
        }
    } else {
        text.text = "BuyProductID FAIL. Not initialized.";
    }
}

public void OnInitialized(IStoreController controller, IExtensionProvider extensions) {
    text.text = "OnInitialized: PASS";

    m_StoreController = controller;

    m_StoreExtensionProvider = extensions;
}

public void OnInitializeFailed(InitializationFailureReason error) {
    text.text = "OnInitializeFailed InitializationFailureReason:" + error;
}

public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) {
    if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal)) {
        text.text = "ProcessPurchase: PASS. Product: '{0}'";

    } else {
        text.text = "ProcessPurchase: FAIL. Unrecognized product: '{0}'";
    }
    return PurchaseProcessingResult.Complete;
}

public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason) {
    text.text = failureReason + "";
}
}
</code>```

I am using the consumable item pile_shadycoin.
In the picture you can see the id and that it's active (it's german)

Picture of Google Play

If I build my project and put it on my smartphone and press the button, which is linked to BuyConsumable() it opens the menu and says:

Fehler Der angeforderte Artikel kann nicht gekauft werden

In English:

Error The requested item cannot be purchased

答:
I found my error. I didn't released the build on alpha or beta.

I pulled the APK directly to my phone.

Body:
I want to implement IAP in my android game.

This is my code, it is from the official unity website:

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.UI;

public class Purchaser : MonoBehaviour, IStoreListener {
private static IStoreController m_StoreController;          // The Unity Purchasing system.
private static IExtensionProvider m_StoreExtensionProvider; // The store-specific Purchasing subsystems.

public Text text;

public static string kProductIDConsumable = "pile_shadycoin";

void Start() {
    if (m_StoreController == null) {
        InitializePurchasing();
    }
}

public void InitializePurchasing() {
    if (IsInitialized()) {
        return;
    }

    var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());

    builder.AddProduct(kProductIDConsumable, ProductType.Consumable);

    UnityPurchasing.Initialize(this, builder);
}

private bool IsInitialized() {
    return m_StoreController != null && m_StoreExtensionProvider != null;
}

public void BuyConsumable() {
    BuyProductID(kProductIDConsumable);
}

void BuyProductID(string productId) {
    if (IsInitialized()) {
        Product product = m_StoreController.products.WithID(productId);

        if (product != null && product.availableToPurchase) {
            text.text = "Purchasing product asychronously: '{0}'";
            m_StoreController.InitiatePurchase(product);
        } else {
            text.text = "BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase";
        }
    } else {
        text.text = "BuyProductID FAIL. Not initialized.";
    }
}

public void OnInitialized(IStoreController controller, IExtensionProvider extensions) {
    text.text = "OnInitialized: PASS";

    m_StoreController = controller;

    m_StoreExtensionProvider = extensions;
}

public void OnInitializeFailed(InitializationFailureReason error) {
    text.text = "OnInitializeFailed InitializationFailureReason:" + error;
}

public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) {
    if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal)) {
        text.text = "ProcessPurchase: PASS. Product: '{0}'";

    } else {
        text.text = "ProcessPurchase: FAIL. Unrecognized product: '{0}'";
    }
    return PurchaseProcessingResult.Complete;
}

public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason) {
    text.text = failureReason + "";
}
}

I am using the consumable item pile_shadycoin.
In the picture you can see the id and that it's active (it's german)

Picture of Google Play

If I build my project and put it on my smartphone and press the button, which is linked to BuyConsumable() it opens the menu and says:

Fehler Der angeforderte Artikel kann nicht gekauft werden

In English:

Error The requested item cannot be purchased


问:
How to display an rhandsontable in Shiny that is dependent on selectInput choices
I have a select input box where the user can select from three choices. Having made the selection I want a table to appear whereby they can enter some additional values associated with those choices.

I then want to display a summary table which contains a summary of the values that have been entered.

When I run the code below I get the following error:

Error in .getReactiveEnvironment()$currentContext() :    Operation not
  allowed without an active reactive context. (You tried to do something
  that can only be done from inside a reactive expression or observer.)

```<code>library(shiny)
library(rhandsontable)
library(dplyr)

ui <- fluidPage(
  mainPanel(
    selectInput("section", "Section", choices = c("A","B","C"), multiple = TRUE),
    rHandsontableOutput('table')
  )
)

server = function(input, output, session) {

  SectionList <- input$section

  Section <- eventReactive(input$section, {
    section_table <- data.frame(Section = SectionList, input1 = 0, input2 = 0)
    return(section_table)
  })

  output$table <- renderRHandsontable({
    if(!is.null(input$table)){
      DF = hot_to_r(input$table)
    } else {
      DF = data.frame(Section = "A", input1 = 0, input2 = 0)
    }
    rhandsontable(DF) %>%
      hot_col(col = "input1") %>%
      hot_col(col = "input2")
  })

  results_summary <- eventReactive(input$table, {
    DF = output$table
    summary <- DF %>% group_by(Section) %>%
      summarise(input1 = mean(input1),
                input2 = mean(input2))
  })

  output$results <- renderTable({
    results_summary()
  })

}
shinyApp(ui, server)
</code>```

答:
I haven't fully understood what you are aiming to do, but the error is produced because of the line:

SectionList <- input$section

this line has to go to a reactive environment. If you change this to, e.g.

Section <- eventReactive(input$section, {
    SectionList <- input$section
    section_table <- data.frame(Section = SectionList, input1 = 0, input2 = 0)
    return(section_table)
  })

the error disappears. Hope this helps!

Body:
I have a select input box where the user can select from three choices. Having made the selection I want a table to appear whereby they can enter some additional values associated with those choices.

I then want to display a summary table which contains a summary of the values that have been entered.

When I run the code below I get the following error:

Error in .getReactiveEnvironment()$currentContext() :    Operation not
  allowed without an active reactive context. (You tried to do something
  that can only be done from inside a reactive expression or observer.)

library(shiny)
library(rhandsontable)
library(dplyr)

ui <- fluidPage(
  mainPanel(
    selectInput("section", "Section", choices = c("A","B","C"), multiple = TRUE),
    rHandsontableOutput('table')
  )
)

server = function(input, output, session) {

  SectionList <- input$section

  Section <- eventReactive(input$section, {
    section_table <- data.frame(Section = SectionList, input1 = 0, input2 = 0)
    return(section_table)
  })

  output$table <- renderRHandsontable({
    if(!is.null(input$table)){
      DF = hot_to_r(input$table)
    } else {
      DF = data.frame(Section = "A", input1 = 0, input2 = 0)
    }
    rhandsontable(DF) %>%
      hot_col(col = "input1") %>%
      hot_col(col = "input2")
  })

  results_summary <- eventReactive(input$table, {
    DF = output$table
    summary <- DF %>% group_by(Section) %>%
      summarise(input1 = mean(input1),
                input2 = mean(input2))
  })

  output$results <- renderTable({
    results_summary()
  })

}
shinyApp(ui, server)


问:
Pervasive ODBC Client Interface
I have been working on small tool for inspecting customers from ODBC database. Tool seems to be working on my computer with drivers installed (Actian PSQL) but I just started to wonder is it possible to spread this tool to other users. However I have found out that you need Pervasive ODBC Client Interface Unicode driver for that. It looks like otherwise connection can't be established. </p>

<p>Do anyone have any idea how this can be done? Is it so that there should be some executable file with drivers inside of it or there is some other way to handle this issue? </p>

答: In order to connect to the Pervasive ODBC driver, it must be installed on the machine where the application is running.  If your target audience has a Pervasive database, they will have the Pervasive ODBC driver.  In addition, the ODBC driver is just a small part of the Pervasive product.  For example, the ODBC driver can't open files directly.  The ODBC driver connects to the engine which opens the files.  You can't use the ODBC driver without an engine to open the files and you can't use the ODBC driver from an application without the driver. </p>

Title: Pervasive ODBC Client Interface

Body:
I have been working on small tool for inspecting customers from ODBC database. Tool seems to be working on my computer with drivers installed (Actian PSQL) but I just started to wonder is it possible to spread this tool to other users. However I have found out that you need Pervasive ODBC Client Interface Unicode driver for that. It looks like otherwise connection can't be established.

Do anyone have any idea how this can be done? Is it so that there should be some executable file with drivers inside of it or there is some other way to handle this issue?


问:
Difference between MirroredStrategy and CentralStorageStrategy
I read the documentation of both CentralStorageStrategy and MirroredStrategy, but can not understand the essence of difference between them.

In MirroredStrategy:

Each variable in the model is mirrored across all the replicas.

In CentralStorageStrategy:

Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs.

Source: https://www.tensorflow.org/guide/distributed_training

What does it mean in practice? What are use cases for the CentralStorageStrategy and how does the training work if variables are placed on the CPU in this strategy?

答:
Consider one particular variable (call it "my_var") in your usual, single-GPU, non-distributed use case (e.g. a weight matrix of a convolutional layer).

If you use 4 GPUs, MirroredStrategy will create 4 variables instead of "my_var" variable, one on each GPU. However each variable will have the same value, because they are always updated in the same way. So the variable updates happen in sync on all the GPUs.

In case of the CentralStorageStrategy, only one variable is created for "my_var", in the host (CPU) memory. The updates only happen in one place.

Which one is better probably depends on the computer's topology and how fast CPU-GPU communication is compared with GPU-GPU. If the GPUs can communicate fast with each other, MirroredStrategy may be more efficient. But I'd benchmark it to be sure.


问:
How can I create scrollable columns in Bootstrap?
I created a new template file template-home2.php in a Wordpress Theme.

In there I have a row with 3 columns, I would like to make each of these columns scrollable instead of the entire page. How can I achieve that?

I have a class scrollable that I apply to the outer section of the page to make it scrollable.

```<code><section class="<?php if( get_theme_mod( 'hide-player' ) == 0 ){ echo "w-f-md";} ?>" id="ajax-container">
    <section class="hbox stretch bg-black dker">
        <section>
            <section class="vbox">
                <section class="scrollable">
                    <div class="row">
                       <div class="col-md-5 no-padder no-gutter">
                           some data
                       </div>
                       <div class="col-md-4 no-padder no-gutter">
                           some data
                       </div>
                       <div class="col-md-3 no-padder no-gutter">
                           some data
                       </div>
                    </div>
                </section>
            </section>
        </section>
    </section>
</section>
</code>```

When I remove the class “scrollable” from the main section and include it in the column div, the column disappears and the other 2 columns overflow on the elements below.

This is the relevant CSS

```<code>.scrollable {
  overflow-x: hidden;
  overflow-y: auto;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow: visible;
  overflow-y: auto;
}
.slimScrollBar {
  border-radius: 5px;
  border: 2px solid transparent;
  border-radius: 10px;
  background-clip: padding-box !important;
}
</code>```

Thank you for your help.

UPDATED CODE

```<code>.homecol1, .homecol2, .homecol3 {
    position: absolute;
    overflow-y: scroll;
}

<section class="<?php if( get_theme_mod( 'hide-player' ) == 0 ){ echo "w-f-md";} ?>" id="ajax-container">
    <section class="hbox stretch bg-black dker">
        <section>
            <section class="vbox">
                <section class="scrollable">
                    <div class="row">
                       <div class="col-md-5 no-padder no-gutter homecol1">
                           some data
                       </div>
                       <div class="col-md-4 no-padder no-gutter homecol2">
                           some data
                       </div>
                       <div class="col-md-3 no-padder no-gutter homecol3">
                           some data
                       </div>
                    </div>
                </section>
            </section>
        </section>
    </section>
</section>
</code>```

答:
Following answer https://stackoverflow.com/a/53897001/11620296 shows solution with bootstrap 4 which works perfectly for me. It has updated demo https://www.codeply.com/go/ouc3hddx5i

Code:

html

Navbar

Sidebar

            Article list

Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
                raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation.
                Shabby chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.

Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb
                readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies,
                forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.

Article content

Footer

```

<p>css</p>

<pre class="lang-css prettyprint-override"><code>html,body {
    height: 100%;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created a new template file template-home2.php in a Wordpress Theme.

In there I have a row with 3 columns, I would like to make each of these columns scrollable instead of the entire page. How can I achieve that?

I have a class scrollable that I apply to the outer section of the page to make it scrollable.

<section class="<?php if( get_theme_mod( 'hide-player' ) == 0 ){ echo "w-f-md";} ?>" id="ajax-container">

                           some data

                           some data

                           some data

When I remove the class “scrollable” from the main section and include it in the column div, the column disappears and the other 2 columns overflow on the elements below.

This is the relevant CSS

.scrollable {
  overflow-x: hidden;
  overflow-y: auto;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow: visible;
  overflow-y: auto;
}
.slimScrollBar {
  border-radius: 5px;
  border: 2px solid transparent;
  border-radius: 10px;
  background-clip: padding-box !important;
}

Thank you for your help.

UPDATED CODE

.homecol1, .homecol2, .homecol3 {
    position: absolute;
    overflow-y: scroll;
}

<section class="<?php if( get_theme_mod( 'hide-player' ) == 0 ){ echo "w-f-md";} ?>" id="ajax-container">

                           some data

                           some data

                           some data

Body:
Following answer https://stackoverflow.com/a/53897001/11620296 shows solution with bootstrap 4 which works perfectly for me. It has updated demo https://www.codeply.com/go/ouc3hddx5i

Code:

html

<div class="container-fluid h-100 d-flex flex-column">
    <div class="row flex-shrink-0">
        <div class="col-12 border">Navbar </div>
    </div>
    <div class="row flex-fill" style="min-height:0">
        <div class="col-2 border mh-100" style="overflow-y: scroll;">Sidebar </div>
        <div class="col-4 border mh-100" style="overflow-y: scroll;">
            Article list
            <p>Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics,
                raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation.
                Shabby chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.</p>

            <p>Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb
                readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies,
                forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.</p>

        </div>
        <div class="col-6 border" style="overflow-y: scroll;">Article content </div>
    </div>
    <div class="row flex-shrink-0">
        <div class="col-12 border">Footer </div>
    </div>
</div>

css

html,body {
    height: 100%;
}


问:
How to combine css with selectors
I need to clean up my CSS file and remove some bloat.  I know it's possible to combine classes and ids by separating them with commas.  However, I'm not sure how to go about combining them when they have more complex selectors like the ones below.

Any help would be appreciated.  Thank you.

```<code>body #gform_wrapper_14 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_15 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_17 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
</code>```

or

```<code>@media only screen and (min-width: 641px) {
    body #gform_wrapper_14 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_15 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_17 {
      max-width: 80%;
      margin: 0 auto;
     }
    .hor-address {
        width:500px;
    }
}
</code>```

Clarification:  I have multiple #gform_wrapper_xx objects (generated by 3rd party Wordpress plugin) and but I don't want to change all of them.  I just want to change these 3.

答:
As simple has that:

body #gform_wrapper_14 .gform_footer input[type=submit],
body #gform_wrapper_15 .gform_footer input[type=submit],
body #gform_wrapper_17 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
```

<p>and that:</p>

<pre class="lang-css prettyprint-override"><code>@media only screen and (min-width: 641px) {
    body #gform_wrapper_14,
    body #gform_wrapper_15,
    body #gform_wrapper_17 {
      max-width: 80%;
      margin: 0 auto;
     }

    .hor-address {
        width:500px;
    }
}
</code>```

Title: How to combine css with selectors

Body:
I need to clean up my CSS file and remove some bloat.  I know it's possible to combine classes and ids by separating them with commas.  However, I'm not sure how to go about combining them when they have more complex selectors like the ones below.

Any help would be appreciated.  Thank you.

body #gform_wrapper_14 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_15 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_17 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}

or

@media only screen and (min-width: 641px) {
    body #gform_wrapper_14 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_15 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_17 {
      max-width: 80%;
      margin: 0 auto;
     }
    .hor-address {
        width:500px;
    }
}

Clarification:  I have multiple #gform_wrapper_xx objects (generated by 3rd party Wordpress plugin) and but I don't want to change all of them.  I just want to change these 3.

Body:
As simple has that:

body #gform_wrapper_14 .gform_footer input[type=submit],
body #gform_wrapper_15 .gform_footer input[type=submit],
body #gform_wrapper_17 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}

and that:

@media only screen and (min-width: 641px) {
    body #gform_wrapper_14,
    body #gform_wrapper_15,
    body #gform_wrapper_17 {
      max-width: 80%;
      margin: 0 auto;
     }

    .hor-address {
        width:500px;
    }
}


问:
Issues with template class conversion - unable to deduce function called
How do I make the following code work properly?

The non-template version compiles perfectly but the template version fails miserably. Why template version fails to figure out which function version to call and how to fix it? I thought about adding to template class AT operator that implicitly converts to BT but it doesn't work either.

```<code>class A {};

class B
{
    public:
    B(A){};
};

void func(B){};

template<typename T>
class AT {};

template<typename T>
class BT
{
    public:
    BT(AT<T>){};
};

template<typename T>
void funcT(BT<T>){};

int main()
{
    func(A{});
    funcT(AT<int>{}); // unable to deduce the funcT template argument
    funcT<int>(AT<int>{}); // compiles but I don't want to write that

    return 0;
}
</code>```

There are dumb fixes like writing function version that accepts AT<T> and casts it to BT<T>. But I don't want to write a bunch of functions when everything should work as is. I could understand it if it was an ambiguous call...

答:
The other answer explained what was going on, but there is a way around this

```<code>template<class T, template<class>class Temp, typename std::enable_if<std::is_convertible< Temp<T>, BT<T>>::value, bool>::type = true>
void funcT(Temp<T> t) {
    auto bt = static_cast<BT<T>>(t);
}
</code>```

This can be called by fooT(A<int>{}); as well as fooT(B<int>{}); having the same behavior.

Body:
How do I make the following code work properly?

The non-template version compiles perfectly but the template version fails miserably. Why template version fails to figure out which function version to call and how to fix it? I thought about adding to template class AT operator that implicitly converts to BT but it doesn't work either.

class A {};

class B
{
    public:
    B(A){};
};

void func(B){};

template<typename T>
class AT {};

template<typename T>
class BT
{
    public:
    BT(AT<T>){};
};

template<typename T>
void funcT(BT<T>){};

int main()
{
    func(A{});
    funcT(AT<int>{}); // unable to deduce the funcT template argument
    funcT<int>(AT<int>{}); // compiles but I don't want to write that

    return 0;
}

There are dumb fixes like writing function version that accepts AT<T> and casts it to BT<T>. But I don't want to write a bunch of functions when everything should work as is. I could understand it if it was an ambiguous call...

Body:
The other answer explained what was going on, but there is a way around this

template<class T, template<class>class Temp, typename std::enable_if<std::is_convertible< Temp<T>, BT<T>>::value, bool>::type = true>
void funcT(Temp<T> t) {
    auto bt = static_cast<BT<T>>(t);
}

This can be called by fooT(A<int>{}); as well as fooT(B<int>{}); having the same behavior.


问:
Swift 5.1 @propertyWrapper - 'self' used in property access before all stored properties are initialized
I am trying to use Swift 5.1 property wrappers but every time I think I have a cool use case for it, I eventually hit the problem where I can't use them inside of my View Model's initializer.

Take this extremely simple example.

class NoProblem {
  var foo = "ABC"
  let upperCased: String

  init(dependencies: AppDependencies) {
    self.upperCased = foo.uppercased()
  }
}
```

<pre class="lang-swift prettyprint-override"><code>@propertyWrapper
struct Box<Value> {
  private var box: Value

  init(wrappedValue: Value) {
    box = wrappedValue
  }

  var wrappedValue: Value {
    get { box }
    set { box = newValue }
  }
}

class OhNoes {
  @Box var foo = "ABC"
  let upperCased: String

  init(dependencies: AppDependencies) {
    self.upperCased = foo.uppercased()
  }
}
</code>```

In NoProblem, everything works as expected. However in OhNoes I get this error: 'self' used in property access 'foo' before all stored properties are initialized.

Of course this is an extremely simplified example, but I get the same problem when doing an @Property wrapper for observable properties, or an @Injected wrapper like in this article, etc.

And no, sadly making it a lay property won't work either: Property 'foo' with a wrapper cannot also be lazy.

This is also a pretty big problem in SwiftUI, see this example:

class AppStore: ObservableObject {
  let foo = "foo"
}

struct ContentView: View {
  @EnvironmentObject private var store: AppStore
  private let foo: String

  init() {
    foo = store.foo // error: 'self' used before all stored properties are initialized
  }

  var body: some View {
    Text("Hello world")
  }
}
```

答:
The most frictionless workaround is to make upperCased a var instead of a let. Okay, that might not be desirable, but at least it means you can keep all of your code and use the resulting OhNoes instance immediately:

```<code>struct AppDependencies {}
@propertyWrapper struct Box<T> {
    private var boxed: T
    init(wrappedValue: T) {
        boxed = wrappedValue
    }
    var wrappedValue: T {
        get { boxed }
        set { boxed = newValue }
    }
}
class OhNoes {
    @Box var foo = "abc"
    var upperCased: String = "" // this is the only real change
    init(dependencies: AppDependencies) {
        self.upperCased = foo.uppercased()
    }
}
</code>```

If you really don't like that, then refer directly to _foo.wrappedValue as suggested by the other answer.

Body:
I am trying to use Swift 5.1 property wrappers but every time I think I have a cool use case for it, I eventually hit the problem where I can't use them inside of my View Model's initializer.

Take this extremely simple example.

class NoProblem {
  var foo = "ABC"
  let upperCased: String

  init(dependencies: AppDependencies) {
    self.upperCased = foo.uppercased()
  }
}

@propertyWrapper
struct Box<Value> {
  private var box: Value

  init(wrappedValue: Value) {
    box = wrappedValue
  }

  var wrappedValue: Value {
    get { box }
    set { box = newValue }
  }
}

class OhNoes {
  @Box var foo = "ABC"
  let upperCased: String

  init(dependencies: AppDependencies) {
    self.upperCased = foo.uppercased()
  }
}

In NoProblem, everything works as expected. However in OhNoes I get this error: 'self' used in property access 'foo' before all stored properties are initialized.

Of course this is an extremely simplified example, but I get the same problem when doing an @Property wrapper for observable properties, or an @Injected wrapper like in this article, etc.

And no, sadly making it a lay property won't work either: Property 'foo' with a wrapper cannot also be lazy.

This is also a pretty big problem in SwiftUI, see this example:

class AppStore: ObservableObject {
  let foo = "foo"
}

struct ContentView: View {
  @EnvironmentObject private var store: AppStore
  private let foo: String

  init() {
    foo = store.foo // error: 'self' used before all stored properties are initialized
  }

  var body: some View {
    Text("Hello world")
  }
}

Body:
The most frictionless workaround is to make upperCased a var instead of a let. Okay, that might not be desirable, but at least it means you can keep all of your code and use the resulting OhNoes instance immediately:

struct AppDependencies {}
@propertyWrapper struct Box<T> {
    private var boxed: T
    init(wrappedValue: T) {
        boxed = wrappedValue
    }
    var wrappedValue: T {
        get { boxed }
        set { boxed = newValue }
    }
}
class OhNoes {
    @Box var foo = "abc"
    var upperCased: String = "" // this is the only real change
    init(dependencies: AppDependencies) {
        self.upperCased = foo.uppercased()
    }
}

If you really don't like that, then refer directly to _foo.wrappedValue as suggested by the other answer.


问:
How implement sticky footer in recyclerview
I have RecyclerView and I need next behavior:

if there are a lot of items (more then fits screen) - footer is last item

if few item/no item - footer is located at screen bottom

Please advise how can I implement this behavior.

答:
```<code>class FooterViewHolder(private val parent: ViewGroup) {

...

fun bind(item: Item) {
    ...
    itemView.post(::adjustTop)
}

private fun adjustTop() {
    val parent = parent as RecyclerView
    var topOffset = parent.height
    for (child in parent.children) topOffset -= child.height
    (itemView.layoutParams as ViewGroup.MarginLayoutParams)
        .setMargins(0, topOffset.coerceAtLeast(0), 0, 0)
}
}
</code>```


问:
pairwise combinations to matrix/table representation
I think this is probably something people have already solved, and may even be some baked in functionality I'm missing, so I figured I'd ask before I reinvent the wheel.

Basically, given some pairwise output from itertools.combinations, I'd like to represent it as a matrix/table of each comparison.

So far, I'm roughly up to this point:

```<code>from itertools import combinations

def chunks(l, n):
    n = max(1, n)
    return [l[i:i+n] for i in range(0, len(l), n)]

x = [("A", 1), ("B", 2), ("C", 3), ("D", 4), ("E", 5)]

[print(i) for i in chunks([i[1]+j[1] for i, j in combinations(x, 2)], len(x)-1)]
</code>```

This gives me a matrix-style output:

```<code>[3, 4, 5, 6]
[5, 6, 7, 7]
[8, 9]
[None, None, None]
</code>```

I'm not sure where the Nones are coming from just yet as the output of chunks([i[1]+j[1] for i, j in combinations(x, 2)], len(x)-1) is:

```<code>[[3, 4, 5, 6], [5, 6, 7, 7], [8, 9]]
</code>```

But I can look into that later on (but feel free to point out my obvious mistake!)

I'd ideally like to end up with a pairwise matrix (ideally with the names of the comparisons attached too so it would appear something like:

```<code>    A    B    C    D    E
A        3    4    5    6
B             5    6    7
C                  7    8
D                       9
E
</code>```

It clear my naive approach of chunking by the length of the input data isn't quite right either as the 7 belonging to the C+D comparison is on the wrong line. I'd forgotten to account for the additional entry disappearing each time.

If there's a better way altogether, I'm happy to change the approach. I've focussed on using itertools for this as it may end up being run over large files with potentially thousands of comparisons in a bigger script with other calculations etc happening, so avoiding self, and repeat comparisons is ideal.

Edit:

To add, I'd like to subsequently be able to output the matrix that I depicted, with the row and column names, to a tsv/csv or similar.

答:
This creates a matrix as you describe, using 0's for the "blanks":

```<code>[[(a[1]+b[1] if a[0]<b[0] else 0) for b in x] for a in x]
</code>```

To print it out:

```<code>print("\t".join(['']+[a[0] for a in x]))
for a in x:
    print("\t".join([a[0]] + [(str(a[1]+b[1]) if a[0]<b[0] else '') for b in x]))
</code>```

Body:
I think this is probably something people have already solved, and may even be some baked in functionality I'm missing, so I figured I'd ask before I reinvent the wheel.

Basically, given some pairwise output from itertools.combinations, I'd like to represent it as a matrix/table of each comparison.

So far, I'm roughly up to this point:

from itertools import combinations

def chunks(l, n):
    n = max(1, n)
    return [l[i:i+n] for i in range(0, len(l), n)]

x = [("A", 1), ("B", 2), ("C", 3), ("D", 4), ("E", 5)]

[print(i) for i in chunks([i[1]+j[1] for i, j in combinations(x, 2)], len(x)-1)]

This gives me a matrix-style output:

[3, 4, 5, 6]
[5, 6, 7, 7]
[8, 9]
[None, None, None]

I'm not sure where the Nones are coming from just yet as the output of chunks([i[1]+j[1] for i, j in combinations(x, 2)], len(x)-1) is:

[[3, 4, 5, 6], [5, 6, 7, 7], [8, 9]]

But I can look into that later on (but feel free to point out my obvious mistake!)

I'd ideally like to end up with a pairwise matrix (ideally with the names of the comparisons attached too so it would appear something like:

    A    B    C    D    E
A        3    4    5    6
B             5    6    7
C                  7    8
D                       9
E

It clear my naive approach of chunking by the length of the input data isn't quite right either as the 7 belonging to the C+D comparison is on the wrong line. I'd forgotten to account for the additional entry disappearing each time.

If there's a better way altogether, I'm happy to change the approach. I've focussed on using itertools for this as it may end up being run over large files with potentially thousands of comparisons in a bigger script with other calculations etc happening, so avoiding self, and repeat comparisons is ideal.

Edit:

To add, I'd like to subsequently be able to output the matrix that I depicted, with the row and column names, to a tsv/csv or similar.

Body:
This creates a matrix as you describe, using 0's for the "blanks":

[[(a[1]+b[1] if a[0]<b[0] else 0) for b in x] for a in x]

To print it out:

print("\t".join(['']+[a[0] for a in x]))
for a in x:
    print("\t".join([a[0]] + [(str(a[1]+b[1]) if a[0]<b[0] else '') for b in x]))


问:
scroll to element on reload page react
I'm trying to figure out how to scroll to the element after page reloads. I'm trying to ref the element and scroll to it after page reloads.

My current example will just scroll to the end of the page

```<code>const transactionRef = useRef(null)
const scrollToElemet = () => {
    transactionRef.current.scrollIntoView({ block: 'end', behavior: 'smooth' });
  }

  useEffect(scrollToElemet)

return (
  <div ref={transactionRef}></div>
)
</code>```

How can I calculate the position of the element and scroll to it on page reload? Thanks

答:
Adding this answer because querying the DOM in react is an anti-pattern:

```<code>export default function App() {
  const footerRef = useRef();

  useEffect(() => {
    footerRef.current.scrollIntoView();
  }, []);

  return (
    <>
      <div className="main">Main</div>
      <div ref={footerRef} className="footer">
        Footer
      </div>
    </>
  );
}
</code>```

Title: scroll to element on reload page react

Body:
I'm trying to figure out how to scroll to the element after page reloads. I'm trying to ref the element and scroll to it after page reloads.

My current example will just scroll to the end of the page

const transactionRef = useRef(null)
const scrollToElemet = () => {
    transactionRef.current.scrollIntoView({ block: 'end', behavior: 'smooth' });
  }

  useEffect(scrollToElemet)

return (

)

How can I calculate the position of the element and scroll to it on page reload? Thanks

Body:
Adding this answer because querying the DOM in react is an anti-pattern:

export default function App() {
  const footerRef = useRef();

  useEffect(() => {
    footerRef.current.scrollIntoView();
  }, []);

  return (
    <>
      <div className="main">Main</div>
      <div ref={footerRef} className="footer">
        Footer
      </div>
    </>
  );
}


问:
Display the character after a white space
I am new to PowerBuilder, I have this dropdown list box which displays the names of employees.
Jerry Casimera Fondrada, Joy Valdez Cortez, Kyle Vincent Korver and Joe Pring. Out from those names, I would like to generate a username using the first letters of their first name together with the last name. Example JCFondera, JVCortez, KVKorver and JPring.</p>

答: Do the names come from a database?  If yes, I advise to use a DropDownDataWindow (DDDW), instead.  In the select you define for the DDDW, use a computed field to let the information appear as you wish. The exact syntax will depend on the DB you use.  Alternatively, use a DDDW and a a computed field. In both cases, no further programming needed.</p>


问:
Objective-c "multiple" getters and binding
I have a class that holds some information and one member is a property options (an NSUInteger). The individual bits of options should be accessible through property getters and setters, to be value-bound to checkboxes:

```<code>#define OP_CHAN_TAG   12

@interface MuxConfig: NSObject

@property NSUInteger options;
@property (nonatomic) BOOL opTagBlocks;

@end

@implementation MuxConfig

- (BOOL) isOpTagBlocks
{
  return (_options & (1 << OP_CHAN_TAG));
}

- (void) setOpTagBlocks:(BOOL)op
{
  if (op)
    _options |= (1 << OP_CHAN_TAG);
  else
    _options &= ~(1 << OP_CHAN_TAG);
}

@end
</code>```

In this example, a checkbox has a value binding to opTagBlocks and an action handler to send the entire options property to a hardware device. This mechanism works. Another part of the application can receive the options from said device and stores them as one word into property options. And I was hoping that the checkbox(es) got updated but they don't. Obviously accessing property options does not 'trigger' the bitwise option handler(s).
So the big question is: how can I make this work?

答:
The solution is to register dependent keys for your properties. Here is the documentation covering this: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVODependentKeys.html

So in your example above, adding

```<code>+ (NSSet *)keyPathsForValuesAffectingOptions {

    return [NSSet setWithObjects:@"opTagBlocks",@"opTagWhatever",nil];
}
</code>```

signals to the system that changes to opTagBlocks (and a second hypothetical property opTagWhatever to show how to add you other flags) also will change options.

You also need the reverse, and indicate that changes to options will also affect  opTagBlocks:

```<code>+ (NSSet *)keyPathsForValuesAffectingOpTagBlocks {

    return [NSSet setWithObjects:@"options",nil];
}
</code>```

Alternatively you could implement + keyPathsForValuesAffectingValueForKey:, see the above documentation.

Body:
I have a class that holds some information and one member is a property options (an NSUInteger). The individual bits of options should be accessible through property getters and setters, to be value-bound to checkboxes:

#define OP_CHAN_TAG   12

@interface MuxConfig: NSObject

@property NSUInteger options;
@property (nonatomic) BOOL opTagBlocks;

@end

@implementation MuxConfig

- (BOOL) isOpTagBlocks
{
  return (_options & (1 << OP_CHAN_TAG));
}

- (void) setOpTagBlocks:(BOOL)op
{
  if (op)
    _options |= (1 << OP_CHAN_TAG);
  else
    _options &= ~(1 << OP_CHAN_TAG);
}

@end

In this example, a checkbox has a value binding to opTagBlocks and an action handler to send the entire options property to a hardware device. This mechanism works. Another part of the application can receive the options from said device and stores them as one word into property options. And I was hoping that the checkbox(es) got updated but they don't. Obviously accessing property options does not 'trigger' the bitwise option handler(s).
So the big question is: how can I make this work?

Body:
The solution is to register dependent keys for your properties. Here is the documentation covering this: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVODependentKeys.html

So in your example above, adding

+ (NSSet *)keyPathsForValuesAffectingOptions {

    return [NSSet setWithObjects:@"opTagBlocks",@"opTagWhatever",nil];
}

signals to the system that changes to opTagBlocks (and a second hypothetical property opTagWhatever to show how to add you other flags) also will change options.

You also need the reverse, and indicate that changes to options will also affect  opTagBlocks:

+ (NSSet *)keyPathsForValuesAffectingOpTagBlocks {

    return [NSSet setWithObjects:@"options",nil];
}

Alternatively you could implement + keyPathsForValuesAffectingValueForKey:, see the above documentation.


问:
How can I combine 4 columns of data in mysql? (3 columns are always null)
In my university project we got a csv file with about 15k rows and its about technical support requests, each request has one column of the brand and another 4 columns for the model, so one columns for the 4 possible brand and for each brand a column which model it is. So in each row there is only one which is filled the rest is null. I want to merge all 4 columns together.

Thank you in advance, this is my first post.

答:
If you are sure that only 1 of the models is going to be filled, then the concat is the option for you.

```<code>select brand, concat(model1,model2,model3,model4) MODEL from {yourtable}
</code>```

Hope it helps!

Body:
If you are sure that only 1 of the models is going to be filled, then the concat is the option for you.

select brand, concat(model1,model2,model3,model4) MODEL from {yourtable}

Hope it helps!


问:
How do I execute an external JavaScript every few seconds?
I like to load an external JavaScript once every 10 seconds or so. Or whenever the body of the page is clicked(if so, I need to run the script only if few seconds are passed).
Even if anyone points me to the documentation., it will be more than sufficient.</p>

答:
You can try bellow code snippet :

index.html

```<code><html>
<head>
<body onClick="refreshPage()">

this page will refresh in every 10 seconds
</body>
</html>

<script src="script.js"></script>
</code>```

script.js

```<code>function refreshPage(){
    window.location.reload();
}

setTimeout(function(){
    window.location.reload();
 }, 10000);
</code>```

Body:
You can try bellow code snippet :

index.html

<html>
<head>
<body onClick="refreshPage()">

this page will refresh in every 10 seconds
</body>
</html>

<script src="script.js"></script>

script.js

function refreshPage(){
    window.location.reload();
}

setTimeout(function(){
    window.location.reload();
 }, 10000);


问:
Hardware/Software Implementation
What does it mean to say that a function (e.g. modular multiplication,sine) is implemented in hardware as opposed to software?</p>

答:
Typically, "software" is a list of instructions from a small set of precise formal instructions supported by the hardware in question. The hardware (the cpu) runs in an infinite loop executing your instruction stream stored in "memory".

When we talk about a software implementation of an algorithm, we mean that we achieve the final answer by having the CPU carry out some set of these instructions in the order put together by an outside programmer.

When we talk about a hardware implementation, we mean that the final answer is carried out with intermediate steps that don't come from a formal (inefficient) software stream coded up by a programmer but instead is carried out with intermediate steps that are not exposed to the outside world. Hardware implementations thus are likely to be faster because (a) they can be very particular to the algorithm being implemented, with no need to reach well-defined states that the outside would will see, and (b) don't have to sync up with the outside world.

Note, that I am calling things like sine(x), "algorithms".

To be more specific about efficiency, the software instructions, being a part of a formal interface, have predefined start/stop points as they await for the next clock cycle. These sync points are needed to some extent to allow other software instructions and other hardware to cleanly and unambiguously access these well defined calculations. In contrast, a hardware implementation is more likely to have a larger amount of its internal implementations be asynchronous, meaning that they run to completion instead of stopping at many intermediate points to await a clock tick.

For example, most processors have an instruction that carries out an integer addition. The entire process of calculating the final bit positions is likely done asynchronously. The stop/sync point occurs only after the added result is achieved. In turn, a more complex algorithm than "add", and which is done in software that contains many such additions, necessarily is partly carried out asynchronously (eg, in between each addition) but with many sync points (after each addition, jump, test, etc, result is known). If that more complex algorithm were done entirely in hardware, it's possible it would run to completion from beginning to end entirely independent of the timing clock. No outside program instructions would be consulted during the hardware calculation of that algorithm.

Title: Hardware/Software Implementation


问:
Can I manually verify an email/password account on firebase?
I'm trying to create a demo account for my app, so that I can submit it to the iOS App Store. The app requires that your email be verified before you can use it. However, the verification emails are not coming into my demo@xxx.xxx inbox, and so I cannot verify the account. Is there any way I can manually set that firebase account as verified?
Thanks</p>

答:
This works as a cloud function.

I add the userid as a key to a child called force with any value and it triggers this function that authenticates the email.

you also must include

```<code>const admin = require('firebase-admin');
</code>```

cloud function

```<code>  exports.forceQue = functions.database.ref('/force/{uid}').onWrite((data,context) => {

  if (!data.after.exists()) {
      return false;
  }

  const uid = context.params.uid;

        admin.auth().updateUser(uid, {emailVerified: true});
        return true;
  });
</code>```

Body:
This works as a cloud function.

I add the userid as a key to a child called force with any value and it triggers this function that authenticates the email.

you also must include

const admin = require('firebase-admin');

cloud function

  exports.forceQue = functions.database.ref('/force/{uid}').onWrite((data,context) => {

  if (!data.after.exists()) {
      return false;
  }

  const uid = context.params.uid;

        admin.auth().updateUser(uid, {emailVerified: true});
        return true;
  });


问:
Typescript: what is the best way to copy *some* (not all) properties from one class instance to another object?
Suppose I have a Typescript class like the following:

```<code>class MyClass {
  constructor(public x: boolean, public y: string, public z: number) {}
}
</code>```

I create an instance of the class:

```<code>const myInstance = new MyClass(true, 'hi', 45);
</code>```

If I want to copy the values of only the properties x and z to another object, I could do the following:

```<code>const myInstance = new MyClass(true, 'hi', 45);
const { x, z } = myInstance;
const myObject = { x, z };
</code>```

Is there any better (and simple) way of achieving this?

Or is this the simplest way?

Note, the above example class is small. Imagine if the class has, say, 20 properties, and I want to get only 5 of them.

It would be good to see a generic solution to the problem.

答:
You can try something like this:</p>

```<code>class MyClass {
  constructor(public x: boolean, public y: string, public z: number) {}
}

const myInstance = new MyClass(true, 'hi', 45);

const { y, ...xAndZ } = myInstance;

console.log(xAndZ) // outputs => {x: true, z:45}
</code>```

Body:
Suppose I have a Typescript class like the following:

class MyClass {
  constructor(public x: boolean, public y: string, public z: number) {}
}

I create an instance of the class:

const myInstance = new MyClass(true, 'hi', 45);

If I want to copy the values of only the properties x and z to another object, I could do the following:

const myInstance = new MyClass(true, 'hi', 45);
const { x, z } = myInstance;
const myObject = { x, z };

Is there any better (and simple) way of achieving this?

Or is this the simplest way?

Note, the above example class is small. Imagine if the class has, say, 20 properties, and I want to get only 5 of them.

It would be good to see a generic solution to the problem.

Body:
You can try something like this:

class MyClass {
  constructor(public x: boolean, public y: string, public z: number) {}
}

const myInstance = new MyClass(true, 'hi', 45);

const { y, ...xAndZ } = myInstance;

console.log(xAndZ) // outputs => {x: true, z:45}


问:
Statistical significance of Lift (Interest) measure for association rule mining
Is there a way to determine the statistical significance (p-values) for lift measures of interestingness for association rule mining?</p>

答: Lift measures the dependence of the LHS and the RHS. The chi-squared statistics for the test of independence can be converted into a p-value (most tools like arules will do that for you). Alternatively, Fishers exact test produces a p-values. Both measures are available via the function interestMeasures() in arules.


问:
How to add a .h file to a flex definition in CMake
So I am trying to use flex in a project with Clion (because I'm on windows), which uses CMake but I cannot compile because my lexer.l file includes token.h
my CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.10)

find_package(FLEX)

FLEX_TARGET(MyScanner lexer.l ${CMAKE_CURRENT_BINARY_DIR}/lex.yy.c)

include_directories(${CMAKE_CURRENT_BINARY_DIR})
add_executable(lexer token.h ${FLEX_MyScanner_OUTPUTS}
         printtoken.c lexan.h lexanl.c )
</code>```

ERROR:

```<code>[ 16%] Building C object CMakeFiles/lexer.dir/lex.yy.c.o
lexan.l:36:10: fatal error: token.h: No such file or directory
compilation terminated.
CMakeFiles/lexer.dir/build.make:74: recipe for target 'CMakeFiles/lexer.dir/lex.yy.c.o' failed
</code>```

How do I include the token.h?

答:
Problem Solved:

I had to add ${CMAKE_SOURCE_DIR} to the include_directories() call for it to find the header file.

Body:
So I am trying to use flex in a project with Clion (because I'm on windows), which uses CMake but I cannot compile because my lexer.l file includes token.h
my CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)

find_package(FLEX)

FLEX_TARGET(MyScanner lexer.l ${CMAKE_CURRENT_BINARY_DIR}/lex.yy.c)

include_directories(${CMAKE_CURRENT_BINARY_DIR})
add_executable(lexer token.h ${FLEX_MyScanner_OUTPUTS}
         printtoken.c lexan.h lexanl.c )

ERROR:

[ 16%] Building C object CMakeFiles/lexer.dir/lex.yy.c.o
lexan.l:36:10: fatal error: token.h: No such file or directory
compilation terminated.
CMakeFiles/lexer.dir/build.make:74: recipe for target 'CMakeFiles/lexer.dir/lex.yy.c.o' failed

How do I include the token.h?


问:
Error: Field X "has changed type from NUMERIC to FLOAT" when INSERTing data to BigQuery with load_table_from_json
I am trying to add data to a BigQuery table using the official Python SDK.

When I pass some JSON into the load_table_from_json(data, table) function, the API response complains that one of my values is a FLOAT in the dataset, but the table's schema says that column is NUMERIC. The value is 0.0.

Since JSON doesn't have explicit data types, it's confusing how/why the API would think that it's a FLOAT type, or how I could force it to know otherwise. I would think that BigQuery's API would be smart enough to know that the value could be safely inserted into either column type.

The full error message is:

```<code>400 Provided Schema does not match Table my-project:my-dataset.my-table. Field count_purchased has changed type from NUMERIC to FLOAT
</code>```

答:
The solution to this is to explicitly specify your own schema to tell BigQuery this is a NUMERIC value. This is done by passing a LoadJobConfig when calling load_table_from_json(data, table, job_config=my_job_config).

Here's how I defined the schema for my load job. Notice that the only thing I needed to pass in was the schema definition; the rest of the defaults worked fine.

my_schema = [
  {
    "name": "count_purchased",
    "type": "NUMERIC"
  },{
    "name": "_load_datetime",
    "type": "DATETIME"
  }
]

my_job_config = bigquery.LoadJobConfig(schema=my_schema)

client = bigquery.Client()
client.load_table_from_json(data, table, job_config=my_job_config)
```

This is necessary because the load_table_from_json method will try to create its own LoadJobConfig object if one is not explicitly passed in [source code]. The load job by default will have autodetect=true. It seems that auto-detection on the BigQuery server-side is not aware of the existing schema. In other words: it defaults to FLOAT any time there's a decimal in the value, even when its destination column is NUMERIC and the value is compatible with that data type. The same thing happens if you try to insert an un-quoted number into a STRING column.

Body:
I am trying to add data to a BigQuery table using the official Python SDK.

When I pass some JSON into the load_table_from_json(data, table) function, the API response complains that one of my values is a FLOAT in the dataset, but the table's schema says that column is NUMERIC. The value is 0.0.

Since JSON doesn't have explicit data types, it's confusing how/why the API would think that it's a FLOAT type, or how I could force it to know otherwise. I would think that BigQuery's API would be smart enough to know that the value could be safely inserted into either column type.

The full error message is:

400 Provided Schema does not match Table my-project:my-dataset.my-table. Field count_purchased has changed type from NUMERIC to FLOAT

Body:
The solution to this is to explicitly specify your own schema to tell BigQuery this is a NUMERIC value. This is done by passing a LoadJobConfig when calling load_table_from_json(data, table, job_config=my_job_config).

Here's how I defined the schema for my load job. Notice that the only thing I needed to pass in was the schema definition; the rest of the defaults worked fine.

my_schema = [
  {
    "name": "count_purchased",
    "type": "NUMERIC"
  },{
    "name": "_load_datetime",
    "type": "DATETIME"
  }
]

my_job_config = bigquery.LoadJobConfig(schema=my_schema)

client = bigquery.Client()
client.load_table_from_json(data, table, job_config=my_job_config)

This is necessary because the load_table_from_json method will try to create its own LoadJobConfig object if one is not explicitly passed in [source code]. The load job by default will have autodetect=true. It seems that auto-detection on the BigQuery server-side is not aware of the existing schema. In other words: it defaults to FLOAT any time there's a decimal in the value, even when its destination column is NUMERIC and the value is compatible with that data type. The same thing happens if you try to insert an un-quoted number into a STRING column.


问:
Set indent on view in Zend Framework
In Zend Framework, it is possible to set indentation for headMeta(), headLink(), etc:

```<code><?= $this->headLink()->setIndent("\t\t") ?>
</code>```

I like this. I like things tidy. So, now I would want to indent my entire view as well in the layout.phtml file, causing every new line in the view script to be indented with X tabs.

```<code><?= $this->layout()->setIndent("\t\t")->content ?>
</code>```

This does not work. Is there any way to do this within Zend Framework without having to intercept the output with ob_start?

答:
Zend_Layout has no setIndent(), check here: http://framework.zend.com/apidoc/1.11/_Layout.html#Zend_Layout You have to take care of the indentation by yourself in your template.

A generic solution would be to use Tidy with Zend Framework. The options to use then would be

```<code>indent => true
indent-spaces => 4
</code>```

Title: Set indent on view in Zend Framework

Body:
In Zend Framework, it is possible to set indentation for headMeta(), headLink(), etc:

<?= $this->headLink()->setIndent("\t\t") ?>

I like this. I like things tidy. So, now I would want to indent my entire view as well in the layout.phtml file, causing every new line in the view script to be indented with X tabs.

<?= $this->layout()->setIndent("\t\t")->content ?>

This does not work. Is there any way to do this within Zend Framework without having to intercept the output with ob_start?

Body:
Zend_Layout has no setIndent(), check here: http://framework.zend.com/apidoc/1.11/_Layout.html#Zend_Layout You have to take care of the indentation by yourself in your template.

A generic solution would be to use Tidy with Zend Framework. The options to use then would be

indent => true
indent-spaces => 4


问:
Seperate Pact Interactions in Provider Verification Tests by Endpoint
I just started to adopt Pact test for my system that consists of one provider service and an Angular frontend as the consumer. I succeeded in setting up both sides, thus, the Angular application generates a (single) pact file with many interactions to multiple endpoints of my provider service. In the provider, I do now face the issue that my verification test gets very large and overly complicated since I have to mock all my endpoints in a single test with all their data, e.g.:

@Provider("example-backend")
@PactFolder("pacts")
@SpringBootTest(...)
class ComprehensivePactTest {

    [...]

    @State("healthy")
    fun `healthy state`() {
        whenever(exampleService.dosomething(any())).thenReturn(exampleResponse)
        whenever(otherService.somethingElse()).thenReturn(otherResponse)
    }
}
```

<p>Is there a way to seperate the interaction from the pact file such that I could have multiple small verification tests in my provider? For instance, I would like to have a verification test for all requests with path starting with "/example" and a second test for path starting with "/other".</p>

<p>So what I would prefer to have is smaller, focused verification test like so:</p>

<pre class="lang-java prettyprint-override"><code>@Provider("example-backend")
@PactFolder("pacts")
@SpringBootTest(...)
class ExampleEndpointPactTest {

    [... include some filter logic here ...]

    @State("healthy")
    fun `healthy state`() {
        whenever(exampleService.dosomething(any())).thenReturn(exampleResponse)
    }
}

@Provider("example-backend")
@PactFolder("pacts")
@SpringBootTest(...)
class OtherEndpointPactTest {

    [... include some filter logic here ...]

    @State("healthy")
    fun `healthy state`() {
        whenever(otherService.somethingElse()).thenReturn(otherResponse)
    }
}
</code>```

Or do I have a fallacy in my thinking? Thanks.

答:
The JUnit4 Readme has a section about this topic. I think it also applies to Junit5 https://github.com/DiUS/pact-jvm/tree/master/provider/pact-jvm-provider-junit#using-multiple-classes-for-the-state-change-methods

Using multiple classes for the state change methods

If you have a large number of state change methods, you can split
  things up by moving them to other classes. There are two ways you can
  do this: Use interfaces

You can put the state change methods on interfaces and then have your
  test class implement those interfaces. See
  StateAnnotationsOnInterfaceTest for an example. Specify the additional
  classes on the test target

You can provide the additional classes to the test target with the
  withStateHandler or setStateHandlers methods. See
  BooksPactProviderTest for an example.

Body:
I just started to adopt Pact test for my system that consists of one provider service and an Angular frontend as the consumer. I succeeded in setting up both sides, thus, the Angular application generates a (single) pact file with many interactions to multiple endpoints of my provider service. In the provider, I do now face the issue that my verification test gets very large and overly complicated since I have to mock all my endpoints in a single test with all their data, e.g.:

@Provider("example-backend")
@PactFolder("pacts")
@SpringBootTest(...)
class ComprehensivePactTest {

    [...]

    @State("healthy")
    fun `healthy state`() {
        whenever(exampleService.dosomething(any())).thenReturn(exampleResponse)
        whenever(otherService.somethingElse()).thenReturn(otherResponse)
    }
}

Is there a way to seperate the interaction from the pact file such that I could have multiple small verification tests in my provider? For instance, I would like to have a verification test for all requests with path starting with "/example" and a second test for path starting with "/other".

So what I would prefer to have is smaller, focused verification test like so:

@Provider("example-backend")
@PactFolder("pacts")
@SpringBootTest(...)
class ExampleEndpointPactTest {

    [... include some filter logic here ...]

    @State("healthy")
    fun `healthy state`() {
        whenever(exampleService.dosomething(any())).thenReturn(exampleResponse)
    }
}

@Provider("example-backend")
@PactFolder("pacts")
@SpringBootTest(...)
class OtherEndpointPactTest {

    [... include some filter logic here ...]

    @State("healthy")
    fun `healthy state`() {
        whenever(otherService.somethingElse()).thenReturn(otherResponse)
    }
}

Or do I have a fallacy in my thinking? Thanks.


问:
Multi-platform compilation: System.Configuration.ConfigurationManager.GetSection throws error on .NetCore
Background:
We are in the process of migrating .Net application to .Net Core.
As a strategy, we would like to keep the existing functionality intact on Full framework while migrating portion of the application to .Net Core. Full application would support .services over Net remoting and REST API whereas .Net core application will only support REST API services.

We have decided to keep the same code base for entire application and support compilation on multiple platforms (NetcoreApp2.1 and Net472).
There is a single application configuration file. Most of the components are dependent on the information stored in this file. Thus we would like to retain the single configuration file for both platforms.
I used System.Configuration.ConfigurationManager package to access configuration information.

Issue:
ConfigurationManager.GetSection(string) throws exception on .Net core platform whereas it works fine on Net472.
Error Message: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section system.runtime.remoting

Work around tried so far:
ConfigurationManager.OpenExeConfiguration(configurationUserLevel).GetSection(string) works perfect on both the platforms for fetching the same section

Sample Code:

```<code>static MyConfigurationSection myConfigurationSettings { get; set; }
        static void Main(string[] args)
        {
            LoadSettings();
        }

        private static void LoadSettings()
        {
            try
            {
                //Net472 : Works
                //NetCoreApp2.1: Throws exception
                myConfigurationSettings = ConfigurationManager.GetSection("myCustomSettings") as MyConfigurationSection;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //Works on both platform
            myConfigurationSettings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).GetSection("myCustomSettings") as MyConfigurationSection;
            Console.WriteLine(myConfigurationSettings.Applications.Count);
            Console.ReadLine();
        }
</code>```

Here is configuration file

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="myCustomSettings" type="TestConfigManager.MyConfigurationSection, TestConfigManager" />
</configSections>
<myCustomSettings>
<applications/>
</myCustomSettings>
<system.runtime.remoting>
<application>
<channels>
<channel ref="tcp" port="1111" />
</channels>
</application>
</system.runtime.remoting>
</configuration>
</code>```

答:
Unfortunately, accessing configuration works slightly differently in the Core Framework (and also .NET 5 and 6). Even with the help of the links below, it took me some time to find it out.
This is how it worked for me:

As preparation, go to NUGET package manager and import

Microsoft.Extensions.Configation,

Microsoft.Extensions.Configation.Json,
Microsoft.Extensions.Configation.Xml

and (optional) Microsoft.Windows.Compatibility

Depending on the type of config file, access it as follows:

App.Config

Example:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="myKey" value="myValue"/>
    </appSettings>
</configuration>
</code>```

Declare

```<code>public static AppSettingsSection AppConfig { get; private set; } = null;
</code>```

Initialize it via

```<code>AppConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                                .AppSettings;
</code>```

Read any keys via:

```<code>var myValue = AppConfig.Settings["myKey"].Value;
</code>```

appconfig.json

Example:

```<code>{
    "AppSettings": {
        "myKey": "myValue"
    }
}
</code>```

Declare

```<code> public static IConfigurationSection JsonConfig { get; private set; } = null;
</code>```

Initialize it via

```<code>JsonConfig = new ConfigurationBuilder().AddJsonFile("appconfig.json",
                optional: true, reloadOnChange: true).Build().GetSection("AppSettings");
</code>```

Read any keys via:

```<code>var myValue = JsonConfig["myKey"];
</code>```

Helpful links:

cant read app config in c-sharp

how to read appsettings values from json

Comparision between appSettings and ApplicationSettings

Body:
Background:
We are in the process of migrating .Net application to .Net Core.
As a strategy, we would like to keep the existing functionality intact on Full framework while migrating portion of the application to .Net Core. Full application would support .services over Net remoting and REST API whereas .Net core application will only support REST API services.

We have decided to keep the same code base for entire application and support compilation on multiple platforms (NetcoreApp2.1 and Net472).
There is a single application configuration file. Most of the components are dependent on the information stored in this file. Thus we would like to retain the single configuration file for both platforms.
I used System.Configuration.ConfigurationManager package to access configuration information.

Issue:
ConfigurationManager.GetSection(string) throws exception on .Net core platform whereas it works fine on Net472.
Error Message: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section system.runtime.remoting

Work around tried so far:
ConfigurationManager.OpenExeConfiguration(configurationUserLevel).GetSection(string) works perfect on both the platforms for fetching the same section

Sample Code:

static MyConfigurationSection myConfigurationSettings { get; set; }
        static void Main(string[] args)
        {
            LoadSettings();
        }

        private static void LoadSettings()
        {
            try
            {
                //Net472 : Works
                //NetCoreApp2.1: Throws exception
                myConfigurationSettings = ConfigurationManager.GetSection("myCustomSettings") as MyConfigurationSection;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //Works on both platform
            myConfigurationSettings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).GetSection("myCustomSettings") as MyConfigurationSection;
            Console.WriteLine(myConfigurationSettings.Applications.Count);
            Console.ReadLine();
        }

Here is configuration file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>

</configSections>
<myCustomSettings>
<applications/>
</myCustomSettings>
<system.runtime.remoting>
<application>
<channels>
<channel ref="tcp" port="1111" />
</channels>
</application>
</system.runtime.remoting>
</configuration>

Body:
Unfortunately, accessing configuration works slightly differently in the Core Framework (and also .NET 5 and 6). Even with the help of the links below, it took me some time to find it out.
This is how it worked for me:

As preparation, go to NUGET package manager and import

Microsoft.Extensions.Configation,

Microsoft.Extensions.Configation.Json,
Microsoft.Extensions.Configation.Xml

and (optional) Microsoft.Windows.Compatibility

Depending on the type of config file, access it as follows:

App.Config

Example:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="myKey" value="myValue"/>
    </appSettings>
</configuration>

Declare

public static AppSettingsSection AppConfig { get; private set; } = null;

Initialize it via

AppConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                                .AppSettings;

Read any keys via:

var myValue = AppConfig.Settings["myKey"].Value;

appconfig.json

Example:

{
    "AppSettings": {
        "myKey": "myValue"
    }
}

Declare

 public static IConfigurationSection JsonConfig { get; private set; } = null;

Initialize it via

JsonConfig = new ConfigurationBuilder().AddJsonFile("appconfig.json",
                optional: true, reloadOnChange: true).Build().GetSection("AppSettings");

Read any keys via:

var myValue = JsonConfig["myKey"];

Helpful links:

cant read app config in c-sharp

how to read appsettings values from json

Comparision between appSettings and ApplicationSettings


问:
Python code to compute three square theorum
A positive integer m can be expresseed as the sum of three squares if it is of the form p + q + r where p, q, r ≥ 0, and p, q, r are all perfect squares. For instance, 2 can be written as 0+1+1 but 7 cannot be expressed as the sum of three squares. The first numbers that cannot be expressed as the sum of three squares are 7, 15, 23, 28, 31, 39, 47, 55, 60, 63, 71, … (see Legendre's three-square theorem).

Write a Python function squares(m) that takes an integer m as input and returns True if m can be expressed as the sum of three squares and False otherwise. (If m is not positive, your function should return False.)

答:
it will work </p>

```<code>import math
def threesquares(m):
    n=int(math.log10(m))
    if n<1:
        n=1
    for a in range(n+1):
        b=0
        z=0
        while z<=m:
            z=((pow(4,a))*(8*b+7))
            if z==m:
                return False
            b+=1
    return True
</code>```

<p>i am using  Legendre's three-square theorem </p>

Body:
it will work

import math
def threesquares(m):
    n=int(math.log10(m))
    if n<1:
        n=1
    for a in range(n+1):
        b=0
        z=0
        while z<=m:
            z=((pow(4,a))*(8*b+7))
            if z==m:
                return False
            b+=1
    return True

i am using  Legendre's three-square theorem


问:
unit test a variable declaration inside ngOnInit()
I'm trying to skill up in TDD, and I'm doing again every tutorials I could followed in Angular.
But this time trying to unit tests them with 100% code coverage.

I've a stupid question, that I can't find the answer in the documentation.
Can't find questions that are that simple in Stackoverflow neither.

```<code>import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, interval, Subscription } from 'rxjs/';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

  secondes: number;
  counterSubscritpion: Subscription;

  ngOnInit() {
    const counter = interval(1000);
    const dummy = 'foo';

    this.counterSubscritpion = counter.subscribe(
      (value) => {
        this.secondes = value;
    });
  }

  ngOnDestroy() {
    this.counterSubscritpion.unsubscribe();
  }
</code>```

My template is of course very simple :

 nothing should appear here : {{dummy}}

 whereas here should be {{secondes}} secondes

```

<p>So reading the documentation will help me testing <code>secondes</code> and <code>counterSubscritpion</code>...</p>

<p><strong>But how do I test that <code>counter</code> and <code>dummy</code> have been declared as well as their values ?</strong>
because Karma's test coverage report tells me that I should test the `interval(1000) calls</p>

<p>So far i'm stuck with this : </p>

```  let fixture: ComponentFixture<AppComponent>;
  let routerOutlet: any;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent]
    });
    fixture = TestBed.createComponent(AppComponent);
  });

  it ('should declare dummy variable', () => {
    const appComp = new AppComponent();
    appComp.ngOnInit();
    // and so what ???
  });
```

答:
First, you are using TestBed to create the AppComponent. TestBed configures and create a test context. It's possible to create routes, services and much more.

But you're not using it in your it. To get the created component by the TestBed, you can call TestBed.get(AppComponent) to retrieve it.

When creating a component outside TestBed (i.e. with new), you won't be able to access component's template. While it can be useful in some situations, it may not be in your case.

```<code>  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent]
    });
    fixture = TestBed.createComponent(AppComponent);
  });

  beforeEach(() => {
    component = TestBed.get(AppComponent);
  });

  it ('should create', () => {
    expect(component).toBeTruthy();
  });

  ...
</code>```

To test async mecanism, read https://codecraft.tv/courses/angular/unit-testing/asynchronous/#_code_async_code_and_code_whenstable_code and https://codecraft.tv/courses/angular/unit-testing/asynchronous/#_code_async_code_and_code_whenstable_code.
Which boils down to async, fakeAsync.

Body:
I'm trying to skill up in TDD, and I'm doing again every tutorials I could followed in Angular.
But this time trying to unit tests them with 100% code coverage.

I've a stupid question, that I can't find the answer in the documentation.
Can't find questions that are that simple in Stackoverflow neither.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, interval, Subscription } from 'rxjs/';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

  secondes: number;
  counterSubscritpion: Subscription;

  ngOnInit() {
    const counter = interval(1000);
    const dummy = 'foo';

    this.counterSubscritpion = counter.subscribe(
      (value) => {
        this.secondes = value;
    });
  }

  ngOnDestroy() {
    this.counterSubscritpion.unsubscribe();
  }

My template is of course very simple :

 nothing should appear here : {{dummy}}

 whereas here should be {{secondes}} secondes

So reading the documentation will help me testing secondes and counterSubscritpion...

But how do I test that counter and dummy have been declared as well as their values ?
because Karma's test coverage report tells me that I should test the `interval(1000) calls

So far i'm stuck with this :

  let fixture: ComponentFixture<AppComponent>;
  let routerOutlet: any;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent]
    });
    fixture = TestBed.createComponent(AppComponent);
  });

  it ('should declare dummy variable', () => {
    const appComp = new AppComponent();
    appComp.ngOnInit();
    // and so what ???
  });

Body:
First, you are using TestBed to create the AppComponent. TestBed configures and create a test context. It's possible to create routes, services and much more.

But you're not using it in your it. To get the created component by the TestBed, you can call TestBed.get(AppComponent) to retrieve it.

When creating a component outside TestBed (i.e. with new), you won't be able to access component's template. While it can be useful in some situations, it may not be in your case.

  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent]
    });
    fixture = TestBed.createComponent(AppComponent);
  });

  beforeEach(() => {
    component = TestBed.get(AppComponent);
  });

  it ('should create', () => {
    expect(component).toBeTruthy();
  });

  ...

To test async mecanism, read https://codecraft.tv/courses/angular/unit-testing/asynchronous/#_code_async_code_and_code_whenstable_code and https://codecraft.tv/courses/angular/unit-testing/asynchronous/#_code_async_code_and_code_whenstable_code.
Which boils down to async, fakeAsync.


问:
why is the address of a c++ function always True?
well why would,

```<code>#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}
</code>```

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?

答:
There is no overloaded function: operator<<(ostream&, int(*)()), so your function pointer is converted into the only type that works, bool. Then operator<<(ostream&, bool) is printing the converted value: 1.

You may be able to print the function address like so:

```<code>cout << (void*)&afunction << endl;
</code>```

Body:
well why would,

#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?

Body:
There is no overloaded function: operator<<(ostream&, int(*)()), so your function pointer is converted into the only type that works, bool. Then operator<<(ostream&, bool) is printing the converted value: 1.

You may be able to print the function address like so:

cout << (void*)&afunction << endl;


问:
How to filter and select multiple columns in pandas
I can't select and filter multiple columns together in Pandas. 'Name' and 'Year of Rank' are column names. Thank you!

```<code>dw[dw.Name=='El Toro' & dw['Name', 'Year of Rank']]
</code>```

答:
I believe this is what you want:

```<code>dw[dw['Name'] == 'El Toro'][['Name','Year of Rank']]
</code>```

or alternatively:

```<code>dw.loc[ dw['Name'] == 'El Toro', ['Name','Year of Rank']]
</code>```

Edit:
As pointed out in the comments, the second one is much preferred as it deals with the filtering and selection as a single entity.

Body:
I can't select and filter multiple columns together in Pandas. 'Name' and 'Year of Rank' are column names. Thank you!

dw[dw.Name=='El Toro' & dw['Name', 'Year of Rank']]

Body:
I believe this is what you want:

dw[dw['Name'] == 'El Toro'][['Name','Year of Rank']]

or alternatively:

dw.loc[ dw['Name'] == 'El Toro', ['Name','Year of Rank']]

Edit:
As pointed out in the comments, the second one is much preferred as it deals with the filtering and selection as a single entity.


问:
Create an external file for side menu
How do I create an external file for my side menu?

C Programming
C++
C#
Go
Java
JavaScript
PHP
Python
Ruby
Swift
```

<p>Currently I have these kind of links in every file and the code is just getting too much. Is there a way to create an external file for the menu items?</p>

<p>I tried this but the problem is <code>class="active"</code>. I want to highlight a menu item when my menu item is in index.php
I Know how to achieve this when my menu is in each individual HTML file but how do I do that when it's in external PHP file ?</p>

<p>Index.php</p>

```

  <link rel="stylesheet" type="text/css" href="CSS/Tags.css">
  <link rel="stylesheet" type="text/css" href="CSS/Nav.css">
  <link rel="stylesheet" type="text/css" href="CSS/Card.css">
  <link rel="stylesheet" type="text/css" href="CSS/Buttons.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">

&nbspOthers

 MS Excel
 MS PowerPoint
 MS Word
 WordPress

```

<p>Main file</p>

```<?php include('index.html'); ?>
```

答:
As pointed out by Abolfazl Ghaemi :

You should NOT use javascript to include your menu . you can use PHP to simply include your menu ( but i sugget header ) file to your page :

```<code><?php include('/template/header.html'); ?>
</code>```

The Gulp/Grunt solution is fine but I'll stick with the <?php include(); ?> solution for your problem.

Does the hosting machine speak PHP ?

If browsers can read HTML just fine to give you a webpage, they can't read PHP. Instead, PHP need to be executed by something on the hosting machine and you will need a PHP interpreter for that like Apache.

If you didn't already, I strongly recommend you to install it or even a full AMP stack.

PHP in HTML files won't work

You need to make sure your file using PHP instructions are .php files. Otherwise, the code in your <?php ?> tag (the PHP code) won't be interpreted at all.

Make sure your main file is a .php file.

Are you calling the correct file ?

Also, you need to be sure the file name you are including is correct. The content as shown in your question is

Main file

```<code><?php include('index.html'); ?>
</code>```

but your file is actually index.php not index.html.

HTML is prettier with CSS

If you want to "highlight" the item with active class, you will need CSS. You can quickly add CSS in your file with a ```

Title: Create an external file for side menu

Body:
How do I create an external file for my side menu?

C Programming
C++
C#
Go
Java
JavaScript
PHP
Python
Ruby
Swift

Currently I have these kind of links in every file and the code is just getting too much. Is there a way to create an external file for the menu items?

I tried this but the problem is class="active". I want to highlight a menu item when my menu item is in index.php
I Know how to achieve this when my menu is in each individual HTML file but how do I do that when it's in external PHP file ?

Index.php

  <link rel="stylesheet" type="text/css" href="CSS/Tags.css">
  <link rel="stylesheet" type="text/css" href="CSS/Nav.css">
  <link rel="stylesheet" type="text/css" href="CSS/Card.css">
  <link rel="stylesheet" type="text/css" href="CSS/Buttons.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">

&nbspOthers

 MS Excel
 MS PowerPoint
 MS Word
 WordPress

Main file

<?php include('index.html'); ?>

Body:
As pointed out by Abolfazl Ghaemi :

You should NOT use javascript to include your menu . you can use PHP to simply include your menu ( but i sugget header ) file to your page :

<?php include('/template/header.html'); ?>

The Gulp/Grunt solution is fine but I'll stick with the <?php include(); ?> solution for your problem.

Does the hosting machine speak PHP ?

If browsers can read HTML just fine to give you a webpage, they can't read PHP. Instead, PHP need to be executed by something on the hosting machine and you will need a PHP interpreter for that like Apache.

If you didn't already, I strongly recommend you to install it or even a full AMP stack.

PHP in HTML files won't work

You need to make sure your file using PHP instructions are .php files. Otherwise, the code in your <?php ?> tag (the PHP code) won't be interpreted at all.

Make sure your main file is a .php file.

Are you calling the correct file ?

Also, you need to be sure the file name you are including is correct. The content as shown in your question is

Main file

<?php include('index.html'); ?>

but your file is actually index.php not index.html.

HTML is prettier with CSS

If you want to "highlight" the item with active class, you will need CSS. You can quickly add CSS in your file with a <style> tag. See the example below.

<ul>
<li>Not highlighted</li>
<li>Still not highlighted</li>
<li class="active">Highlighted ! Spotlight's on me baby !</li>
<li>Not highlighted</li>
</ul>

<style>
.active {
  color: red;
  font-weight: bold;
}
</style>