答:
i think you want to do this, because you want to restrict this page if the user has not a required role:

```<code>if( $userrole !== 'Administrator' &&
    $userrole !== 'Manager' &&
    $userrole !== 'Product Hunter' &&
    $userrole !== 'Product Selector' &&
    $userrole !== 'Analytic' &&
    $userrole !== 'Order Manager'){
    header('Location: ../dashboard.php');
    die;
}
else{
 //code here
}
</code>```

better way I think:

```<code>$aAllowedRoles = array(
    'Administrator',
    'Manager',
    'Product Hunter',
    'Product Selector',
    'Analytic',
    'Order Manager'
);

if ( !in_array($userrole, $aAllowedRoles) ) {
    header('Location: ../dashboard.php');
    die;
}

// code here
</code>```

Title: Why does 'if statement' ignores conditions or reads them as if they are not true when they actually are?

Body:
I stumbled upon something that is causing me real hard time and I can't figure it out so, please take a look at my situation and help me out...

I am writing a code that is supposed to prevent some of the website users from accessing a specific part of the website called orders.php

Each user has a previously assigned role and I am trying to achieve this restriction by allowing only a few of the roles to access it so if you don't have some of the specific roles that are allowed to visit the website assigned to you, you get redirected to the homepage.

These is one of the ways that I've tried

    if( $userrole !== 'Administrator' OR
        $userrole !== 'Manager' OR
        $userrole !== 'Product Hunter' OR
        $userrole !== 'Product Selector' OR
        $userrole !== 'Analytic' OR
        $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    else{
     //code here
    }

I tried using || instead of OR but it is not working either

I also tried using elseif statement for each role like this:

if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Hunter'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Selector'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Analytic'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
   else{
    //code goes here
   }

As far as I understand, the code shall continue to execute the else statement the moment it reads your role name, for an example if you are an Administrator, then it shall execute the else statement because it is said that if you are not some of the specified roles then you will be redirected and since you are one of the specified roles then the code shall execute for you but for some odd reason it is redirecting you to the homepage no matter if you are an Administrator, Manager or a Visitor...

The only way the code allows you to visit the website instead of redirecting you to the homepage is when you have only one role specified, for an example:

    if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }else{
     //code goes here
    }

This way, if you are an Administrator, then you are allowed to visit the page, and if you have any different role then you get redirected.

The reason I use !== is because I want the code to define if this user can visit this part of the website at the beginning instead of telling it to show the code to the users with these few specific roles and redirect everyone else.

$userrole is previously set to equal a $_SESSION variable which contains the value of the actual role of the user and is defined at login, if I echo it, it prints the name of the role so that is not causing the problem for sure.

I've found some posts suggesting using switch statements but I haven't tried them yet since I prefer doing it this way if possible.

Thanks in advance!

Body:
i think you want to do this, because you want to restrict this page if the user has not a required role:

if( $userrole !== 'Administrator' &&
    $userrole !== 'Manager' &&
    $userrole !== 'Product Hunter' &&
    $userrole !== 'Product Selector' &&
    $userrole !== 'Analytic' &&
    $userrole !== 'Order Manager'){
    header('Location: ../dashboard.php');
    die;
}
else{
 //code here
}

better way I think:

$aAllowedRoles = array(
    'Administrator',
    'Manager',
    'Product Hunter',
    'Product Selector',
    'Analytic',
    'Order Manager'
);

if ( !in_array($userrole, $aAllowedRoles) ) {
    header('Location: ../dashboard.php');
    die;
}

// code here


来源: stackexchange

问:
Trouble training xgboost on categorical column
I am trying to run a Python notebook (link). At line below In [446]: where author train XGBoost, I am getting an error

ValueError: DataFrame.dtypes for data must be int, float or bool.
                  Did not expect the data types in fields StateHoliday, Assortment

```<code># XGB with xgboost library
dtrain = xgb.DMatrix(X_train[predictors], y_train)
dtest = xgb.DMatrix(X_test[predictors], y_test)

watchlist = [(dtrain, 'train'), (dtest, 'test')]

xgb_model = xgb.train(params, dtrain, 300, evals = watchlist,
                      early_stopping_rounds = 50, feval = rmspe_xg, verbose_eval = True)
</code>```

Here is the minimal code for testing

```<code>import pickle
import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split

with open('train_store', 'rb') as f:
    train_store = pickle.load(f)

train_store.shape

predictors = ['Store', 'DayOfWeek', 'Open', 'Promo', 'StateHoliday', 'SchoolHoliday', 'Year', 'Month', 'Day',
              'WeekOfYear', 'StoreType', 'Assortment', 'CompetitionDistance', 'CompetitionOpenSinceMonth',
              'CompetitionOpenSinceYear', 'Promo2', 'Promo2SinceWeek', 'Promo2SinceYear', 'CompetitionOpen',
              'PromoOpen']

y = np.log(train_store.Sales) # log transformation of Sales
X = train_store

# split the data into train/test set
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size = 0.3, # 30% for the evaluation set
                                                    random_state = 42)

# base parameters
params = {
    'booster': 'gbtree',
    'objective': 'reg:linear', # regression task
    'subsample': 0.8,          # 80% of data to grow trees and prevent overfitting
    'colsample_bytree': 0.85,  # 85% of features used
    'eta': 0.1,
    'max_depth': 10,
    'seed': 42} # for reproducible results

num_round = 60 # default 300

dtrain = xgb.DMatrix(X_train[predictors], y_train)
dtest  = xgb.DMatrix(X_test[predictors],  y_test)

watchlist = [(dtrain, 'train'), (dtest, 'test')]

xgb_model = xgb.train(params, dtrain, num_round, evals = watchlist,
                      early_stopping_rounds = 50, feval = rmspe_xg, verbose_eval = True)
</code>```

Link to train_store data file: Link 1

答:
The XGBoost version in the H2O package can handle categorical variables (but not too many!) but it appears that XGBoost as its own package can't.

I tried this with pandas dataframes but xgboost didn't like it

```<code>categoricals = ['StoreType', ] . # etc.
pdf[categorical] = pdf[categorical].astype('category')
</code>```

To use H2O with categoricals, you will have to convert strings to categoricals first:

```<code>h2odf[categoricals] = h2odf[categoricals].asfactor()
</code>```

Note too, that h2o has its own dataframes that are different from pandas.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run a Python notebook (link). At line below In [446]: where author train XGBoost, I am getting an error

ValueError: DataFrame.dtypes for data must be int, float or bool.
                  Did not expect the data types in fields StateHoliday, Assortment

# XGB with xgboost library
dtrain = xgb.DMatrix(X_train[predictors], y_train)
dtest = xgb.DMatrix(X_test[predictors], y_test)

watchlist = [(dtrain, 'train'), (dtest, 'test')]

xgb_model = xgb.train(params, dtrain, 300, evals = watchlist,
                      early_stopping_rounds = 50, feval = rmspe_xg, verbose_eval = True)

Here is the minimal code for testing

import pickle
import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split

with open('train_store', 'rb') as f:
    train_store = pickle.load(f)

train_store.shape

predictors = ['Store', 'DayOfWeek', 'Open', 'Promo', 'StateHoliday', 'SchoolHoliday', 'Year', 'Month', 'Day',
              'WeekOfYear', 'StoreType', 'Assortment', 'CompetitionDistance', 'CompetitionOpenSinceMonth',
              'CompetitionOpenSinceYear', 'Promo2', 'Promo2SinceWeek', 'Promo2SinceYear', 'CompetitionOpen',
              'PromoOpen']

y = np.log(train_store.Sales) # log transformation of Sales
X = train_store

# split the data into train/test set
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size = 0.3, # 30% for the evaluation set
                                                    random_state = 42)

# base parameters
params = {
    'booster': 'gbtree',
    'objective': 'reg:linear', # regression task
    'subsample': 0.8,          # 80% of data to grow trees and prevent overfitting
    'colsample_bytree': 0.85,  # 85% of features used
    'eta': 0.1,
    'max_depth': 10,
    'seed': 42} # for reproducible results

num_round = 60 # default 300

dtrain = xgb.DMatrix(X_train[predictors], y_train)
dtest  = xgb.DMatrix(X_test[predictors],  y_test)

watchlist = [(dtrain, 'train'), (dtest, 'test')]

xgb_model = xgb.train(params, dtrain, num_round, evals = watchlist,
                      early_stopping_rounds = 50, feval = rmspe_xg, verbose_eval = True)

Link to train_store data file: Link 1

Body:
The XGBoost version in the H2O package can handle categorical variables (but not too many!) but it appears that XGBoost as its own package can't.

I tried this with pandas dataframes but xgboost didn't like it

categoricals = ['StoreType', ] . # etc.
pdf[categorical] = pdf[categorical].astype('category')

To use H2O with categoricals, you will have to convert strings to categoricals first:

h2odf[categoricals] = h2odf[categoricals].asfactor()

Note too, that h2o has its own dataframes that are different from pandas.


问:
AWS CodeBuild buildspec.yml get all files and subfolders recursively
I'm trying to use AWS CodeBuild to get all files and subfolders inside a nested public folder and deploy to an S3 bucket using CodePipeline. I was able to hook them all together but struggling to configure the buildspec.yml file to get the output I want.

My folder structure:

```<code><path>/public/

├── 404.html
├── css
│   ├── ...
├── fonts
│   ├── bootstrap
│   │   ├── ...
│   ├── icomoon
│   │   ├── icomoon
│   │   │   ├── ...
│   └── simple-line-icons
│       ├── ...
├── images
│   ├── ...
├── index.html
├── index.xml
├── js
│   ├── ...
└── tags
    └── index.xml
</code>```

I need to put everything (including the subfolders) inside the public folder into the root of an S3 bucket.

So far I've tried following the docs here, here and here. I've tried using:

**/* to get everything recursively inside the folder public but the S3 bucket will have the path to the folder so the index.html is not in the root.

discard-paths: yes to remove the path to the public folder but inside the S3 bucket, all files are there in the root, no sub-folder structure is kept.

base-directory: as described here.

artifacts:
secondary-artifacts:
artifact1:
  files:
    - directory/file
artifact2:
  files:
    - directory/file2 to keep the folder structure but my build failed.

Different combinations of all the syntaxes above but my build just failed.

答:
TL;DR You probably don't need to use "discard-paths: yes". So, drop "discard-paths: yes" and instead use "base-directory" with "**/*" for glob pattern. Read on for more reasoning why.

So yeah, as it usually happens, the culprit was pretty trivial. In my case the directory structure looked like this:

```<code>dist/
|-- favicon.ico
|-- index.html
|-- js
|   `-- app.js
`-- revision.txt
</code>```

So in order for the artifact to contain everything from the "dist" directory whilst preserving the nested directories structure, the buildspec had to look like this:

```<code>artifacts:
  files:
    - '**/*'
  base-directory: 'dist'
</code>```

Essentially "base-directory" parameter behaves as unix's "cd" command, so at first CodeBuild jumps to that directory and only after that resolves the glob pattern, in this case - **/*. If you also happen to use "discard-paths" then what happens is that, presumably, CodeBuild will change current directory to "dist", resolve the files structure correctly but then remove all path prefixes from the resolved paths, thus the result will be a plain directory structure with no nesting.

Hope that helps!

Body:
I'm trying to use AWS CodeBuild to get all files and subfolders inside a nested public folder and deploy to an S3 bucket using CodePipeline. I was able to hook them all together but struggling to configure the buildspec.yml file to get the output I want.

My folder structure:

<path>/public/

├── 404.html
├── css
│   ├── ...
├── fonts
│   ├── bootstrap
│   │   ├── ...
│   ├── icomoon
│   │   ├── icomoon
│   │   │   ├── ...
│   └── simple-line-icons
│       ├── ...
├── images
│   ├── ...
├── index.html
├── index.xml
├── js
│   ├── ...
└── tags
    └── index.xml

I need to put everything (including the subfolders) inside the public folder into the root of an S3 bucket.

So far I've tried following the docs here, here and here. I've tried using:

**/* to get everything recursively inside the folder public but the S3 bucket will have the path to the folder so the index.html is not in the root.

discard-paths: yes to remove the path to the public folder but inside the S3 bucket, all files are there in the root, no sub-folder structure is kept.

base-directory: as described here.

artifacts:
secondary-artifacts:
artifact1:
  files:
    - directory/file
artifact2:
  files:
    - directory/file2 to keep the folder structure but my build failed.

Different combinations of all the syntaxes above but my build just failed.

Body:
TL;DR You probably don't need to use "discard-paths: yes". So, drop "discard-paths: yes" and instead use "base-directory" with "**/*" for glob pattern. Read on for more reasoning why.

So yeah, as it usually happens, the culprit was pretty trivial. In my case the directory structure looked like this:

dist/
|-- favicon.ico
|-- index.html
|-- js
|   `-- app.js
`-- revision.txt

So in order for the artifact to contain everything from the "dist" directory whilst preserving the nested directories structure, the buildspec had to look like this:

artifacts:
  files:
    - '**/*'
  base-directory: 'dist'

Essentially "base-directory" parameter behaves as unix's "cd" command, so at first CodeBuild jumps to that directory and only after that resolves the glob pattern, in this case - **/*. If you also happen to use "discard-paths" then what happens is that, presumably, CodeBuild will change current directory to "dist", resolve the files structure correctly but then remove all path prefixes from the resolved paths, thus the result will be a plain directory structure with no nesting.

Hope that helps!


问:
Changing tab from external form
I have a TabControl in Form A. I am trying to change that tab from Form B through a button.

I am using this code:

```<code>Dashboard.TabSystem.SelectedTab = tab_Dashboard
</code>```

And Visual Studio is giving me the following error:

```<code>'tab_Dashboard' is not declared. It may be inaccessible due to its protection level.
</code>```

Maybe I am being stupid but I can't get it to see the tab page?

答:
If it's not declared then it's not a designer field. Is that just the name of the tab? Try getting the tab object from the Dashboard.TabSystem:

```<code>Dim tab As TabPage = Dashboard.TabSystem.TabPages("tab_Dashboard")
</code>```

And then set the selected tab:

```<code>Dashboard.TabSystem.SelectedTab = tab
</code>```

Title: Changing tab from external form

Body:
I have a TabControl in Form A. I am trying to change that tab from Form B through a button.

I am using this code:

Dashboard.TabSystem.SelectedTab = tab_Dashboard

And Visual Studio is giving me the following error:

'tab_Dashboard' is not declared. It may be inaccessible due to its protection level.

Maybe I am being stupid but I can't get it to see the tab page?

Body:
If it's not declared then it's not a designer field. Is that just the name of the tab? Try getting the tab object from the Dashboard.TabSystem:

Dim tab As TabPage = Dashboard.TabSystem.TabPages("tab_Dashboard")

And then set the selected tab:

Dashboard.TabSystem.SelectedTab = tab


问:
Sklearn using natural language processing with numerical data
I'm using sklearn for a project and I have two columns to use to predict. One column is text, which is a series of articles, and the other is equal_cnts, which is a real number. I am trying to create a model that trains on both the text and the numbers using SVM, but I'm having trouble figuring out how to use both features.

```<code>vect = CountVectorizer(ngram_range=(1, 2))
tfidf = TfidfTransformer()
svm = svm.SVC(kernel='linear', C = 100, gamma = 0.1)

text_clf = Pipeline([('vect', vect), ('tfidf', tfidf), ('svm', svm)])
scores = cross_val_score(text_clf, pd.concat([df['text'], df['equal_cnt']], axis = 1), df['empirical'], cv=10)
</code>```

I'm currently trying to do the above, where the Pipeline is intended to process the text and the model is being testing for accuracy against df["empirical"].

答:
I think the modern and slick way of doing this with scikit-learn would use the ColumnTransformer and would look like this:

```<code>from sklearn.pipeline import make_pipeline
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC

X = df.drop("empirical", axis=1)
y = df["empirical"]

preprocessor = ColumnTransformer(
    # We apply a TF-IDF vectorizer to the "text" column
    [("text", TfidfVectorizer(max_features=10), "text"),],
    # the "passthrough" value for the "remainder" parameter lets 'equal_cnt' pass
    # through the first stage of the pipeline without modifying this column
    remainder="passthrough"
)
classifier = SVC(kernel='linear', C=1., gamma='scale')

pipeline = make_pipeline(preprocessor, classifier)

scores = cross_val_score(pipeline, X, y, cv=10)
</code>```

And you can adjust the TF-IDF and SVM hyper-parameters as needed of course.

Body:
I'm using sklearn for a project and I have two columns to use to predict. One column is text, which is a series of articles, and the other is equal_cnts, which is a real number. I am trying to create a model that trains on both the text and the numbers using SVM, but I'm having trouble figuring out how to use both features.

vect = CountVectorizer(ngram_range=(1, 2))
tfidf = TfidfTransformer()
svm = svm.SVC(kernel='linear', C = 100, gamma = 0.1)

text_clf = Pipeline([('vect', vect), ('tfidf', tfidf), ('svm', svm)])
scores = cross_val_score(text_clf, pd.concat([df['text'], df['equal_cnt']], axis = 1), df['empirical'], cv=10)

I'm currently trying to do the above, where the Pipeline is intended to process the text and the model is being testing for accuracy against df["empirical"].

Body:
I think the modern and slick way of doing this with scikit-learn would use the ColumnTransformer and would look like this:

from sklearn.pipeline import make_pipeline
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC

X = df.drop("empirical", axis=1)
y = df["empirical"]

preprocessor = ColumnTransformer(
    # We apply a TF-IDF vectorizer to the "text" column
    [("text", TfidfVectorizer(max_features=10), "text"),],
    # the "passthrough" value for the "remainder" parameter lets 'equal_cnt' pass
    # through the first stage of the pipeline without modifying this column
    remainder="passthrough"
)
classifier = SVC(kernel='linear', C=1., gamma='scale')

pipeline = make_pipeline(preprocessor, classifier)

scores = cross_val_score(pipeline, X, y, cv=10)

And you can adjust the TF-IDF and SVM hyper-parameters as needed of course.


问:
itemize environment giving this error for unclear reason: Something's wrong, perhaps a missing \item( its happening on line 11)
I am using itemize, not missing an \item (to my knowledge) and there isn't any extra text without an item that I know of. I'm pretty sure I'm using itemize correctly because I've used it in the same way for other 'LaTeX' files before with no issue. I'm really confused.

Also, when I removed the code that had the error, it told me that another section of code that was fine before now had the same error.

```<code>\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[dvipsnames]{xcolor}
\begin{document}
\begin{itemize}
    \item recombinant
    \item Deoxyribose vs Ribose: Only one difference
    \item Nitrogen Bases in DNA
    \begin{itemize}
        \begin{itemize}
            \item Purines, 2 rings
            \begin{itemize}
                \item Adenine
                \item Guanine
           \end{itemize}{}
        \end{itemize}{}
        \begin{itemize}
            \item Pyrimidines, 1 ring
            \begin{itemize}
                \item T
                \item C
            \end{itemize}{}
        \end{itemize}{}
    \end{itemize}{}
    \item[Nitrogen bases = Steps of ladder]
    \begin{itemize}
        \item phosphate group
        \item deoxyribose sugar(connected to nitrogen base)
    \end{itemize}{}
\end{itemize}{}
\end{document}{}
</code>```

答:
You are missing an \item. In your second level itemization, you immediately try to start a third level itemization without having an item before.

```<code>\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[dvipsnames]{xcolor}
\begin{document}
\begin{itemize}
    \item recombinant
    \item Deoxyribose vs Ribose: Only one difference
    \item Nitrogen Bases in DNA
    \begin{itemize}
       \item \begin{itemize}
            \item Purines, 2 rings
            \begin{itemize}
                \item Adenine
                \item Guanine
           \end{itemize}
        \end{itemize}
        \begin{itemize}
            \item Pyrimidines, 1 ring
            \begin{itemize}
                \item T
                \item C
            \end{itemize}
        \end{itemize}
    \end{itemize}
    \item[Nitrogen bases = Steps of ladder]
    \begin{itemize}
        \item phosphate group
        \item deoxyribose sugar(connected to nitrogen base)
    \end{itemize}
\end{itemize}
\end{document}
</code>```

Body:
I am using itemize, not missing an \item (to my knowledge) and there isn't any extra text without an item that I know of. I'm pretty sure I'm using itemize correctly because I've used it in the same way for other 'LaTeX' files before with no issue. I'm really confused.

Also, when I removed the code that had the error, it told me that another section of code that was fine before now had the same error.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[dvipsnames]{xcolor}
\begin{document}
\begin{itemize}
    \item recombinant
    \item Deoxyribose vs Ribose: Only one difference
    \item Nitrogen Bases in DNA
    \begin{itemize}
        \begin{itemize}
            \item Purines, 2 rings
            \begin{itemize}
                \item Adenine
                \item Guanine
           \end{itemize}{}
        \end{itemize}{}
        \begin{itemize}
            \item Pyrimidines, 1 ring
            \begin{itemize}
                \item T
                \item C
            \end{itemize}{}
        \end{itemize}{}
    \end{itemize}{}
    \item[Nitrogen bases = Steps of ladder]
    \begin{itemize}
        \item phosphate group
        \item deoxyribose sugar(connected to nitrogen base)
    \end{itemize}{}
\end{itemize}{}
\end{document}{}

Body:
You are missing an \item. In your second level itemization, you immediately try to start a third level itemization without having an item before.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[dvipsnames]{xcolor}
\begin{document}
\begin{itemize}
    \item recombinant
    \item Deoxyribose vs Ribose: Only one difference
    \item Nitrogen Bases in DNA
    \begin{itemize}
       \item \begin{itemize}
            \item Purines, 2 rings
            \begin{itemize}
                \item Adenine
                \item Guanine
           \end{itemize}
        \end{itemize}
        \begin{itemize}
            \item Pyrimidines, 1 ring
            \begin{itemize}
                \item T
                \item C
            \end{itemize}
        \end{itemize}
    \end{itemize}
    \item[Nitrogen bases = Steps of ladder]
    \begin{itemize}
        \item phosphate group
        \item deoxyribose sugar(connected to nitrogen base)
    \end{itemize}
\end{itemize}
\end{document}


问:
C# Trying to get XML inner text for nested node
I can succesfully load the XMl document and traverse the nodes. Once I get the node that I want, I start setting values. How do I deal with nested nodes?

Here is the xml:

```<code><incident>
<id>1234</id>
<number>5678</number>
<name>This is a name</name>
<state>Awaiting Input</state>
<priority>Medium</priority>
<category>
    <id>99999</id>
    <name>Applications</name>
    <default_tags>applications</default_tags>
    <parent_id nil="true" />
    <default_assignee_id nil="true" />
</category>
</code>```

Here is some C#:

```<code>   id = node.SelectSingleNode("id").InnerText;  //works fine
   number = node.SelectSingleNode("number").InnerText;  //works fine

   name = node.SelectSingleNode("name").InnerText;  //works fine
   descHTML = node.SelectSingleNode("description").InnerText;  //works fine
   desc = node.SelectSingleNode("description_no_html").InnerText;  //works fine
   state = node.SelectSingleNode("state").InnerText;  //works fine
   priority = node.SelectSingleNode("priority").InnerText;  //works fine

   catagoryID = node.SelectSingleNode("category/id").InnerText; // null reference error
   catagoryName = node.SelectSingleNode("category/name").InnerText; // null reference error
   catagoryTags = node.SelectSingleNode("category/default_tags").InnerText; // null reference error
</code>```

答:
I suppose you use the XmlDocument class and CATEGORY NODE is the only item that will have childnodes, so I have this method to go through each element, including subnodes <em>(I hope this helps someone).</em> </p>

```<code>string xml =
@"<incident>
    <id>1234</id>
    <number>5678</number>
    <name>This is a name</name>
    <state>Awaiting Input</state>
    <priority>Medium</priority>
    <category>
        <id>99999</id>
        <name>Applications</name>
        <default_tags>applications</default_tags>
        <parent_id nil=""true"" />
        <default_assignee_id nil=""true"" />
    </category>
</incident>";

List<String> innerTextNode = new List<string>();
XmlDocument XmlDoc= new XmlDocument();
XmlDoc.LoadXml(xml);

XmlElement root = XmlDoc.DocumentElement;
XmlNodeList nodes = root.ChildNodes;
XmlNodeList childs;

foreach (XmlNode anode in nodes)
{
    // The next is for any NODE that will have childnodes
    // bool havechilds = anode.ChildNodes.OfType<XmlNode>().Any(x => x.NodeType != XmlNodeType.Text)

    if (!anode.LocalName.Equals("category", StringComparison.CurrentCulture))
    {
        // The node is only text, no has childnodes
        // So capturing InnerText
        innerTextNode.Add(anode.InnerText);
    }
    else
    {
        childs = nodo.ChildNodes;
        foreach (XmlNode childone in childs)
        {
            // So capturing InnerText
            innerTextNode.Add(childone.InnerText);
        }
    }
}
</code>```

Body:
I can succesfully load the XMl document and traverse the nodes. Once I get the node that I want, I start setting values. How do I deal with nested nodes?

Here is the xml:

<incident>
<id>1234</id>
<number>5678</number>
<name>This is a name</name>
<state>Awaiting Input</state>
<priority>Medium</priority>
<category>
    <id>99999</id>
    <name>Applications</name>
    <default_tags>applications</default_tags>
    <parent_id nil="true" />
    <default_assignee_id nil="true" />
</category>

Here is some C#:

   id = node.SelectSingleNode("id").InnerText;  //works fine
   number = node.SelectSingleNode("number").InnerText;  //works fine

   name = node.SelectSingleNode("name").InnerText;  //works fine
   descHTML = node.SelectSingleNode("description").InnerText;  //works fine
   desc = node.SelectSingleNode("description_no_html").InnerText;  //works fine
   state = node.SelectSingleNode("state").InnerText;  //works fine
   priority = node.SelectSingleNode("priority").InnerText;  //works fine

   catagoryID = node.SelectSingleNode("category/id").InnerText; // null reference error
   catagoryName = node.SelectSingleNode("category/name").InnerText; // null reference error
   catagoryTags = node.SelectSingleNode("category/default_tags").InnerText; // null reference error

Body:
I suppose you use the XmlDocument class and CATEGORY NODE is the only item that will have childnodes, so I have this method to go through each element, including subnodes (I hope this helps someone).

string xml =
@"<incident>
    <id>1234</id>
    <number>5678</number>
    <name>This is a name</name>
    <state>Awaiting Input</state>
    <priority>Medium</priority>
    <category>
        <id>99999</id>
        <name>Applications</name>
        <default_tags>applications</default_tags>
        <parent_id nil=""true"" />
        <default_assignee_id nil=""true"" />
    </category>
</incident>";

List<String> innerTextNode = new List<string>();
XmlDocument XmlDoc= new XmlDocument();
XmlDoc.LoadXml(xml);

XmlElement root = XmlDoc.DocumentElement;
XmlNodeList nodes = root.ChildNodes;
XmlNodeList childs;

foreach (XmlNode anode in nodes)
{
    // The next is for any NODE that will have childnodes
    // bool havechilds = anode.ChildNodes.OfType<XmlNode>().Any(x => x.NodeType != XmlNodeType.Text)

    if (!anode.LocalName.Equals("category", StringComparison.CurrentCulture))
    {
        // The node is only text, no has childnodes
        // So capturing InnerText
        innerTextNode.Add(anode.InnerText);
    }
    else
    {
        childs = nodo.ChildNodes;
        foreach (XmlNode childone in childs)
        {
            // So capturing InnerText
            innerTextNode.Add(childone.InnerText);
        }
    }
}


问:
It´s possible to do Database driven tests using data tables using Karate?
When writing my API tests with Cucumber I have implemented some step definitions that allow specifying the data that needs to exist in the database for each scenario.

Something like this:

```<code>Given I have database table "users" with data:
 | id | name   |
 | 1  | User 1 |
</code>```

This will do an insert in the specified table.

Is it possible to do something like this with Karate?

Thank you.

答:
Yes it is, you will need a insertRows method in your DBUTIL file which i borrowed from @peter

you can then call the methods and pass the variable from the table

```<code>Background:
* def config = {username: 'XXXX', password: 'XXXXX', url: 'jdbc:oracle:thin:@XXXXX.net:6236/XXXX_XXXXX', driverClassName: 'oracle.jdbc.driver.OracleDriver'}
* def DbUtil = Java.type('util.DbUtils')
* def db = new DbUtil(config)
</code>```

def Value = db.insertrows(INSERT INTO sales.promotions (promotion_name,discount,    start_date,expired_date)VALUES(<name>);)*

below is the example of DB file, you will need to add dependencies with maven or gradle

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>
<dependency>
    <groupId>com.oracle.jdbc</groupId>
    <artifactId>ojdbc6_g</artifactId>
    <version>12.1.0.2</version>
</dependency>

package util;

import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class DbUtils {

    private static final Logger logger = LoggerFactory.getLogger(DbUtils.class);

    private final JdbcTemplate jdbc;

    public DbUtils(Map<String, Object> config) {
        String url = (String) config.get("url");
        String username = (String) config.get("username");
        String password = (String) config.get("password");
        String driver = (String) config.get("driverClassName");
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        jdbc = new JdbcTemplate(dataSource);
        logger.info("init jdbc template: {}", url);
    }

    public Object readValue(String query) {
        return jdbc.queryForObject(query, Object.class);
    }

    public Map<String, Object> readRow(String query) {
        return jdbc.queryForMap(query);
    }

    public List<Map<String, Object>> readRows(String query) {
        return jdbc.queryForList(query);
    }

    public void insertRows(final String sql){
        jdbc.batchUpdate(new String[]{sql});
        }

}
</code>```

Body:
When writing my API tests with Cucumber I have implemented some step definitions that allow specifying the data that needs to exist in the database for each scenario.

Something like this:

Given I have database table "users" with data:
 | id | name   |
 | 1  | User 1 |

This will do an insert in the specified table.

Is it possible to do something like this with Karate?

Thank you.

Body:
Yes it is, you will need a insertRows method in your DBUTIL file which i borrowed from @peter

you can then call the methods and pass the variable from the table

Background:
* def config = {username: 'XXXX', password: 'XXXXX', url: 'jdbc:oracle:thin:@XXXXX.net:6236/XXXX_XXXXX', driverClassName: 'oracle.jdbc.driver.OracleDriver'}
* def DbUtil = Java.type('util.DbUtils')
* def db = new DbUtil(config)

def Value = db.insertrows(INSERT INTO sales.promotions (promotion_name,discount,    start_date,expired_date)VALUES(<name>);)*

below is the example of DB file, you will need to add dependencies with maven or gradle

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>
<dependency>
    <groupId>com.oracle.jdbc</groupId>
    <artifactId>ojdbc6_g</artifactId>
    <version>12.1.0.2</version>
</dependency>

package util;

import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class DbUtils {

    private static final Logger logger = LoggerFactory.getLogger(DbUtils.class);

    private final JdbcTemplate jdbc;

    public DbUtils(Map<String, Object> config) {
        String url = (String) config.get("url");
        String username = (String) config.get("username");
        String password = (String) config.get("password");
        String driver = (String) config.get("driverClassName");
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        jdbc = new JdbcTemplate(dataSource);
        logger.info("init jdbc template: {}", url);
    }

    public Object readValue(String query) {
        return jdbc.queryForObject(query, Object.class);
    }

    public Map<String, Object> readRow(String query) {
        return jdbc.queryForMap(query);
    }

    public List<Map<String, Object>> readRows(String query) {
        return jdbc.queryForList(query);
    }

    public void insertRows(final String sql){
        jdbc.batchUpdate(new String[]{sql});
        }

}


问:
horizontally displayed JSON data react card
I am new to react ,I am fetching some json data and I would like to displayed them horizontally in bootstrap card,Whenever I tried ,it keeps displayed vertically .here is my code.

```<code><div className="row"  >
<div className="col-md-4" >
<div className="card" >
             <img className="card-img-top" src={user.picture.large? ( user.picture.large) : ("http://appalachiantrail.org/images/default-source/default-album/trailfocus.jpg?sfvrsn=2")} />
               <div className="card-body" >
                 <h1 className="card-title">{user.name.first}</h1>
                   <h2 className="card-text">{user.id.value} </h2>
                     <h4 className="card-text">{user.email} </h4>
                     </div>
<br>
                     </br>

   </div>
</div>
</code>```

this is what I want to achieve

See  code here of what I want to achieve,how do I replace those static column with my dynamic json response data ? Please advise

thanks

答:
You should be putting them inside a container with display:flex styling

```<code><style>
.container{
   display:flex;
}
</style>
<div class="container">
  <div className="card-body" >
     <h1 className="card-title">{user.name.first}</h1>
     <h2 className="card-text">{user.id.value} </h2>
     <h4 className="card-text">{user.email} </h4>
  </div>
  <div className="card-body" >
     <h1 className="card-title">{user.name.first}</h1>
     <h2 className="card-text">{user.id.value} </h2>
     <h4 className="card-text">{user.email} </h4>
  </div>
  <div className="card-body" >
     <h1 className="card-title">{user.name.first}</h1>
     <h2 className="card-text">{user.id.value} </h2>
     <h4 className="card-text">{user.email} </h4>
  </div>
</div>

</code>```

Body:
I am new to react ,I am fetching some json data and I would like to displayed them horizontally in bootstrap card,Whenever I tried ,it keeps displayed vertically .here is my code.

{user.name.first}

{user.id.value}

{user.email}

this is what I want to achieve

See  code here of what I want to achieve,how do I replace those static column with my dynamic json response data ? Please advise

thanks

Body:
You should be putting them inside a container with display:flex styling

<style>
.container{
   display:flex;
}
</style>
<div class="container">
  <div className="card-body" >
     <h1 className="card-title">{user.name.first}</h1>
     <h2 className="card-text">{user.id.value} </h2>
     <h4 className="card-text">{user.email} </h4>
  </div>
  <div className="card-body" >
     <h1 className="card-title">{user.name.first}</h1>
     <h2 className="card-text">{user.id.value} </h2>
     <h4 className="card-text">{user.email} </h4>
  </div>
  <div className="card-body" >
     <h1 className="card-title">{user.name.first}</h1>
     <h2 className="card-text">{user.id.value} </h2>
     <h4 className="card-text">{user.email} </h4>
  </div>
</div>


问:
How do I test XML equality in Ruby?
Clearly I need to (a) convert both strings to canonical XML or (b) compare their parse-trees.  The following doesn't work because the document object returned doesn't have a sensible == defined.

```<code>Nokogiri.XML(doc_a) == Nokogiri.XML(doc_b)
</code>```

Nor does the following, because Nokogiri's to_xml leaves some internal whitespace:

```<code>Nokogiri.XML(doc_a).to_xml == Nokogiri.XML(doc_b).to_xml
</code>```

This is a reasonable approximation of equality (and will work for most cases), but it's not quite right:

```<code>Nokogiri.XML(doc_a).to_xml.squeeze(' ') == Nokogiri.XML(doc_b).to_xml.squeeze(' ')
</code>```

I'm already using Nokogiri, so I'd prefer to stick with it, but I'll use whatever library works.

答: If you are looking for structural equality and don't care about the order of tags and attributes, probably the xml-simple library is a good choice. It converts the xml into ruby's data structures (hashes and lists) which can be safely compared with the == operator.

ContentLicense: CC BY-SA 2.5

Title: How do I test XML equality in Ruby?

Body:
Clearly I need to (a) convert both strings to canonical XML or (b) compare their parse-trees.  The following doesn't work because the document object returned doesn't have a sensible == defined.

Nokogiri.XML(doc_a) == Nokogiri.XML(doc_b)

Nor does the following, because Nokogiri's to_xml leaves some internal whitespace:

Nokogiri.XML(doc_a).to_xml == Nokogiri.XML(doc_b).to_xml

This is a reasonable approximation of equality (and will work for most cases), but it's not quite right:

Nokogiri.XML(doc_a).to_xml.squeeze(' ') == Nokogiri.XML(doc_b).to_xml.squeeze(' ')

I'm already using Nokogiri, so I'd prefer to stick with it, but I'll use whatever library works.

ContentLicense: CC BY-SA 3.0


问:
How do I integrate neo4j driver in node.js
I want to use neo4j graph database with Node.

But I am getting error . Please help.

Error says neo4j is not defined.
But i have already installed the driver using npm

Here is my code :

```<code>var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');

var app = require('neo4j-driver').v1;   // neo4J driver

var app = express();

app.set('views',path.join(__dirname,'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname,'public')));

// var driver =  neo4j.v1.driver('bolt://localhost:7687', neo4j.v1.auth.basic('neo4j','test'));  // neo4j driver
// var session = driver.session();

const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('neo4j', 'test'));

app.get('/',function(req,res) {
        res.send('it Works');
});
app.listen(3000);
console.log('Server Started on port 3000');

module.exports = app;
</code>```

I am getting following error :

```<code>PS D:\Projects\neo4J_node> node .\app.js
D:\Projects\neo4J_node\app.js:23
const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('neo4j', 'test'));
               ^

ReferenceError: neo4j is not defined
    at Object.<anonymous> (D:\Projects\neo4J_node\app.js:23:16)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
PS D:\Projects\neo4J_node>
</code>```

答:
The drivers has been updated and the one you are using is no longer valid. Make the changes below and test it with session adding the test node to the neo4j.
Change:

var app = require('neo4j-driver').v1;   // neo4J driver
```

<p>to:</p>

<pre class="lang-js prettyprint-override"><code>var neo4j = require('neo4j-driver')
</code>```

to test the connection try this code:

const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('neo4j', 'test'));

const session = driver.session()

const resultPromise = session.writeTransaction(tx =>
  tx.run(
    'CREATE (a:Greeting) SET a.message = $message RETURN a.message + ", from node " + id(a)',
    { message: 'hello, world' }
  )
)

resultPromise.then(result => {
  session.close()

  const singleRecord = result.records[0]
  const greeting = singleRecord.get(0)

  console.log(greeting)

  // on application exit:
  driver.close()
})
```

Body:
I want to use neo4j graph database with Node.

But I am getting error . Please help.

Error says neo4j is not defined.
But i have already installed the driver using npm

Here is my code :

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');

var app = require('neo4j-driver').v1;   // neo4J driver

var app = express();

app.set('views',path.join(__dirname,'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname,'public')));

// var driver =  neo4j.v1.driver('bolt://localhost:7687', neo4j.v1.auth.basic('neo4j','test'));  // neo4j driver
// var session = driver.session();

const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('neo4j', 'test'));

app.get('/',function(req,res) {
        res.send('it Works');
});
app.listen(3000);
console.log('Server Started on port 3000');

module.exports = app;

I am getting following error :

PS D:\Projects\neo4J_node> node .\app.js
D:\Projects\neo4J_node\app.js:23
const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('neo4j', 'test'));
               ^

ReferenceError: neo4j is not defined
    at Object.<anonymous> (D:\Projects\neo4J_node\app.js:23:16)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
PS D:\Projects\neo4J_node>

Body:
The drivers has been updated and the one you are using is no longer valid. Make the changes below and test it with session adding the test node to the neo4j.
Change:

var app = require('neo4j-driver').v1;   // neo4J driver

to:

var neo4j = require('neo4j-driver')

to test the connection try this code:

const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('neo4j', 'test'));

const session = driver.session()

const resultPromise = session.writeTransaction(tx =>
  tx.run(
    'CREATE (a:Greeting) SET a.message = $message RETURN a.message + ", from node " + id(a)',
    { message: 'hello, world' }
  )
)

resultPromise.then(result => {
  session.close()

  const singleRecord = result.records[0]
  const greeting = singleRecord.get(0)

  console.log(greeting)

  // on application exit:
  driver.close()
})


问:
Converting a matrix into a data frame in a long format (R)
I have a matrix in this format:

```<code>Example_matrix<- structure(list(X1 = c("Species 1", "Species 2", "Species 3",
"Species 4", "Species 5", "Species 6", "Species 7", "Species 8"
), `Site 1` = c(0, 0, 0, 2, 2, 0, 0, 5), `Site 2` = c(0, 0, 0,
4, 0, 0, 0, 0), `Site 3` = c(0, 1, 0, 0, 0, 1, 0, 0), `Site 4` = c(0,
0, 0, 0, 0, 1, 0, 0)), class = c("spec_tbl_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -8L), spec = structure(list(
    cols = list(X1 = structure(list(), class = c("collector_character",
    "collector")), `Site 1` = structure(list(), class = c("collector_double",
    "collector")), `Site 2` = structure(list(), class = c("collector_double",
    "collector")), `Site 3` = structure(list(), class = c("collector_double",
    "collector")), `Site 4` = structure(list(), class = c("collector_double",
    "collector"))), default = structure(list(), class = c("collector_guess",
    "collector")), skip = 1), class = "col_spec"))
</code>```

(This is a simplified version of it)

Is there way of quickly converting a matrix like that into a long format df? I had a look at some of the similar questions but the options didn't work for me. All I'm wanting to do is to end up with a df that will have 3 columns: Site, Species and the Abundance (which is currently the value within each cell in the matrix).

Thanks!

答:
We could use pivot_longer from tidyr

```<code>library(dplyr)
library(tidyr)
newdat <- Example_matrix %>%
    pivot_longer(cols = starts_with('Site'),
          names_to = 'Site', values_to = 'Abundance')

newdat
# A tibble: 32 x 3
#   X1        Site   Abundance
#   <chr>     <chr>      <dbl>
# 1 Species 1 Site 1         0
# 2 Species 1 Site 2         0
# 3 Species 1 Site 3         0
# 4 Species 1 Site 4         0
# 5 Species 2 Site 1         0
# 6 Species 2 Site 2         0
# 7 Species 2 Site 3         1
# 8 Species 2 Site 4         0
# 9 Species 3 Site 1         0
#10 Species 3 Site 2         0
# … with 22 more rows
</code>```

In base R, we can do

```<code>as.data.frame.table(`row.names<-`(as.matrix(Example_matrix)[,-1],
       Example_matrix$X1))
</code>```

Body:
I have a matrix in this format:

Example_matrix<- structure(list(X1 = c("Species 1", "Species 2", "Species 3",
"Species 4", "Species 5", "Species 6", "Species 7", "Species 8"
), `Site 1` = c(0, 0, 0, 2, 2, 0, 0, 5), `Site 2` = c(0, 0, 0,
4, 0, 0, 0, 0), `Site 3` = c(0, 1, 0, 0, 0, 1, 0, 0), `Site 4` = c(0,
0, 0, 0, 0, 1, 0, 0)), class = c("spec_tbl_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -8L), spec = structure(list(
    cols = list(X1 = structure(list(), class = c("collector_character",
    "collector")), `Site 1` = structure(list(), class = c("collector_double",
    "collector")), `Site 2` = structure(list(), class = c("collector_double",
    "collector")), `Site 3` = structure(list(), class = c("collector_double",
    "collector")), `Site 4` = structure(list(), class = c("collector_double",
    "collector"))), default = structure(list(), class = c("collector_guess",
    "collector")), skip = 1), class = "col_spec"))

(This is a simplified version of it)

Is there way of quickly converting a matrix like that into a long format df? I had a look at some of the similar questions but the options didn't work for me. All I'm wanting to do is to end up with a df that will have 3 columns: Site, Species and the Abundance (which is currently the value within each cell in the matrix).

Thanks!

Body:
We could use pivot_longer from tidyr

library(dplyr)
library(tidyr)
newdat <- Example_matrix %>%
    pivot_longer(cols = starts_with('Site'),
          names_to = 'Site', values_to = 'Abundance')

newdat
# A tibble: 32 x 3
#   X1        Site   Abundance
#   <chr>     <chr>      <dbl>
# 1 Species 1 Site 1         0
# 2 Species 1 Site 2         0
# 3 Species 1 Site 3         0
# 4 Species 1 Site 4         0
# 5 Species 2 Site 1         0
# 6 Species 2 Site 2         0
# 7 Species 2 Site 3         1
# 8 Species 2 Site 4         0
# 9 Species 3 Site 1         0
#10 Species 3 Site 2         0
# … with 22 more rows

In base R, we can do

as.data.frame.table(`row.names<-`(as.matrix(Example_matrix)[,-1],
       Example_matrix$X1))


问:
find an element under a

  "some text"

 tag as shown in figure
This is the HTMl code, I want to get "1" and so on all values written in nested
  tags

<img src="https://i.stack.imgur.com/XYJTu.png" alt="This is the HTMl code, I want to get "1" and so on all values written in nested
  tags">

I have tried

```<code>total = driver.find_element_by_xpath("//a[text()='...']/following-sibling::a").text
</code>```

and

```<code>totl = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, "//div[@class='ng-binding']")))
print (totl.text)
</code>```

but nothing works. It will be a great favor if you let me out of it.

答:
To be able to get text WebElement should be visible, that's why wait for visibility of all elements. Code examples to get all a elements (total is be a list of WebElements):

```<code>total = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'ul[uib-pagination] li a')))

# or

total = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'li.pagination-page a')))
</code>```

To get text from total:

```<code># texts of all links in total
total_texts = [element.text from element in total]
print(total_texts)

# text of the first one
first_page_number = total[0].text

# text of the last one
last_page_number = total[-1].text
</code>```

Title: find an element under a <ul> <li> <a> "some text" </a> </li> </ul> tag as shown in figure

Body:
This is the HTMl code, I want to get "1" and so on all values written in nested
  tags

<img src="https://i.stack.imgur.com/XYJTu.png" alt="This is the HTMl code, I want to get "1" and so on all values written in nested
  tags">

I have tried

total = driver.find_element_by_xpath("//a[text()='...']/following-sibling::a").text

and

totl = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, "//div[@class='ng-binding']")))
print (totl.text)

but nothing works. It will be a great favor if you let me out of it.

Body:
To be able to get text WebElement should be visible, that's why wait for visibility of all elements. Code examples to get all a elements (total is be a list of WebElements):

total = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'ul[uib-pagination] li a')))

# or

total = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'li.pagination-page a')))

To get text from total:

# texts of all links in total
total_texts = [element.text from element in total]
print(total_texts)

# text of the first one
first_page_number = total[0].text

# text of the last one
last_page_number = total[-1].text


问:
How to specify non linear regression model in python
I am taking an Econometrics course, and have been trying to use Python rather than the propreitry STATA and EVIEWS they set the assignments in.

In one of the questions, I have consumption data over time. I am asked to compute it in two ways.

The first way is calculating a model of the form consumption = Aexp(Bt), and the second way is to log both sides and do ordinary OLS on log(consumption) = alpha + Bt

I know how to do the second way. Howver, when I try to do the first way it goes wrong. Using statsmodels, I can exponentiate the time data (after normalising), but this calculates a regression in the form consumption = Aexp(t) + B, which is not what I want. (I want to specify where the parameters go). In sklearn I could find a polynomial regression, but not exponential.

Then I found scipy.curve_fit
However this seems to have two problems:
(1) It seems to rely on initial guesses for parameters, which means my output will end up being different from proprietry software (whereas output for things like OLS are the same) [as I assume initial guesses means some iterative solution is done which is helpful for very weird and wonderful functions, but I assume fairly standard results hold for exponential regression]
(2) every time I try to implement it, it just returns the guess parameters.

Here is my code

```<code>`consumption_data = pd.read_csv(......\consumption.csv")
def func(x,a,b):
    return a * np.exp(b*x)

xdata = consumption_data.YEAR
ydata = consumption_data.CONSUMPTION
ydata = (ydata - 1948)/100

popt, pcov = curve_fit(func, xdata, ydata, (1,1))
print(popt)

plt.plot(xdata, func(xdata, *popt), 'g--',)
`
</code>```

The scipy.optimize code is basically just copy-pasted from their tutorial
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

答:
short answer: use statsmodels GLM

statsmodels does not have nonlinear least squares. The best python library for that is lmfit https://pypi.org/project/lmfit/

curve_fit, lmfit and nonlinear least squares algorithm in general find an iterative solution to the optimization problem. Even when we have to provide starting values, the solution is in many cases the same across packages up to convergence tolerance, e.g. 1e-5 or 1e-6.
Many standard models in statistics and econometrics have a single global maximum with well behaved data. However, in other cases like mixture models, there might be many local optima and the estimation might converge to one of them.

To the specific case:

consumption = A exp(B t)

can be rewritten as

consumption = exp(a + B t)

So this is just a single index model or a generalized linear model with an exponential mean function.

The general version has the expectation of the dependent variable as a nonlinear function of a linear combination of the explanatory variables:

E(y | x) = g(x b)

This can be estimated with statsmodels with GLM with family Gaussian and the log-link.

Aside: In econometrics, there is a literature to use Poisson quasi-likelihood as an estimator for exp models instead of taking the log of the dependent variable.
Poisson usually uses the log-link function as in the above.

However, using GLM allows us to use log-link, i.e. exponential mean function, with any of the supported distribution families. The main difference is in the underlying variance assumption. Gaussian assumes constant variance, Poisson assumes that the variance is proportional to the mean and Gamma assumes that the variance is quadratic in the mean.

If we use a robust sandwich covariance estimator for parameter inference, then standard errors and inference are correct even if the variance function is misspecified.

Body:
I am taking an Econometrics course, and have been trying to use Python rather than the propreitry STATA and EVIEWS they set the assignments in.

In one of the questions, I have consumption data over time. I am asked to compute it in two ways.

The first way is calculating a model of the form consumption = Aexp(Bt), and the second way is to log both sides and do ordinary OLS on log(consumption) = alpha + Bt

I know how to do the second way. Howver, when I try to do the first way it goes wrong. Using statsmodels, I can exponentiate the time data (after normalising), but this calculates a regression in the form consumption = Aexp(t) + B, which is not what I want. (I want to specify where the parameters go). In sklearn I could find a polynomial regression, but not exponential.

Then I found scipy.curve_fit
However this seems to have two problems:
(1) It seems to rely on initial guesses for parameters, which means my output will end up being different from proprietry software (whereas output for things like OLS are the same) [as I assume initial guesses means some iterative solution is done which is helpful for very weird and wonderful functions, but I assume fairly standard results hold for exponential regression]
(2) every time I try to implement it, it just returns the guess parameters.

Here is my code

`consumption_data = pd.read_csv(......\consumption.csv")
def func(x,a,b):
    return a * np.exp(b*x)

xdata = consumption_data.YEAR
ydata = consumption_data.CONSUMPTION
ydata = (ydata - 1948)/100

popt, pcov = curve_fit(func, xdata, ydata, (1,1))
print(popt)

plt.plot(xdata, func(xdata, *popt), 'g--',)
`

The scipy.optimize code is basically just copy-pasted from their tutorial
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html


问:
How can I stop my animation from running when stoprun = 1?
I have tried th1.join but that didn't work and I don't know what else to try.

Also, I need it to be a single function

Here is my code:

https://repl.it/@JamesGordon1/JuicyScentedCrypto
(sorry too long to post)

答:
In stop you write:

```<code>  while not c == 27:
    c = InKey()
    stoprun = 1
  return
</code>```

The stoprun = 1 will create a new local name stoprun instead of modifying the global variable because you never marked stoprun global. Do this:

```<code>def stop():
    global stoprun
    ... # your code
</code>```

Body:
In stop you write:

  while not c == 27:
    c = InKey()
    stoprun = 1
  return

The stoprun = 1 will create a new local name stoprun instead of modifying the global variable because you never marked stoprun global. Do this:

def stop():
    global stoprun
    ... # your code


问:
How to define a Map<String,CustomObject> in build.gradle
I have a plugin as below

```<code>class AbstractConfigExtension {
    public static final String NAME = "abstract_extension"
    Project project

    // Configuration extension properties
    String service
    String substrate
    String region
    String group
    String pod
    Map<String,InstanceGridDetails> instanceGridDetails  = new HashMap<String,InstanceGridDetails>()
    // new HashMap<String,String>()
    List<String> tags = new ArrayList<>()
    List<String> instances = ["i01"]
    int numInstances = 1
    boolean generateServiceFiles = true
}
</code>```

I have a different class called InstanceGridDetails.groovy

```<code>class InstanceGridDetails {
    // Grid Properties
    String grid
    String dsName
    String ddName

    public AcdsInstanceGridDetails () {

    }

    String getGrid() {
        return this.grid
    }

    void grid(String grid) {
        this.grid = grid
    }

    String dsName() {
        return this.dsName
    }

    void dsName(String dsName) {
        this.dsName = dsName
    }

    String ddName() {
        return this.ddName
    }

    void ddName(String ddName) {
        this.ddName = ddName
    }
}
</code>```

This is called as a plugin using the build.gradle as below

```<code>apply plugin: 'java'
apply plugin: HoconConfigPlugin
apply plugin: GriddableCaacRpmPlugin

abstract_extension {
    service "relay"
    substrate "1p"
    region "xrd"
    instanceGridDetails = ["i01": InstanceGridDetails { gridName "grid1"
                                                            dsName "ds1"
                                                            ddName "dd1"} ]
    numInstances 1
    tags = ["medium_mem"]
}
</code>```

when I am doing as above I am getting the issue as below

FAILURE: Build failed with an exception.

Where: Build file 'config-packages/service-cfg-1p-xrd/build.gradle'
  line: 13

What went wrong: A problem occurred evaluating project ':config-packages:service-cfg-1p-xrd'.

Could not find method InstanceGridDetails() for arguments [build_b1plunv4uhm1dpn66jee47jiz$_run_closure1$_closure2@25cf3fbf] on
    object of type AbstractConfigExtension.

答:
Your constructor is still called AcdsInstanceGridDetails while your class is called InstanceGridDetails. They should have the same name.

Try replacing all occurrences of AcdsInstanceGridDetails with InstanceGridDetails

Body:
I have a plugin as below

class AbstractConfigExtension {
    public static final String NAME = "abstract_extension"
    Project project

    // Configuration extension properties
    String service
    String substrate
    String region
    String group
    String pod
    Map<String,InstanceGridDetails> instanceGridDetails  = new HashMap<String,InstanceGridDetails>()
    // new HashMap<String,String>()
    List<String> tags = new ArrayList<>()
    List<String> instances = ["i01"]
    int numInstances = 1
    boolean generateServiceFiles = true
}

I have a different class called InstanceGridDetails.groovy

class InstanceGridDetails {
    // Grid Properties
    String grid
    String dsName
    String ddName

    public AcdsInstanceGridDetails () {

    }

    String getGrid() {
        return this.grid
    }

    void grid(String grid) {
        this.grid = grid
    }

    String dsName() {
        return this.dsName
    }

    void dsName(String dsName) {
        this.dsName = dsName
    }

    String ddName() {
        return this.ddName
    }

    void ddName(String ddName) {
        this.ddName = ddName
    }
}

This is called as a plugin using the build.gradle as below

apply plugin: 'java'
apply plugin: HoconConfigPlugin
apply plugin: GriddableCaacRpmPlugin

abstract_extension {
    service "relay"
    substrate "1p"
    region "xrd"
    instanceGridDetails = ["i01": InstanceGridDetails { gridName "grid1"
                                                            dsName "ds1"
                                                            ddName "dd1"} ]
    numInstances 1
    tags = ["medium_mem"]
}

when I am doing as above I am getting the issue as below

FAILURE: Build failed with an exception.

Where: Build file 'config-packages/service-cfg-1p-xrd/build.gradle'
  line: 13

What went wrong: A problem occurred evaluating project ':config-packages:service-cfg-1p-xrd'.

Could not find method InstanceGridDetails() for arguments [build_b1plunv4uhm1dpn66jee47jiz$_run_closure1$_closure2@25cf3fbf] on
    object of type AbstractConfigExtension.


问:
How to add a picture next to a table?
```<code><style>

table.greyGridTable {
  border: 2px solid #2196F3;
  width: 50%;
  text-align: center;
  border-collapse: collapse;
  font-family: 'Times New Roman', Times, serif, Helvetica, sans-serif;
}
table.greyGridTable td, table.greyGridTable th {
  border: 1px solid #FFFFFF;
  padding: 3px 4px;
}
table.greyGridTable tbody td {
  text-align: left;
  font-size: 25px;
}
table.greyGridTable td:nth-child(even) {
  background:  #2196F3;
}
table.greyGridTable thead {
  background: #2196F3;
  border-bottom: 4px solid #333333;
}
table.greyGridTable thead th {
  font-size: 30px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  border-left: 2px solid #333333;
}
table.greyGridTable thead th:first-child {
  border-left: none;
}

table.greyGridTable tfoot {
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  border-top: 4px solid #333333;
  background:  #2196F3 ;
}
table.greyGridTable tfoot td {
  font-size: 14px;
}

</style>
<style>
.Pa_Kreisi {
    float: left;
    width: 100%;
    height: top;
}
.Pa_Labi {
    float: right;
    width: 100%;
    height: top;
}
</style>

<div class="Pa_Kreisi">
    <table class="greyGridTable">
    <thead>
    <tr>
    <th>Atsēgas vārdi kurus meklēt mūsu mājas lapā:</th>

    </tr>
    </thead>
    <tfoot>
    <tr>
    <td>Meklēt iespējams caur logu lapas augšējā, labajā stūrī!</td>

    </tr>
    </tfoot>
    <tbody>
    <tr>
    <td>Komercprogrammatūra</td>

    </tr>
    <tr>
    <td>Izplatāmprogrammatūra</td>

    </tr>
    <tr>
    <td>Brīvprogrammatūra</td>

    </tr>
    <tr>
    <td>Bezmaksas programmatūra</td>
    </tr>

    </tr>
    </tbody>
    </table>
</div>
<div class="Pa_Labi">

    <img src="snow-run-final.jpg">

</div>
</code>```

Don't mind the text in the table. How do you put the picture next to the table at the top of the website?
I tried it with float, but it didn't work... maybe i made a mistake? Any help appreciated.

For some reason this website want's me to add more details to the question, so ill tell you about myself. I am 18 years old from Latvia, just started to learn how to code, and i am doing a homework for school right now. Since i want it to look pleasing as well, not just tick all the boxes teacher asked us to do, i am hereby asking for your help.

答:
You can use flexbox to align the table and img next to each other.

      ...

```

Title: How to add a picture next to a table?

Body:
    Atsēgas vārdi kurus meklēt mūsu mājas lapā:

    Meklēt iespējams caur logu lapas augšējā, labajā stūrī!

    Komercprogrammatūra

    Izplatāmprogrammatūra

    Brīvprogrammatūra

    Bezmaksas programmatūra

Don't mind the text in the table. How do you put the picture next to the table at the top of the website?
I tried it with float, but it didn't work... maybe i made a mistake? Any help appreciated.

For some reason this website want's me to add more details to the question, so ill tell you about myself. I am 18 years old from Latvia, just started to learn how to code, and i am doing a homework for school right now. Since i want it to look pleasing as well, not just tick all the boxes teacher asked us to do, i am hereby asking for your help.

Body:
You can use flexbox to align the table and img next to each other.

<style>
  .align-next-to-each-other {
    display: flex;
  }
</style>

<div class="align-next-to-each-other">
  <div class="Pa_Kreisi">
    <table class="greyGridTable">
      ...
    </table>
  </div>
  <div class="Pa_Labi">
    <img src="snow-run-final.jpg">
  </div>
</div>


问:
Crashlytics not sending events on iOS
I've migrated our app from react-native-firebase to @react-native-firebase/crashlytics and managed to get crash reports from Android, but no luck with iOS.

I've done all the following:

removed react-native-fabric and all of it's references

installed @react-native-firebase/app

installed @react-native-firebase/crashlytics

added GoogleServices-info.plist in xCode as described in the manual

added firebase.json in the root of the app with crashlytics_debug_enabled: true (this solved Android)

But still no success, not from the simulator nor from appCenter deployed app.

I think it's good to mention that we have 3 schemes (dev, staging, production).

Any idea how to make this work?

答: Chintan from Firebase. Can you reach out to Firebase Support with the bundle ids of all 3 variant? You can also reference this SO post in there. It might just need manual activation.</p>

Title: Crashlytics not sending events on iOS


问:
Code for finding words fails to create correct output
I want to create a program that reads a text file and searches for the phrase "CATEGORIE ANIMALI"
then when it finds it, I want it to search for "UCCELLO" and "ANFIBIO", when it finds "ANFIBIO" I want it to continue reading the file for the next "CATEGORIE ANIMALI"
Here is the text file:

CATEGORIA ANIMALI
MAMMIFERO
PESCE
UCCELLO = tucano
ANFIBIO = rana
RETTILE
CATEGORIA ANIMALI
MAMMIFERO
PESCE
UCCELLO = gru
ANFIBIO = rospo
RETTILE
CATEGORIA ANIMALI
MAMMIFERO
PESCE
UCCELLO = gru
ANFIBIO = rana
RETTILE
```

<p>and here is the code</p>

<pre class="lang-py prettyprint-override"><code>file = open('testfile.txt', 'r')

search_phrase1 = "CATEGORIA ANIMALI"
search_phrase2 = "UCCELLO"
search_phrase3 = "ANFIBIO"
markerInd1 = 0
markerInd2 = 0
markerInd3 = 0
reserveMarker = 0

for line in file.readlines():
    reserveMarker += 1
    if line.find(search_phrase1) >= 0:
        markerInd1 += 1
        print(line)
        for line in file.readlines():
            if line.find(search_phrase2) >= 0:
                markerInd2 += 1
                print(line)
            elif line.find(search_phrase3) >= 0:
                markerInd3 += 1
                print(line)
                break

print(markerInd1)
print(markerInd2)
print(markerInd3)
print(reserveMarker)
</code>```

Output I wish to obtain:

CATEGORIE ANIMALI

UCCELLO = tucano

ANFIBIO = rana

CATEGORIE ANIMALI

UCCELLO = gru

ANFIBIO = rospo

CATEGORIE ANIMALI

UCCELLO = gru

ANFIBIO = rana

3
3
3
19
```

<p>What it really looks like:</p>

<pre class="lang-none prettyprint-override"><code>CATEGORIE ANIMALI

CATEGORIE ANIMALI

CATEGORIE ANIMALI

3
0
0
19
</code>```

答:
I would use with open instead of open so the file closes correctly. You also do not need the 2nd for loop. I think that is mostly where your issue is. That and break needs to be removed. See below example.

```<code>import os

search_phrase1 = "CATEGORIA ANIMALI"
search_phrase2 = "UCCELLO"
search_phrase3 = "ANFIBIO"
markerInd1 = 0
markerInd2 = 0
markerInd3 = 0
reserveMarker = 0

with open('testfile.txt', 'r') as file:
    for line in file.readlines():
        reserveMarker += 1

        if search_phrase1 in line:
            markerInd1 += 1
            print(line)
        if search_phrase2 in line:
            markerInd2 += 1
            print(line)
        elif search_phrase3 in line:
            markerInd3 += 1
            print(line)

print(markerInd1)
print(markerInd2)
print(markerInd3)
print(reserveMarker)
</code>```

Results:

```<code>CATEGORIA ANIMALI

UCCELLO = tucano

ANFIBIO = rana

CATEGORIA ANIMALI

UCCELLO = gru

ANFIBIO = rospo

CATEGORIA ANIMALI

UCCELLO = gru

ANFIBIO = rana

3
3
3
18  # I got 18 instead of 19 so I think you have an extra blank line in your data.
</code>```

Body:
I want to create a program that reads a text file and searches for the phrase "CATEGORIE ANIMALI"
then when it finds it, I want it to search for "UCCELLO" and "ANFIBIO", when it finds "ANFIBIO" I want it to continue reading the file for the next "CATEGORIE ANIMALI"
Here is the text file:

CATEGORIA ANIMALI
MAMMIFERO
PESCE
UCCELLO = tucano
ANFIBIO = rana
RETTILE
CATEGORIA ANIMALI
MAMMIFERO
PESCE
UCCELLO = gru
ANFIBIO = rospo
RETTILE
CATEGORIA ANIMALI
MAMMIFERO
PESCE
UCCELLO = gru
ANFIBIO = rana
RETTILE

and here is the code

file = open('testfile.txt', 'r')

search_phrase1 = "CATEGORIA ANIMALI"
search_phrase2 = "UCCELLO"
search_phrase3 = "ANFIBIO"
markerInd1 = 0
markerInd2 = 0
markerInd3 = 0
reserveMarker = 0

for line in file.readlines():
    reserveMarker += 1
    if line.find(search_phrase1) >= 0:
        markerInd1 += 1
        print(line)
        for line in file.readlines():
            if line.find(search_phrase2) >= 0:
                markerInd2 += 1
                print(line)
            elif line.find(search_phrase3) >= 0:
                markerInd3 += 1
                print(line)
                break

print(markerInd1)
print(markerInd2)
print(markerInd3)
print(reserveMarker)

Output I wish to obtain:

CATEGORIE ANIMALI

UCCELLO = tucano

ANFIBIO = rana

CATEGORIE ANIMALI

UCCELLO = gru

ANFIBIO = rospo

CATEGORIE ANIMALI

UCCELLO = gru

ANFIBIO = rana

3
3
3
19

What it really looks like:

CATEGORIE ANIMALI

CATEGORIE ANIMALI

CATEGORIE ANIMALI

3
0
0
19

Body:
I would use with open instead of open so the file closes correctly. You also do not need the 2nd for loop. I think that is mostly where your issue is. That and break needs to be removed. See below example.

import os

search_phrase1 = "CATEGORIA ANIMALI"
search_phrase2 = "UCCELLO"
search_phrase3 = "ANFIBIO"
markerInd1 = 0
markerInd2 = 0
markerInd3 = 0
reserveMarker = 0

with open('testfile.txt', 'r') as file:
    for line in file.readlines():
        reserveMarker += 1

        if search_phrase1 in line:
            markerInd1 += 1
            print(line)
        if search_phrase2 in line:
            markerInd2 += 1
            print(line)
        elif search_phrase3 in line:
            markerInd3 += 1
            print(line)

print(markerInd1)
print(markerInd2)
print(markerInd3)
print(reserveMarker)

Results:

CATEGORIA ANIMALI

UCCELLO = tucano

ANFIBIO = rana

CATEGORIA ANIMALI

UCCELLO = gru

ANFIBIO = rospo

CATEGORIA ANIMALI

UCCELLO = gru

ANFIBIO = rana

3
3
3
18  # I got 18 instead of 19 so I think you have an extra blank line in your data.


问:
HTML5 php contact form script confirmation
I'm having some trouble with a script confirmation. By standard it's set to hide the contact form and display a confirmation message but it's not working for all browsers. After some tests I realized it doesn't work for most IE versions, which are around 40% of my visitors.

How do I replace the hide-and-show-msg to a "thankyou.html"? I'm guessing this works as most IEs fail to show the confirmation message although they manage to hide the form. The code in 'header' is currently:

```<code><script src="php/js/jquery.validate.js"></script>
<script src="php/js/jquery.placeholder.js"></script>
<script src="php/js/jquery.form.js"></script>
<script>
$(function(){
$('#contact').validate({
submitHandler: function(form) {
    $(form).ajaxSubmit({
    url: 'thankyou.php',
    success: function() {
    $('#contact').hide();
    $('#contact-form').append("<p class='thanks'>Thank you! The message was sent.</center></p>")
    }
    });
    }
});
});
</script>
</code>```

答:
Replace

```<code>$('#contact').hide();     $('#contact-form').append("<p class='thanks'>Thank you! The message was sent.</center></p>")
</code>```

with window.location.href="thankyou.html";

Easy solution. Of course, this code uses relative paths, replace the "thankyou.html" with the actual location of that page.

Also, take out the part that says . You shouldn't be adding a closing tag in that code, the center object should be closed correctly already. Perhaps that's the problem why IE won't show it. HTML coded wrong.

EDIT: And yes, if you so incline, you can use jQuery via $(window.location).attr('href', 'thankyou.html');
though this offers no benefits to my original solution, which is easier to read and understand, not to mention abitrarily faster.

Body:
Replace

$('#contact').hide();     $('#contact-form').append("<p class='thanks'>Thank you! The message was sent.</center></p>")

with window.location.href="thankyou.html";

Easy solution. Of course, this code uses relative paths, replace the "thankyou.html" with the actual location of that page.

Also, take out the part that says </center>. You shouldn't be adding a closing tag in that code, the center object should be closed correctly already. Perhaps that's the problem why IE won't show it. HTML coded wrong.

EDIT: And yes, if you so incline, you can use jQuery via $(window.location).attr('href', 'thankyou.html');
though this offers no benefits to my original solution, which is easier to read and understand, not to mention abitrarily faster.


问:
How to display matching description of an object nested in an array?
I have a function, whose purpose is to display specific description of a particular object that is nested within an array. The idea is that once the function (findSettings()) receives a particular array(systemSettings) and some key(tab12) that is in the objects, it should run through the switch statement and provide its matching description.

In other words, if the function's argument is 'tab12', then it should return the description, 'Description for tab12'.

I have tried to find a matching object using the find method, and that works well, although if I try to run the switch statement, it returns an error: 'Obejct is possibly undefined'.

```<code>const systemSettings = [
  {key: 'tab1', value: 'Main Tab'},
  {key: 'tab12', value: 'Tab 12'},
  {key: 'tab13', value: 'Tab 13'},
  {key: 'tab4', value: 'Tab 4'}
]

type sampObj = {
  key: string;
  value: string;
}

let info: string = '';

function findSetting(arr: sampObj[], settingKey: string) {

  const selectedObjs = arr.find(obj => obj.key === settingKey);

  switch(selectedObjs.key) {
    case 'tab1':
      info += 'Description for tab1';
      break;
    case 'tab12':
      info += 'Description for tab12';
      break;
    case 'tab13':
      info += 'Description for tab13';
      break;
    case 'tab4':
      info += 'Description for tab4';
      break;
    default:
      info += 'No description available'
  }

}

findSetting(systemSettings, 'tab12')```

Any assistance would be highly appreciated.
Thanks.
```

答:
I think simpler solution would be to use something like Map for storing your descriptions against the keys. Also, there is handy Utility Type in TypeScript called Record for type safety. Then you simply don't have to provide your array in findSetting  function

```<code>  systemSettingsDescriptions: Record<string, string> = {
    tab1: "Description for tab1",
    tab2: "Description for tab2",
    tab3: "Description for tab3"
  };

  systemSettings: sampObj [] = [
    { key: "tab1", value: "Main Tab" },
    { key: "tab12", value: "Tab 12" },
    { key: "tab13", value: "Tab 13" },
    { key: "tab4", value: "Tab 4" }
  ];

  function findSetting(settingKey: string): string {
    this.systemSettingsDescriptions[settingKey] || "No description available";
  }
</code>```

Body:
I have a function, whose purpose is to display specific description of a particular object that is nested within an array. The idea is that once the function (findSettings()) receives a particular array(systemSettings) and some key(tab12) that is in the objects, it should run through the switch statement and provide its matching description.

In other words, if the function's argument is 'tab12', then it should return the description, 'Description for tab12'.

I have tried to find a matching object using the find method, and that works well, although if I try to run the switch statement, it returns an error: 'Obejct is possibly undefined'.

const systemSettings = [
  {key: 'tab1', value: 'Main Tab'},
  {key: 'tab12', value: 'Tab 12'},
  {key: 'tab13', value: 'Tab 13'},
  {key: 'tab4', value: 'Tab 4'}
]

type sampObj = {
  key: string;
  value: string;
}

let info: string = '';

function findSetting(arr: sampObj[], settingKey: string) {

  const selectedObjs = arr.find(obj => obj.key === settingKey);

  switch(selectedObjs.key) {
    case 'tab1':
      info += 'Description for tab1';
      break;
    case 'tab12':
      info += 'Description for tab12';
      break;
    case 'tab13':
      info += 'Description for tab13';
      break;
    case 'tab4':
      info += 'Description for tab4';
      break;
    default:
      info += 'No description available'
  }

}

findSetting(systemSettings, 'tab12')```

Any assistance would be highly appreciated.
Thanks.

Body:
I think simpler solution would be to use something like Map for storing your descriptions against the keys. Also, there is handy Utility Type in TypeScript called Record for type safety. Then you simply don't have to provide your array in findSetting  function

  systemSettingsDescriptions: Record<string, string> = {
    tab1: "Description for tab1",
    tab2: "Description for tab2",
    tab3: "Description for tab3"
  };

  systemSettings: sampObj [] = [
    { key: "tab1", value: "Main Tab" },
    { key: "tab12", value: "Tab 12" },
    { key: "tab13", value: "Tab 13" },
    { key: "tab4", value: "Tab 4" }
  ];

  function findSetting(settingKey: string): string {
    this.systemSettingsDescriptions[settingKey] || "No description available";
  }


问:
MoPub #withMediatedNetworkConfiguration explained
IMHO the MoPub documentation lacks on code samples explaining the usage of available functions. This function is #withMediatedNetworkConfiguration.

Why is this function important? In the Network SDK initialization it says

Note that you can call .withMediatedNetworkConfiguration() on your SdkConfiguration.Builder to pass network configurations required for pre-initialization. Otherwise expect your first attempt to pre-initialize mediated networks to fail because no network data is cached at this point. All your subsequent attempts to pre-initialize should succeed for the duration of the app’s life.

Meaning if you call the app first time, only MoPub's Marketplace will be initialized. Mediation networks did not get required parameters during init and will fail. Next launch everything will work.

So MoPub does give you a chance to call #withMediatedNetworkConfiguration to pass required parameters even on first launch.

But how is all this accomplished?

答:
Indeed this lacks of documentation.

Facebook for example does not need any parameters mediated by MoPub, it will successfully init on first app launch. AdColony and Vungle (and most of the others) will NOT init on first launch. This is loss in revenue due to lack of competition.

Let's take a look at AdColony, which gave me some headache. Simple MoPubSDK init with AdColony init looks like this.

```<code>SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder("362da1882dfc49f3a33b92ea1708f3a5")
            .withMediatedNetworkConfiguration(AdColonyAdapterConfiguration.class.getName(), adColonySettings)
            .build();

MoPub.initializeSdk(activity, sdkConfiguration, listener);
</code>```

Alright. But how does the AdColonyAdapterConfiguration#initializeNetwork look like. This gives us some ideas has is the content of the passed configuration is.

Not to hard. Two strings are passed (appId and zoneId) and one string array (allZoneIds).

Reading the MoPub documentation up and down helped me find the AdColony mediation guide saying

For my understanding appId and zoneId is required and allZoneIds is kind off optional?! But which zoneId if multiple are used in my app? To make things short. This is all wrong. In
AdColonyAdapterConfiguration#initializeNetwork we can find out that only appId and allZoneIds is really needed.

See here

AllZoneIds is a retrieved by Json.jsonArrayToStringArray. But how is that formatted again?! Let's come to an end.

Lets look at the comprehensive answer how to initialize adColony with MoPub on first launch:

```<code>Map<String, String> adColonySettings = new HashMap<>();
    adColonySettings.put("appId", "yourAppId");
    adColonySettings.put("zoneId", "ANYOfYourZoneIds");
    adColonySettings.put("allZoneIds", "[\"bannerZoneId, interstitialZoneId\"]");

    SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder("moPubId")
 .withMediatedNetworkConfiguration(AdColonyAdapterConfiguration.class.getName(), adColonySettings)
            .build();

    MoPub.initializeSdk(activity, sdkConfiguration, initSdkListener());
</code>```

Another sample is Vungle. Init it like this:

```<code>Map<String, String> vungleSettings = new HashMap<>();
    vungleSettings.put("appId", "vungleAppId");

    SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder("moPubId")
            .withMediatedNetworkConfiguration(VungleAdapterConfiguration.class.getName(), vungleSettings)
            .build();
</code>```

Body:
Indeed this lacks of documentation.

Facebook for example does not need any parameters mediated by MoPub, it will successfully init on first app launch. AdColony and Vungle (and most of the others) will NOT init on first launch. This is loss in revenue due to lack of competition.

Let's take a look at AdColony, which gave me some headache. Simple MoPubSDK init with AdColony init looks like this.

SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder("362da1882dfc49f3a33b92ea1708f3a5")
            .withMediatedNetworkConfiguration(AdColonyAdapterConfiguration.class.getName(), adColonySettings)
            .build();

MoPub.initializeSdk(activity, sdkConfiguration, listener);

Alright. But how does the AdColonyAdapterConfiguration#initializeNetwork look like. This gives us some ideas has is the content of the passed configuration is.

Not to hard. Two strings are passed (appId and zoneId) and one string array (allZoneIds).

Reading the MoPub documentation up and down helped me find the AdColony mediation guide saying

For my understanding appId and zoneId is required and allZoneIds is kind off optional?! But which zoneId if multiple are used in my app? To make things short. This is all wrong. In
AdColonyAdapterConfiguration#initializeNetwork we can find out that only appId and allZoneIds is really needed.

See here

AllZoneIds is a retrieved by Json.jsonArrayToStringArray. But how is that formatted again?! Let's come to an end.

Lets look at the comprehensive answer how to initialize adColony with MoPub on first launch:

Map<String, String> adColonySettings = new HashMap<>();
    adColonySettings.put("appId", "yourAppId");
    adColonySettings.put("zoneId", "ANYOfYourZoneIds");
    adColonySettings.put("allZoneIds", "[\"bannerZoneId, interstitialZoneId\"]");

    SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder("moPubId")
 .withMediatedNetworkConfiguration(AdColonyAdapterConfiguration.class.getName(), adColonySettings)
            .build();

    MoPub.initializeSdk(activity, sdkConfiguration, initSdkListener());

Another sample is Vungle. Init it like this:

Map<String, String> vungleSettings = new HashMap<>();
    vungleSettings.put("appId", "vungleAppId");

    SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder("moPubId")
            .withMediatedNetworkConfiguration(VungleAdapterConfiguration.class.getName(), vungleSettings)
            .build();


问:
Implementing a Typescript class interface does not preserve method types
I'm trying to write a Typescript interface, then write a class that implements that interface.

The problem is that I can't seem to get the method signatures from the interface to apply to the class.

Here's a slimmed-down example:

export interface Foo {
  bar(value: string): void;
}

export class MyFoo implements Foo {
  // ✔ Typescript error:
  // Property 'bar' is missing in type 'MyFoo' but required in type 'Foo'
}

export class MyFoo implements Foo {
  // value is inferred as `any` instead of `string`,
  // and there aren't any errors with the return type mismatch
  bar(value) { return true; }
}

```

It seems that the compiler is aware that the bar method should exist, but doesn't preserve the signature of it for some reason.

答:
Type any can be assigned to any other type in TypeScript. You should specify the type for value in the implementation of the bar method. Then. if it's anything other than string, the compiler will throw an error.

You can force your TypeScript compiler not to allow any implicit any by adding the following line to your tsconfig.json file.

```<code>"noImplicitAny": true
</code>```

In general, the best practice is to explicitly add the type for function parameters and return values and avoid any to the extent possible.

Body:
I'm trying to write a Typescript interface, then write a class that implements that interface.

The problem is that I can't seem to get the method signatures from the interface to apply to the class.

Here's a slimmed-down example:

export interface Foo {
  bar(value: string): void;
}

export class MyFoo implements Foo {
  // ✔ Typescript error:
  // Property 'bar' is missing in type 'MyFoo' but required in type 'Foo'
}

export class MyFoo implements Foo {
  // value is inferred as `any` instead of `string`,
  // and there aren't any errors with the return type mismatch
  bar(value) { return true; }
}

It seems that the compiler is aware that the bar method should exist, but doesn't preserve the signature of it for some reason.

Body:
Type any can be assigned to any other type in TypeScript. You should specify the type for value in the implementation of the bar method. Then. if it's anything other than string, the compiler will throw an error.

You can force your TypeScript compiler not to allow any implicit any by adding the following line to your tsconfig.json file.

"noImplicitAny": true

In general, the best practice is to explicitly add the type for function parameters and return values and avoid any to the extent possible.


问:
How to get SUM of f3 but Grouped by f2
I want to get all comments count grouped by category. eg

```<code>f1      f2      f3
php     hello   34
php     hello   34
php     hello   34
php     world   23
php     world   23
php     world   23
asp     world1   43
asp     world1  43
asp     world1   43
</code>```

How to get sum of f3 but grouped by f2?

So not 34 + 34 + 34 +23 ... but 34 + 23 + 43

EDIT: f2 is unique

答:
The only way I can think of to get the sum of the three different values is

```<code>Select sum (distinct f3) from yourtable
</code>```

I hope it makes sense to you, because I'm still trying to figure out what you want.

Title: How to get SUM of f3 but Grouped by f2

Body:
I want to get all comments count grouped by category. eg

f1      f2      f3
php     hello   34
php     hello   34
php     hello   34
php     world   23
php     world   23
php     world   23
asp     world1   43
asp     world1  43
asp     world1   43

How to get sum of f3 but grouped by f2?

So not 34 + 34 + 34 +23 ... but 34 + 23 + 43

EDIT: f2 is unique

Body:
The only way I can think of to get the sum of the three different values is

Select sum (distinct f3) from yourtable

I hope it makes sense to you, because I'm still trying to figure out what you want.