问:
Can a C# program be cross-platform?
I'm a newbie to programming, and I'm considering using C# to write a VERY simple program that simply edits a text file.

Will it work on Macs and Linux? What will work?

I want to know what makes a program cross-platform?

答:
Now C# is fully cross platform and has variety of frameworks and run times.

Java is a language + framework. But C# is just a modern language. C# language features are very powerful, easy to learn. No confusion between framework and language.

C# can be used in following frameworks

.Net core (Multi platform supports Linux, Windows and Mac), mostly used to develop restful services, web applications and enterprise systems

.Net Framework (Windows only), Same as .net core, but has more windows only features

Unity - One of most used game engine to develop games for PC, Sony, Xbox devices etc..

Xamarin - To develop native Mobile apps (Android, IOS, Mac)

.Net standard - Create a library in .net standard use in all above applications

Java - Code once, Ship same file to all platforms

C++, C, Rust - Code once, Compile for specific platform

C# - It is just a language, pick your framework according to requirement.

Most popular applications like Chrome, Firefox uses C++, Rust and they are compiled for each platform. But still they share the majority of code between these platforms. Some games use C++ to share the code between IOS and Android.

For new developers its good to start with NodeJS and C#. Both are easy and can do any type of applications.

Title: Can a C# program be cross-platform?


来源: stackexchange

问:
Connecting to Microsoft SQL server using Python
I am trying to connect to SQL through python to run some queries on some SQL databases on Microsoft SQL server. From my research online and on this forum the most promising library seems to be pyodbc. So I have made the following code

```<code>import pyodbc
conn = pyodbc.connect(init_string="driver={SQLOLEDB}; server=+ServerName+;
database=+MSQLDatabase+; trusted_connection=true")
cursor = conn.cursor()
</code>```

and get the following error

```<code>Traceback (most recent call last):
  File "C:\Users...\scrap.py", line 3, in <module>
    conn = pyodbc.connect(init_string="driver={SQLOLEDB}; server=+ServerName+; database=+MSQLDatabase+; trusted_connection=true")
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
</code>```

I have looked at the folowing posts and tried changing my driver to {sql server} and have connected using ODBC links before in SAS, which is partially what my above code is based on, so don't think I need to install anything else.

pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')

Pyodbc - "Data source name not found, and no default driver specified"

Thanks

答:
I Prefer this way ... it was much easier

http://www.pymssql.org/en/stable/pymssql_examples.html

```<code>conn = pymssql.connect("192.168.10.198", "odoo", "secret", "EFACTURA")
cursor = conn.cursor()
cursor.execute('SELECT * FROM usuario')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to connect to SQL through python to run some queries on some SQL databases on Microsoft SQL server. From my research online and on this forum the most promising library seems to be pyodbc. So I have made the following code

import pyodbc
conn = pyodbc.connect(init_string="driver={SQLOLEDB}; server=+ServerName+;
database=+MSQLDatabase+; trusted_connection=true")
cursor = conn.cursor()

and get the following error

Traceback (most recent call last):
  File "C:\Users...\scrap.py", line 3, in <module>
    conn = pyodbc.connect(init_string="driver={SQLOLEDB}; server=+ServerName+; database=+MSQLDatabase+; trusted_connection=true")
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

I have looked at the folowing posts and tried changing my driver to {sql server} and have connected using ODBC links before in SAS, which is partially what my above code is based on, so don't think I need to install anything else.

pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')

Pyodbc - "Data source name not found, and no default driver specified"

Thanks

Body:
I Prefer this way ... it was much easier

http://www.pymssql.org/en/stable/pymssql_examples.html

conn = pymssql.connect("192.168.10.198", "odoo", "secret", "EFACTURA")
cursor = conn.cursor()
cursor.execute('SELECT * FROM usuario')


问:
Formula vs non-formula interface in train()
[I looked into similar threads here and in github, and none of the issues suggested by Max and others seem to relate to my case.]

I have seen some here reporting about formula interface failing whereas non-formula interface working fine for them. My problem is the opposite. Thetrain()function below with formula interface works perfect:

```<code>glmTune <- train(class ~ .,
                 data = trainData,
                 method = "glmnet",
                 trControl = train.control,
                 tuneGrid = tune.grid)
</code>```

This one below gives NA errors:

```<code>predictors <- trainData[, !(names(trainData) %in% "class")]
response <- trainData$class
glmTune <- train(x = predictors,
                 y = response,
                 method = "glmnet",
                 trControl = train.control,
                 tuneGrid = tune.grid)
</code>```

This happens with bothglmnetandxgboost,and regardless of whetheryis factor or numeric, butxhas lot of factor variables. Thanks for any help.

Wanted to add, the error for factoryis this:

```<code>Something is wrong; all the Accuracy metric values are missing:
    Accuracy       Kappa
 Min.   : NA   Min.   : NA
 1st Qu.: NA   1st Qu.: NA
 Median : NA   Median : NA
 Mean   :NaN   Mean   :NaN
 3rd Qu.: NA   3rd Qu.: NA
 Max.   : NA   Max.   : NA
 NA's   :243   NA's   :243
Error: Stopping
In addition: Warning message:
In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.
</code>```

And for numericalyit is only slightly different (different performance metric):

```<code>Something is wrong; all the RMSE metric values are missing:
      RMSE        Rsquared
 Min.   : NA   Min.   : NA
 1st Qu.: NA   1st Qu.: NA
 Median : NA   Median : NA
 Mean   :NaN   Mean   :NaN
 3rd Qu.: NA   3rd Qu.: NA
 Max.   : NA   Max.   : NA
 NA's   :100   NA's   :100
Error: Stopping
In addition: Warning message:
In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.
</code>```

Here is the code:

```<code>library(caret)
library(dplyr)
library(glmnet)

# see dput(droplevels(head(df, 20))) output of data below:

# 70%/30% split
set.seed(42)
inTrain <- createDataPartition(df$lnprice, p=0.7, list=F)
trainData <- df[inTrain, ]
testData <- df[-inTrain, ]

# train model
train.control <- trainControl(method = "repeatedcv",
                              number = 10,
                              repeats= 5,
                              allowParallel = F)
tune.grid <- expand.grid(lambda = seq(0.0001,0.1,length=20),
                         alpha = c(0, 0.5, 1))
X <- trainData[, !(names(trainData) %in% "lnprice")]
Y <- trainData$lnprice
fit <- train(
#  x = X, y = Y,                        # non-formula
  lnprice ~ ., data = trainData,       # formula
  method = "glmnet",
  preProcess = c("zv", "center", "scale"),
  tuneGrid = tune.grid,
  trControl = train.control)

# plot model
print(plot(fit))

> dput(droplevels(head(df,20)))
structure(list(fuel.type = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "gas", class = "factor"),
    aspiration = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("std",
    "turbo"), class = "factor"), num.of.doors = structure(c(2L,
    2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L), .Label = c("four", "two"), class = "factor"),
    body.style = structure(c(1L, 1L, 2L, 3L, 3L, 3L, 3L, 4L,
    3L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L), .Label = c("convertible",
    "hatchback", "sedan", "wagon"), class = "factor"), drive.wheels = structure(c(2L,
    2L, 2L, 1L, 3L, 1L, 1L, 1L, 1L, 3L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L), .Label = c("fwd", "rwd", "X4wd"), class = "factor"),
    engine.location = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "front", class = "factor"),
    wheel.base = c(88.6, 88.6, 94.5, 99.8, 99.4, 99.8, 105.8,
    105.8, 105.8, 99.5, 101.2, 101.2, 101.2, 101.2, 103.5, 103.5,
    103.5, 110, 88.4, 94.5), length = c(168.8, 168.8, 171.2,
    176.6, 176.6, 177.3, 192.7, 192.7, 192.7, 178.2, 176.8, 176.8,
    176.8, 176.8, 189, 189, 193.8, 197, 141.1, 155.9), width = c(64.1,
    64.1, 65.5, 66.2, 66.4, 66.3, 71.4, 71.4, 71.4, 67.9, 64.8,
    64.8, 64.8, 64.8, 66.9, 66.9, 67.9, 70.9, 60.3, 63.6), height = c(48.8,
    48.8, 52.4, 54.3, 54.3, 53.1, 55.7, 55.7, 55.9, 52, 54.3,
    54.3, 54.3, 54.3, 55.7, 55.7, 53.7, 56.3, 53.2, 52), curb.weight = c(2548L,
    2548L, 2823L, 2337L, 2824L, 2507L, 2844L, 2954L, 3086L, 3053L,
    2395L, 2395L, 2710L, 2765L, 3055L, 3230L, 3380L, 3505L, 1488L,
    1874L), engine.type = structure(c(1L, 1L, 4L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 3L), .Label = c("dohc",
    "l", "ohc", "ohcv"), class = "factor"), num.of.cylinders = structure(c(2L,
    2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L), .Label = c("five.six", "four.or.less"), class = "factor"),
    engine.size = c(130L, 130L, 152L, 109L, 136L, 136L, 136L,
    136L, 131L, 131L, 108L, 108L, 164L, 164L, 164L, 209L, 209L,
    209L, 61L, 90L), fuel.system = structure(c(1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L), .Label = c("mpfi", "X2bbl"), class = "factor"), bore = c(3.47,
    3.47, 2.68, 3.19, 3.19, 3.19, 3.19, 3.19, 3.13, 3.13, 3.5,
    3.5, 3.31, 3.31, 3.31, 3.62, 3.62, 3.62, 2.91, 3.03), stroke = c(2.68,
    2.68, 3.47, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 2.8, 2.8,
    3.19, 3.19, 3.19, 3.39, 3.39, 3.39, 3.03, 3.11), compression.ratio = c(9,
    9, 9, 10, 8, 8.5, 8.5, 8.5, 8.3, 7, 8.8, 8.8, 9, 9, 9, 8,
    8, 8, 9.5, 9.6), horsepower = c(111, 111, 154, 102, 115,
    110, 110, 110, 140, 160, 101, 101, 121, 121, 121, 182, 182,
    182, 48, 70), peak.rpm = c(5000L, 5000L, 5000L, 5500L, 5500L,
    5500L, 5500L, 5500L, 5500L, 5500L, 5800L, 5800L, 4250L, 4250L,
    4250L, 5400L, 5400L, 5400L, 5100L, 5400L), city.mpg = c(21L,
    21L, 19L, 24L, 18L, 19L, 19L, 19L, 17L, 16L, 23L, 23L, 21L,
    21L, 20L, 16L, 16L, 15L, 47L, 38L), highway.mpg = c(27L,
    27L, 26L, 30L, 22L, 25L, 25L, 25L, 20L, 22L, 29L, 29L, 28L,
    28L, 25L, 22L, 22L, 20L, 53L, 43L), make = structure(c(1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 4L, 4L), .Label = c("alfa.romero", "audi", "bmw",
    "chevrolet"), class = "factor"), lnprice = c(9.5101, 9.7111,
    9.7111, 9.5432, 9.7671, 9.6323, 9.7819, 9.848, 10.0806, 9.69176,
    9.7069, 9.7365, 9.9508, 9.9573, 10.1091, 10.334, 10.629,
    10.5154, 8.5469, 8.7475)), .Names = c("fuel.type", "aspiration",
"num.of.doors", "body.style", "drive.wheels", "engine.location",
"wheel.base", "length", "width", "height", "curb.weight", "engine.type",
"num.of.cylinders", "engine.size", "fuel.system", "bore", "stroke",
"compression.ratio", "horsepower", "peak.rpm", "city.mpg", "highway.mpg",
"make", "lnprice"), row.names = c(NA, 20L), class = "data.frame")
</code>```

答:
Strange. It looks like the train.default method doesn't have a default na.action handler?

Output from ?caret::train

```<code>## Default S3 method:
train(x, y, method = "rf", preProcess = NULL, ...,
  weights = NULL, metric = ifelse(is.factor(y), "Accuracy", "RMSE"),
  maximize = ifelse(metric %in% c("RMSE", "logLoss", "MAE"), FALSE, TRUE),
  trControl = trainControl(), tuneGrid = NULL,
  tuneLength = ifelse(trControl$method == "none", 1, 3))
</code>```

Whereas the train.formula method does:

```<code>## S3 method for class 'formula'
train(form, data, ..., weights, subset, na.action = na.fail, contrasts = NULL)
                                        ^^^^^^^^^^^^^^^^^^^
</code>```

If you add na.action = na.fail to your train.default call, x, y interface, do you get the same behaviour as the train.formula call?

Body:
[I looked into similar threads here and in github, and none of the issues suggested by Max and others seem to relate to my case.]

I have seen some here reporting about formula interface failing whereas non-formula interface working fine for them. My problem is the opposite. Thetrain()function below with formula interface works perfect:

glmTune <- train(class ~ .,
                 data = trainData,
                 method = "glmnet",
                 trControl = train.control,
                 tuneGrid = tune.grid)

This one below gives NA errors:

predictors <- trainData[, !(names(trainData) %in% "class")]
response <- trainData$class
glmTune <- train(x = predictors,
                 y = response,
                 method = "glmnet",
                 trControl = train.control,
                 tuneGrid = tune.grid)

This happens with bothglmnetandxgboost,and regardless of whetheryis factor or numeric, butxhas lot of factor variables. Thanks for any help.

Wanted to add, the error for factoryis this:

Something is wrong; all the Accuracy metric values are missing:
    Accuracy       Kappa
 Min.   : NA   Min.   : NA
 1st Qu.: NA   1st Qu.: NA
 Median : NA   Median : NA
 Mean   :NaN   Mean   :NaN
 3rd Qu.: NA   3rd Qu.: NA
 Max.   : NA   Max.   : NA
 NA's   :243   NA's   :243
Error: Stopping
In addition: Warning message:
In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.

And for numericalyit is only slightly different (different performance metric):

Something is wrong; all the RMSE metric values are missing:
      RMSE        Rsquared
 Min.   : NA   Min.   : NA
 1st Qu.: NA   1st Qu.: NA
 Median : NA   Median : NA
 Mean   :NaN   Mean   :NaN
 3rd Qu.: NA   3rd Qu.: NA
 Max.   : NA   Max.   : NA
 NA's   :100   NA's   :100
Error: Stopping
In addition: Warning message:
In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.

Here is the code:

library(caret)
library(dplyr)
library(glmnet)

# see dput(droplevels(head(df, 20))) output of data below:

# 70%/30% split
set.seed(42)
inTrain <- createDataPartition(df$lnprice, p=0.7, list=F)
trainData <- df[inTrain, ]
testData <- df[-inTrain, ]

# train model
train.control <- trainControl(method = "repeatedcv",
                              number = 10,
                              repeats= 5,
                              allowParallel = F)
tune.grid <- expand.grid(lambda = seq(0.0001,0.1,length=20),
                         alpha = c(0, 0.5, 1))
X <- trainData[, !(names(trainData) %in% "lnprice")]
Y <- trainData$lnprice
fit <- train(
#  x = X, y = Y,                        # non-formula
  lnprice ~ ., data = trainData,       # formula
  method = "glmnet",
  preProcess = c("zv", "center", "scale"),
  tuneGrid = tune.grid,
  trControl = train.control)

# plot model
print(plot(fit))

> dput(droplevels(head(df,20)))
structure(list(fuel.type = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "gas", class = "factor"),
    aspiration = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("std",
    "turbo"), class = "factor"), num.of.doors = structure(c(2L,
    2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L), .Label = c("four", "two"), class = "factor"),
    body.style = structure(c(1L, 1L, 2L, 3L, 3L, 3L, 3L, 4L,
    3L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L), .Label = c("convertible",
    "hatchback", "sedan", "wagon"), class = "factor"), drive.wheels = structure(c(2L,
    2L, 2L, 1L, 3L, 1L, 1L, 1L, 1L, 3L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L), .Label = c("fwd", "rwd", "X4wd"), class = "factor"),
    engine.location = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "front", class = "factor"),
    wheel.base = c(88.6, 88.6, 94.5, 99.8, 99.4, 99.8, 105.8,
    105.8, 105.8, 99.5, 101.2, 101.2, 101.2, 101.2, 103.5, 103.5,
    103.5, 110, 88.4, 94.5), length = c(168.8, 168.8, 171.2,
    176.6, 176.6, 177.3, 192.7, 192.7, 192.7, 178.2, 176.8, 176.8,
    176.8, 176.8, 189, 189, 193.8, 197, 141.1, 155.9), width = c(64.1,
    64.1, 65.5, 66.2, 66.4, 66.3, 71.4, 71.4, 71.4, 67.9, 64.8,
    64.8, 64.8, 64.8, 66.9, 66.9, 67.9, 70.9, 60.3, 63.6), height = c(48.8,
    48.8, 52.4, 54.3, 54.3, 53.1, 55.7, 55.7, 55.9, 52, 54.3,
    54.3, 54.3, 54.3, 55.7, 55.7, 53.7, 56.3, 53.2, 52), curb.weight = c(2548L,
    2548L, 2823L, 2337L, 2824L, 2507L, 2844L, 2954L, 3086L, 3053L,
    2395L, 2395L, 2710L, 2765L, 3055L, 3230L, 3380L, 3505L, 1488L,
    1874L), engine.type = structure(c(1L, 1L, 4L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 3L), .Label = c("dohc",
    "l", "ohc", "ohcv"), class = "factor"), num.of.cylinders = structure(c(2L,
    2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L), .Label = c("five.six", "four.or.less"), class = "factor"),
    engine.size = c(130L, 130L, 152L, 109L, 136L, 136L, 136L,
    136L, 131L, 131L, 108L, 108L, 164L, 164L, 164L, 209L, 209L,
    209L, 61L, 90L), fuel.system = structure(c(1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L), .Label = c("mpfi", "X2bbl"), class = "factor"), bore = c(3.47,
    3.47, 2.68, 3.19, 3.19, 3.19, 3.19, 3.19, 3.13, 3.13, 3.5,
    3.5, 3.31, 3.31, 3.31, 3.62, 3.62, 3.62, 2.91, 3.03), stroke = c(2.68,
    2.68, 3.47, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 2.8, 2.8,
    3.19, 3.19, 3.19, 3.39, 3.39, 3.39, 3.03, 3.11), compression.ratio = c(9,
    9, 9, 10, 8, 8.5, 8.5, 8.5, 8.3, 7, 8.8, 8.8, 9, 9, 9, 8,
    8, 8, 9.5, 9.6), horsepower = c(111, 111, 154, 102, 115,
    110, 110, 110, 140, 160, 101, 101, 121, 121, 121, 182, 182,
    182, 48, 70), peak.rpm = c(5000L, 5000L, 5000L, 5500L, 5500L,
    5500L, 5500L, 5500L, 5500L, 5500L, 5800L, 5800L, 4250L, 4250L,
    4250L, 5400L, 5400L, 5400L, 5100L, 5400L), city.mpg = c(21L,
    21L, 19L, 24L, 18L, 19L, 19L, 19L, 17L, 16L, 23L, 23L, 21L,
    21L, 20L, 16L, 16L, 15L, 47L, 38L), highway.mpg = c(27L,
    27L, 26L, 30L, 22L, 25L, 25L, 25L, 20L, 22L, 29L, 29L, 28L,
    28L, 25L, 22L, 22L, 20L, 53L, 43L), make = structure(c(1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 4L, 4L), .Label = c("alfa.romero", "audi", "bmw",
    "chevrolet"), class = "factor"), lnprice = c(9.5101, 9.7111,
    9.7111, 9.5432, 9.7671, 9.6323, 9.7819, 9.848, 10.0806, 9.69176,
    9.7069, 9.7365, 9.9508, 9.9573, 10.1091, 10.334, 10.629,
    10.5154, 8.5469, 8.7475)), .Names = c("fuel.type", "aspiration",
"num.of.doors", "body.style", "drive.wheels", "engine.location",
"wheel.base", "length", "width", "height", "curb.weight", "engine.type",
"num.of.cylinders", "engine.size", "fuel.system", "bore", "stroke",
"compression.ratio", "horsepower", "peak.rpm", "city.mpg", "highway.mpg",
"make", "lnprice"), row.names = c(NA, 20L), class = "data.frame")

Body:
Strange. It looks like the train.default method doesn't have a default na.action handler?

Output from ?caret::train

## Default S3 method:
train(x, y, method = "rf", preProcess = NULL, ...,
  weights = NULL, metric = ifelse(is.factor(y), "Accuracy", "RMSE"),
  maximize = ifelse(metric %in% c("RMSE", "logLoss", "MAE"), FALSE, TRUE),
  trControl = trainControl(), tuneGrid = NULL,
  tuneLength = ifelse(trControl$method == "none", 1, 3))

Whereas the train.formula method does:

## S3 method for class 'formula'
train(form, data, ..., weights, subset, na.action = na.fail, contrasts = NULL)
                                        ^^^^^^^^^^^^^^^^^^^

If you add na.action = na.fail to your train.default call, x, y interface, do you get the same behaviour as the train.formula call?


问:
How do I set continuation tokens for Cosmos DB queries sent by document_client objects in Python?
I have an API that retrieves documents based on keywords that appear in document fields. I would like to paginate results so that I can return documents to a client sending a request, as well as allowing them to request more documents if they want. The query itself only takes a second or so in the browser when I am in the Azure Data Explorer, but it takes about a minute when I query using the Python DocumentDB library.

Looking at the Microsoft Cosmos DB REST API, it appears as if there are two tokens, x-ms_continuation and x-ms-max-item-count that are used.

It doesn't appear that putting these as entries in the options dictionary of document_client.QueryDocuments() does the trick.

In the GitHub repository, the Read() method references the options parameter:

```<code>    headers = base.GetHeaders(self,
                              initial_headers,
                              'get',
                              path,
                              id,
                              type,
                              options)
    # Read will use ReadEndpoint since it uses GET operation
    url_connection = self._global_endpoint_manager.ReadEndpoint
    result, self.last_response_headers = self.__Get(url_connection,
                                                    path,
                                                    headers)
</code>```

Looking in base.py, where the file is located, I saw these two blocks of code

```<code>if options.get('continuation'):
    headers[http_constants.HttpHeaders.Continuation] = (
        options['continuation'])

if options.get('maxItemCount'):
    headers[http_constants.HttpHeaders.PageSize] = options['maxItemCount']
</code>```

This would appear to correspond to the two parameters above. However, when I set them as options in the query ({'continuation':True,'maxItemCount':10}), nothing changes.

The final query looks like

```<code>client.QueryDocuments(collection_link, query, {'continuation':True,'maxItemCount':10})
</code>```

I have also tried using a string instead of an int for maxItemCount.

What am I doing incorrectly here?

Edit: The headers are the same as the two from the documentation above, from http_constants.py:

```<code># Our custom DocDB headers
Continuation = 'x-ms-continuation'
PageSize = 'x-ms-max-item-count'
</code>```

答:
The way continuation token works is that when you query documents and there are more documents available matching that query, service returns you a marker (or a token) that you need to include in your next query. That will tell the service to fetch the documents from that marker and not the beginning.

So in your code, the very 1st query will have no continuation parameter (or null). When you get the result, you should find if or not a token is returned from the service. If no token is returned that means there's no more data available. However if a token is returned, you should include that in your query options in the 2nd query.

Body:
I have an API that retrieves documents based on keywords that appear in document fields. I would like to paginate results so that I can return documents to a client sending a request, as well as allowing them to request more documents if they want. The query itself only takes a second or so in the browser when I am in the Azure Data Explorer, but it takes about a minute when I query using the Python DocumentDB library.

Looking at the Microsoft Cosmos DB REST API, it appears as if there are two tokens, x-ms_continuation and x-ms-max-item-count that are used.

It doesn't appear that putting these as entries in the options dictionary of document_client.QueryDocuments() does the trick.

In the GitHub repository, the Read() method references the options parameter:

    headers = base.GetHeaders(self,
                              initial_headers,
                              'get',
                              path,
                              id,
                              type,
                              options)
    # Read will use ReadEndpoint since it uses GET operation
    url_connection = self._global_endpoint_manager.ReadEndpoint
    result, self.last_response_headers = self.__Get(url_connection,
                                                    path,
                                                    headers)

Looking in base.py, where the file is located, I saw these two blocks of code

if options.get('continuation'):
    headers[http_constants.HttpHeaders.Continuation] = (
        options['continuation'])

if options.get('maxItemCount'):
    headers[http_constants.HttpHeaders.PageSize] = options['maxItemCount']

This would appear to correspond to the two parameters above. However, when I set them as options in the query ({'continuation':True,'maxItemCount':10}), nothing changes.

The final query looks like

client.QueryDocuments(collection_link, query, {'continuation':True,'maxItemCount':10})

I have also tried using a string instead of an int for maxItemCount.

What am I doing incorrectly here?

Edit: The headers are the same as the two from the documentation above, from http_constants.py:

# Our custom DocDB headers
Continuation = 'x-ms-continuation'
PageSize = 'x-ms-max-item-count'


问:
VB.net trying to access a UI element from seperate thread is not working
I have a rich text box in my main for that I want to write stuff to from different threads. I have tried to do this using invoking, but I can't seem to get it to work. If I try it with:

```<code>If InvokeRequired Then
    Dim Dgate As writeLogDelegate = New writeLogDelegate(AddressOf writeLog)
    BeginInvoke(Dgate, New Object() {Message})
Else
    RTB_Log.AppendText(Message)
End If
</code>```

then InvokeRequired does not return true like it should and checking if the handle is created returns false, but on form load, if I get the value of IsHandleCreated, it returns true. My method for trying to invoke writing is like so:

Thread Class snippet:

```<code>Public Sub startClientPoll(ByRef Sender As TcpListener)
    Dim TThread As New Thread(New ParameterizedThreadStart(AddressOf pollClientConnect))
    TThread.Start(Sender)
End Sub
Private Sub pollClientConnect(tcplistener As TcpListener)
    Do
        If tcplistener.Pending() Then
            'MessageBox.Show("")
            RaiseEvent clientConnecting()
        End If
    Loop Until Ended = True
End Sub
</code>```

Event handler class snippet:

```<code>Private Sub client_Connect() Handles listenerSocket.clientConnecting
    Form1.writeLog("New client awaiting accept" & vbNewLine)
    Dim clientSocket As TcpClient = listenerSocket.AcceptTcpClient()
    Dim clientHandler As New MPClientReciever(clientSocket)
End Sub
</code>```

Main form snippet:

```<code>Public Sub writeLog(ByVal Message As String)
    If Not IsHandleCreated Then
        CreateControl()
    End If
    If InvokeRequired Then
        Dim Dgate As writeLogDelegate = New writeLogDelegate(AddressOf writeLog)
        BeginInvoke(Dgate, New Object() {Message})
    Else
        RTB_Log.AppendText(Message)
    End If
End Sub
</code>```

答:
You can define a Sub globally on your class as the following:

```<code>Private Delegate Sub AddText_DL(ByVal txtControl As Control, ByVal txtVAL As String, ByVal append As Boolean)
Private Sub AddText(ByVal txtControl As Control, ByVal txtVAL As String, ByVal append As Boolean)
    If txtControl.InvokeRequired = True Then
        Dim progDel As New AddText_DL(AddressOf AddText)
        Dim parameters(2) As Object
        parameters(0) = txtControl
        parameters(1) = txtVAL
        parameters(2) = append
        txtControl.Invoke(progDel, parameters)
    Else
        If append = True Then
            txtControl.text &= txtVAL
        Else
            txtControl.text = txtVAL
        End If
    End If
End Sub
</code>```

To use it in different threads, call

```<code>AddText(MyTextBoxObject, "add this text please, don't append", False)
</code>```

And for your reference, if you want to access a UI control's property and get its set value, you can instead use:

```<code>Private Delegate Function CheckedStatus_DL(ByVal checkable As Control) As Boolean
Function CheckedStatus(ByVal checkable As Control) As Boolean
    If checkable.InvokeRequired = True Then
        Dim gridDel As New CheckedStatus_DL(AddressOf CheckedStatus)
        Dim parameters(0) As Object
        parameters(0) = checkable
        Return checkable.Invoke(gridDel, parameters)
    Else
        Return checkable.checked
    End If
End Function
</code>```

Also you can use this Function with any control that has .Checked property

Body:
I have a rich text box in my main for that I want to write stuff to from different threads. I have tried to do this using invoking, but I can't seem to get it to work. If I try it with:

If InvokeRequired Then
    Dim Dgate As writeLogDelegate = New writeLogDelegate(AddressOf writeLog)
    BeginInvoke(Dgate, New Object() {Message})
Else
    RTB_Log.AppendText(Message)
End If

then InvokeRequired does not return true like it should and checking if the handle is created returns false, but on form load, if I get the value of IsHandleCreated, it returns true. My method for trying to invoke writing is like so:

Thread Class snippet:

Public Sub startClientPoll(ByRef Sender As TcpListener)
    Dim TThread As New Thread(New ParameterizedThreadStart(AddressOf pollClientConnect))
    TThread.Start(Sender)
End Sub
Private Sub pollClientConnect(tcplistener As TcpListener)
    Do
        If tcplistener.Pending() Then
            'MessageBox.Show("")
            RaiseEvent clientConnecting()
        End If
    Loop Until Ended = True
End Sub

Event handler class snippet:

Private Sub client_Connect() Handles listenerSocket.clientConnecting
    Form1.writeLog("New client awaiting accept" & vbNewLine)
    Dim clientSocket As TcpClient = listenerSocket.AcceptTcpClient()
    Dim clientHandler As New MPClientReciever(clientSocket)
End Sub

Main form snippet:

Public Sub writeLog(ByVal Message As String)
    If Not IsHandleCreated Then
        CreateControl()
    End If
    If InvokeRequired Then
        Dim Dgate As writeLogDelegate = New writeLogDelegate(AddressOf writeLog)
        BeginInvoke(Dgate, New Object() {Message})
    Else
        RTB_Log.AppendText(Message)
    End If
End Sub

Body:
You can define a Sub globally on your class as the following:

Private Delegate Sub AddText_DL(ByVal txtControl As Control, ByVal txtVAL As String, ByVal append As Boolean)
Private Sub AddText(ByVal txtControl As Control, ByVal txtVAL As String, ByVal append As Boolean)
    If txtControl.InvokeRequired = True Then
        Dim progDel As New AddText_DL(AddressOf AddText)
        Dim parameters(2) As Object
        parameters(0) = txtControl
        parameters(1) = txtVAL
        parameters(2) = append
        txtControl.Invoke(progDel, parameters)
    Else
        If append = True Then
            txtControl.text &= txtVAL
        Else
            txtControl.text = txtVAL
        End If
    End If
End Sub

To use it in different threads, call

AddText(MyTextBoxObject, "add this text please, don't append", False)

And for your reference, if you want to access a UI control's property and get its set value, you can instead use:

Private Delegate Function CheckedStatus_DL(ByVal checkable As Control) As Boolean
Function CheckedStatus(ByVal checkable As Control) As Boolean
    If checkable.InvokeRequired = True Then
        Dim gridDel As New CheckedStatus_DL(AddressOf CheckedStatus)
        Dim parameters(0) As Object
        parameters(0) = checkable
        Return checkable.Invoke(gridDel, parameters)
    Else
        Return checkable.checked
    End If
End Function

Also you can use this Function with any control that has .Checked property


问:
SpreadsheetApp how to use variable inside formula
I want to be able to put my variable row into the

```<code>.setValue("=SUM(B54:BA54)")
</code>```

Actually I need the value of row to replace B54:B54. I'm looking for something like

```<code>.setValue("=SUM(B+row+:BA+row)")
</code>```

So if row = 50 the setValue will put =SUM(B50:BA50) in the cell

```<code>var text3 = result3.getResponseText();
var row = parseInt(text3);
activeSheet.getRange(row+3,55).setValue("=SUM(B54:BA54)");
</code>```

答:
```<code>var text3 = result3.getResponseText();
var row = parseInt(text3);
activeSheet.getRange(row+3,55).setValue("=SUM(B" + row + ":BA" + row + ")");
</code>```

using concatenation should work like you want it.

Body:
I want to be able to put my variable row into the

.setValue("=SUM(B54:BA54)")

Actually I need the value of row to replace B54:B54. I'm looking for something like

.setValue("=SUM(B+row+:BA+row)")

So if row = 50 the setValue will put =SUM(B50:BA50) in the cell

var text3 = result3.getResponseText();
var row = parseInt(text3);
activeSheet.getRange(row+3,55).setValue("=SUM(B54:BA54)");

Body:
var text3 = result3.getResponseText();
var row = parseInt(text3);
activeSheet.getRange(row+3,55).setValue("=SUM(B" + row + ":BA" + row + ")");

using concatenation should work like you want it.


问:
Can I make an R package available only to select users?
I'm developing several internal R packages for a team to make use of. However, I would like some of these packages to only be available to specific users. Is there any way of doing this within R, or do I need to resort to Windows directory locks?</p>

答:
R "knows" where packages are based on directories listed in its library path -- .libPaths() shows it, and can alter it -- as can other commands, see help(Startup).

You can have some control of what is available by adding to the .libPaths() directories which are mapped, or not, in the R startup -- when you can test for them in code. See $RHOME/etc/Rprofile.site. That way you are back to OS-level directory access and who gets to mount what...

In and by itself, R does not do authentication and permissioning at all.  Add-on products like RStudio (Server (Pro)) can, even with Active Directory and whatnot, but the Pro version is not free.


问:
Attempt to get length of null array on NfcManager.start()
I'm using react native v0.49 and installed react-native-nfc-manager .
when I try to use nfc I get the error

```<code>Attempt to get length of null array
</code>```

so I checked on the nfc folder and I find the issue into the plugin installation

```<code>@ReactMethod
public void start(Callback callback) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
    if (nfcAdapter != null) {
        Log.d(LOG_TAG, "start");
        callback.invoke(null);
    } else {
        Log.d(LOG_TAG, "not support in this device");
        callback.invoke("no nfc support");
    }
}
</code>```

as you can see when the nfcAdapter is not null it

```<code>callback.invoke(null)
</code>```

so here is the problem, so I tried to change it to

```<code>callback.invoke(LOG_TAG)
</code>```

and it's not show the error but I don't get any nfc tag, is show me undefined but not error.
what can i do?
here is all the NfcManager.java file

```<code>package community.revteltech.nfc;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import android.provider.Settings;
import com.facebook.react.bridge.*;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Parcelable;

import org.json.JSONObject;
import org.json.JSONException;

import java.util.*;

import static android.app.Activity.RESULT_OK;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;

class NfcManager extends ReactContextBaseJavaModule implements ActivityEventListener, LifecycleEventListener {
    private static final String LOG_TAG = "NfcManager";
    private final List<IntentFilter> intentFilters = new ArrayList<IntentFilter>();
    private final ArrayList<String[]> techLists = new ArrayList<String[]>();
    private Context context;
    private ReactApplicationContext reactContext;
    private Boolean isForegroundEnabled = false;
    private Boolean isResumed = false;

    public NfcManager(ReactApplicationContext reactContext) {
        super(reactContext);
        context = reactContext;
        this.reactContext = reactContext;
        reactContext.addActivityEventListener(this);
        reactContext.addLifecycleEventListener(this);
        Log.d(LOG_TAG, "NfcManager created");
    }

    @Override
    public String getName() {
        return "NfcManager";
    }

    @ReactMethod
    public void start(Callback callback) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
        if (nfcAdapter != null) {
            Log.d(LOG_TAG, "start");
            callback.invoke(null);
        } else {
            Log.d(LOG_TAG, "not support in this device");
            callback.invoke("no nfc support");
        }
    }

    @ReactMethod
    public void isEnabled(Callback callback) {
        Log.d(LOG_TAG, "isEnabled");
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
        if (nfcAdapter != null) {
            callback.invoke(null, nfcAdapter.isEnabled());
        } else {
            callback.invoke(null, false);
        }
    }

    @ReactMethod
    public void goToNfcSetting(Callback callback) {
        Log.d(LOG_TAG, "goToNfcSetting");
        Activity currentActivity = getCurrentActivity();
        currentActivity.startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
        callback.invoke();
    }

    @ReactMethod
    public void getLaunchTagEvent(Callback callback) {
        Activity currentActivity = getCurrentActivity();
        Intent launchIntent = currentActivity.getIntent();
        WritableMap nfcTag = parseNfcIntent(launchIntent);
        callback.invoke(null, nfcTag);
    }

    @ReactMethod
    private void registerTagEvent(Callback callback) {
        Log.d(LOG_TAG, "registerTag");
        isForegroundEnabled = true;

        // capture all mime-based dispatch NDEF
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        intentFilters.add(ndef);

        // capture all rest NDEF, such as uri-based
        intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED));
        techLists.add(new String[]{Ndef.class.getName()});

        // for those without NDEF, get them as tags
        intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED));

        if (isResumed) {
            enableDisableForegroundDispatch(true);
        }
        callback.invoke();
    }

    @ReactMethod
    private void unregisterTagEvent(Callback callback) {
        Log.d(LOG_TAG, "registerTag");
        isForegroundEnabled = false;
        intentFilters.clear();
        if (isResumed) {
            enableDisableForegroundDispatch(false);
        }
        callback.invoke();
    }

    @Override
    public void onHostResume() {
        Log.d(LOG_TAG, "onResume");
        isResumed = true;
        if (isForegroundEnabled) {
            enableDisableForegroundDispatch(true);
        }
    }

    @Override
    public void onHostPause() {
        Log.d(LOG_TAG, "onPause");
        isResumed = false;
        enableDisableForegroundDispatch(false);
    }

    @Override
    public void onHostDestroy() {
        Log.d(LOG_TAG, "onDestroy");
    }

    private void enableDisableForegroundDispatch(boolean enable) {
        Log.i(LOG_TAG, "enableForegroundDispatch, enable = " + enable);
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
        Activity currentActivity = getCurrentActivity();

        if (nfcAdapter != null && !currentActivity.isFinishing()) {
            try {
                if (enable) {
                    nfcAdapter.enableForegroundDispatch(currentActivity, getPendingIntent(), getIntentFilters(), getTechLists());
                } else {
                    nfcAdapter.disableForegroundDispatch(currentActivity);
                }
            } catch (IllegalStateException e) {
                Log.w(LOG_TAG, "Illegal State Exception starting NFC. Assuming application is terminating.");
            }
        }
    }

    private PendingIntent getPendingIntent() {
        Activity activity = getCurrentActivity();
        Intent intent = new Intent(activity, activity.getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return PendingIntent.getActivity(activity, 0, intent, 0);
    }

    private IntentFilter[] getIntentFilters() {
        return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
    }

    private String[][] getTechLists() {
        return techLists.toArray(new String[0][0]);
    }

    private void sendEvent(String eventName,
    @Nullable WritableMap params) {
        getReactApplicationContext()
        .getJSModule(RCTNativeAppEventEmitter.class)
        .emit(eventName, params);
    }

    private void sendEventWithJson(String eventName,
    JSONObject json) {
        try {
            WritableMap map = JsonConvert.jsonToReact(json);
            sendEvent(eventName, map);
        } catch (JSONException ex) {
            Log.d(LOG_TAG, "fireNdefEvent fail: " + ex);
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(LOG_TAG, "onReceive " + intent);
        }
    };

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        Log.d(LOG_TAG, "onActivityResult");
    }

    @Override
    public void onNewIntent(Intent intent) {
        Log.d(LOG_TAG, "onNewIntent " + intent);
        WritableMap nfcTag = parseNfcIntent(intent);
        if (nfcTag != null) {
            sendEvent("NfcManagerDiscoverTag", nfcTag);
        }
    }

    private WritableMap parseNfcIntent(Intent intent) {
        Log.d(LOG_TAG, "parseIntent " + intent);
        String action = intent.getAction();
        Log.d(LOG_TAG, "action " + action);
        if (action == null) {
            return null;
        }

        WritableMap parsed = null;
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        // Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES));

        if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
            Ndef ndef = Ndef.get(tag);
            Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES));
            parsed = ndef2React(ndef, messages);
        } else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
            for (String tagTech : tag.getTechList()) {
                Log.d(LOG_TAG, tagTech);
                if (tagTech.equals(NdefFormatable.class.getName())) {
                    // fireNdefFormatableEvent(tag);
                } else if (tagTech.equals(Ndef.class.getName())) { //
                    Ndef ndef = Ndef.get(tag);
                    parsed = ndef2React(ndef, new NdefMessage[] { ndef.getCachedNdefMessage() });
                }
            }
        } else if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
            parsed = tag2React(tag);
        }

        return parsed;
    }

    private WritableMap tag2React(Tag tag) {
        try {
            JSONObject json = Util.tagToJSON(tag);
            return JsonConvert.jsonToReact(json);
        } catch (JSONException ex) {
            return null;
        }

    }

    private WritableMap ndef2React(Ndef ndef, Parcelable[] messages) {
        try {
            JSONObject json = buildNdefJSON(ndef, messages);
            return JsonConvert.jsonToReact(json);
        } catch (JSONException ex) {
            return null;
        }
    }

    JSONObject buildNdefJSON(Ndef ndef, Parcelable[] messages) {
        JSONObject json = Util.ndefToJSON(ndef);

        // ndef is null for peer-to-peer
        // ndef and messages are null for ndef format-able
        if (ndef == null && messages != null) {

            try {

                if (messages.length > 0) {
                    NdefMessage message = (NdefMessage) messages[0];
                    json.put("ndefMessage", Util.messageToJSON(message));
                    // guessing type, would prefer a more definitive way to determine type
                    json.put("type", "NDEF Push Protocol");
                }

                if (messages.length > 1) {
                    Log.d(LOG_TAG, "Expected one ndefMessage but found " + messages.length);
                }

            } catch (JSONException e) {
                // shouldn't happen
                Log.e(Util.TAG, "Failed to convert ndefMessage into json", e);
            }
        }
        return json;
    }

}
</code>```

my nfc component

```<code>import React, { Component } from 'react';
import {
    View,
    Text,
    Button,
    Platform,
    TouchableOpacity,
    Linking
} from 'react-native';
import NfcManager, {NdefParser} from 'react-native-nfc-manager';

class NFC extends Component {
    constructor(props) {
        super(props);
        this.state = {
            supported: true,
            enabled: false,
            tag: {},
        }
    }

    componentDidMount() {
        NfcManager.start({
            onSessionClosedIOS: () => {
                console.log('ios session closed');
            }
        })
        .then(result => {
            console.log('start OK', result);
        })
        .catch(error => {
            console.warn('start fail', error);
            this.setState({supported: false});
        })

        if (Platform.OS === 'android') {
            NfcManager.getLaunchTagEvent()
            .then(tag => {
                console.log('launch tag', tag);
                if (tag) {
                    this.setState({ tag });
                }
            })
            .catch(err => {
                console.log(err);
            })
            NfcManager.isEnabled()
            .then(enabled => {
                this.setState({ enabled });
            })
            .catch(err => {
                console.log(err);
            })
        }
    }

    render() {
        let { supported, enabled, tag } = this.state;
        return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>{`Is NFC supported ? ${supported}`}</Text>
        <Text>{`Is NFC enabled (Android only)? ${enabled}`}</Text>

        <TouchableOpacity style={{ marginTop: 20 }} onPress={this._startDetection}>
        <Text style={{ color: 'blue' }}>Start Tag Detection</Text>
        </TouchableOpacity>

        <TouchableOpacity style={{ marginTop: 20 }} onPress={this._stopDetection}>
        <Text style={{ color: 'red' }}>Stop Tag Detection</Text>
        </TouchableOpacity>

        <TouchableOpacity style={{ marginTop: 20 }} onPress={this._clearMessages}>
        <Text>Clear</Text>
        </TouchableOpacity>

        <TouchableOpacity style={{ marginTop: 20 }} onPress={this._goToNfcSetting}>
        <Text >Go to NFC setting</Text>
        </TouchableOpacity>

        <Text style={{ marginTop: 20 }}>{`Current tag JSON: ${JSON.stringify(tag)}`}</Text>
        </View>
        )
    }

    _onTagDiscovered = tag => {
        console.log('Tag Discovered', tag);
        this.setState({ tag });
        let url = this._parseUri(tag);
        if (url) {
            Linking.openURL(url)
            .catch(err => {
                console.warn(err);
            })
        }
    }

    _startDetection = () => {
        NfcManager.registerTagEvent(this._onTagDiscovered)
        .then(result => {
            console.log('registerTagEvent OK', result)
        })
        .catch(error => {
            console.warn('registerTagEvent fail', error)
        })
    }

    _stopDetection = () => {
        NfcManager.unregisterTagEvent()
        .then(result => {
            console.log('unregisterTagEvent OK', result)
        })
        .catch(error => {
            console.warn('unregisterTagEvent fail', error)
        })
    }

    _clearMessages = () => {
        this.setState({tag: null});
    }

    _goToNfcSetting = () => {
        if (Platform.OS === 'android') {
            NfcManager.goToNfcSetting()
            .then(result => {
                console.log('goToNfcSetting OK', result)
            })
            .catch(error => {
                console.warn('goToNfcSetting fail', error)
            })
        }
    }

    _parseUri = (tag) => {
        let result = NdefParser.parseUri(tag.ndefMessage[0]),
        uri = result && result.uri;
        if (uri) {
            console.log('parseUri: ' + uri);
            return uri;
        }
        return null;
    }
}
export default NFC;
</code>```

答:
Be careful, NFC could not be available in all devices, so you have to check first:

```<code>  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
     if (nfcAdapter == null){
        Toast.makeText(this, "NFC not available", Toast.LENGTH_SHORT).show();
        return;
     }else{
          Toast.makeText(this, "NFC is avalable", Toast.LENGTH_SHORT).show();
     }
     ....
     ....
 }
</code>```

If NFC is not present that will be the reason to get the error message:

Attempt to get length of null array on NfcManager.start()

Body:
I'm using react native v0.49 and installed react-native-nfc-manager .
when I try to use nfc I get the error

Attempt to get length of null array

so I checked on the nfc folder and I find the issue into the plugin installation

@ReactMethod
public void start(Callback callback) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
    if (nfcAdapter != null) {
        Log.d(LOG_TAG, "start");
        callback.invoke(null);
    } else {
        Log.d(LOG_TAG, "not support in this device");
        callback.invoke("no nfc support");
    }
}

as you can see when the nfcAdapter is not null it

callback.invoke(null)

so here is the problem, so I tried to change it to

callback.invoke(LOG_TAG)

and it's not show the error but I don't get any nfc tag, is show me undefined but not error.
what can i do?
here is all the NfcManager.java file

package community.revteltech.nfc;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import android.provider.Settings;
import com.facebook.react.bridge.*;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Parcelable;

import org.json.JSONObject;
import org.json.JSONException;

import java.util.*;

import static android.app.Activity.RESULT_OK;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;

class NfcManager extends ReactContextBaseJavaModule implements ActivityEventListener, LifecycleEventListener {
    private static final String LOG_TAG = "NfcManager";
    private final List<IntentFilter> intentFilters = new ArrayList<IntentFilter>();
    private final ArrayList<String[]> techLists = new ArrayList<String[]>();
    private Context context;
    private ReactApplicationContext reactContext;
    private Boolean isForegroundEnabled = false;
    private Boolean isResumed = false;

    public NfcManager(ReactApplicationContext reactContext) {
        super(reactContext);
        context = reactContext;
        this.reactContext = reactContext;
        reactContext.addActivityEventListener(this);
        reactContext.addLifecycleEventListener(this);
        Log.d(LOG_TAG, "NfcManager created");
    }

    @Override
    public String getName() {
        return "NfcManager";
    }

    @ReactMethod
    public void start(Callback callback) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
        if (nfcAdapter != null) {
            Log.d(LOG_TAG, "start");
            callback.invoke(null);
        } else {
            Log.d(LOG_TAG, "not support in this device");
            callback.invoke("no nfc support");
        }
    }

    @ReactMethod
    public void isEnabled(Callback callback) {
        Log.d(LOG_TAG, "isEnabled");
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
        if (nfcAdapter != null) {
            callback.invoke(null, nfcAdapter.isEnabled());
        } else {
            callback.invoke(null, false);
        }
    }

    @ReactMethod
    public void goToNfcSetting(Callback callback) {
        Log.d(LOG_TAG, "goToNfcSetting");
        Activity currentActivity = getCurrentActivity();
        currentActivity.startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
        callback.invoke();
    }

    @ReactMethod
    public void getLaunchTagEvent(Callback callback) {
        Activity currentActivity = getCurrentActivity();
        Intent launchIntent = currentActivity.getIntent();
        WritableMap nfcTag = parseNfcIntent(launchIntent);
        callback.invoke(null, nfcTag);
    }

    @ReactMethod
    private void registerTagEvent(Callback callback) {
        Log.d(LOG_TAG, "registerTag");
        isForegroundEnabled = true;

        // capture all mime-based dispatch NDEF
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        intentFilters.add(ndef);

        // capture all rest NDEF, such as uri-based
        intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED));
        techLists.add(new String[]{Ndef.class.getName()});

        // for those without NDEF, get them as tags
        intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED));

        if (isResumed) {
            enableDisableForegroundDispatch(true);
        }
        callback.invoke();
    }

    @ReactMethod
    private void unregisterTagEvent(Callback callback) {
        Log.d(LOG_TAG, "registerTag");
        isForegroundEnabled = false;
        intentFilters.clear();
        if (isResumed) {
            enableDisableForegroundDispatch(false);
        }
        callback.invoke();
    }

    @Override
    public void onHostResume() {
        Log.d(LOG_TAG, "onResume");
        isResumed = true;
        if (isForegroundEnabled) {
            enableDisableForegroundDispatch(true);
        }
    }

    @Override
    public void onHostPause() {
        Log.d(LOG_TAG, "onPause");
        isResumed = false;
        enableDisableForegroundDispatch(false);
    }

    @Override
    public void onHostDestroy() {
        Log.d(LOG_TAG, "onDestroy");
    }

    private void enableDisableForegroundDispatch(boolean enable) {
        Log.i(LOG_TAG, "enableForegroundDispatch, enable = " + enable);
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
        Activity currentActivity = getCurrentActivity();

        if (nfcAdapter != null && !currentActivity.isFinishing()) {
            try {
                if (enable) {
                    nfcAdapter.enableForegroundDispatch(currentActivity, getPendingIntent(), getIntentFilters(), getTechLists());
                } else {
                    nfcAdapter.disableForegroundDispatch(currentActivity);
                }
            } catch (IllegalStateException e) {
                Log.w(LOG_TAG, "Illegal State Exception starting NFC. Assuming application is terminating.");
            }
        }
    }

    private PendingIntent getPendingIntent() {
        Activity activity = getCurrentActivity();
        Intent intent = new Intent(activity, activity.getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return PendingIntent.getActivity(activity, 0, intent, 0);
    }

    private IntentFilter[] getIntentFilters() {
        return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
    }

    private String[][] getTechLists() {
        return techLists.toArray(new String[0][0]);
    }

    private void sendEvent(String eventName,
    @Nullable WritableMap params) {
        getReactApplicationContext()
        .getJSModule(RCTNativeAppEventEmitter.class)
        .emit(eventName, params);
    }

    private void sendEventWithJson(String eventName,
    JSONObject json) {
        try {
            WritableMap map = JsonConvert.jsonToReact(json);
            sendEvent(eventName, map);
        } catch (JSONException ex) {
            Log.d(LOG_TAG, "fireNdefEvent fail: " + ex);
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(LOG_TAG, "onReceive " + intent);
        }
    };

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        Log.d(LOG_TAG, "onActivityResult");
    }

    @Override
    public void onNewIntent(Intent intent) {
        Log.d(LOG_TAG, "onNewIntent " + intent);
        WritableMap nfcTag = parseNfcIntent(intent);
        if (nfcTag != null) {
            sendEvent("NfcManagerDiscoverTag", nfcTag);
        }
    }

    private WritableMap parseNfcIntent(Intent intent) {
        Log.d(LOG_TAG, "parseIntent " + intent);
        String action = intent.getAction();
        Log.d(LOG_TAG, "action " + action);
        if (action == null) {
            return null;
        }

        WritableMap parsed = null;
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        // Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES));

        if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
            Ndef ndef = Ndef.get(tag);
            Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES));
            parsed = ndef2React(ndef, messages);
        } else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
            for (String tagTech : tag.getTechList()) {
                Log.d(LOG_TAG, tagTech);
                if (tagTech.equals(NdefFormatable.class.getName())) {
                    // fireNdefFormatableEvent(tag);
                } else if (tagTech.equals(Ndef.class.getName())) { //
                    Ndef ndef = Ndef.get(tag);
                    parsed = ndef2React(ndef, new NdefMessage[] { ndef.getCachedNdefMessage() });
                }
            }
        } else if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
            parsed = tag2React(tag);
        }

        return parsed;
    }

    private WritableMap tag2React(Tag tag) {
        try {
            JSONObject json = Util.tagToJSON(tag);
            return JsonConvert.jsonToReact(json);
        } catch (JSONException ex) {
            return null;
        }

    }

    private WritableMap ndef2React(Ndef ndef, Parcelable[] messages) {
        try {
            JSONObject json = buildNdefJSON(ndef, messages);
            return JsonConvert.jsonToReact(json);
        } catch (JSONException ex) {
            return null;
        }
    }

    JSONObject buildNdefJSON(Ndef ndef, Parcelable[] messages) {
        JSONObject json = Util.ndefToJSON(ndef);

        // ndef is null for peer-to-peer
        // ndef and messages are null for ndef format-able
        if (ndef == null && messages != null) {

            try {

                if (messages.length > 0) {
                    NdefMessage message = (NdefMessage) messages[0];
                    json.put("ndefMessage", Util.messageToJSON(message));
                    // guessing type, would prefer a more definitive way to determine type
                    json.put("type", "NDEF Push Protocol");
                }

                if (messages.length > 1) {
                    Log.d(LOG_TAG, "Expected one ndefMessage but found " + messages.length);
                }

            } catch (JSONException e) {
                // shouldn't happen
                Log.e(Util.TAG, "Failed to convert ndefMessage into json", e);
            }
        }
        return json;
    }

}

my nfc component

import React, { Component } from 'react';
import {
    View,
    Text,
    Button,
    Platform,
    TouchableOpacity,
    Linking
} from 'react-native';
import NfcManager, {NdefParser} from 'react-native-nfc-manager';

class NFC extends Component {
    constructor(props) {
        super(props);
        this.state = {
            supported: true,
            enabled: false,
            tag: {},
        }
    }

    componentDidMount() {
        NfcManager.start({
            onSessionClosedIOS: () => {
                console.log('ios session closed');
            }
        })
        .then(result => {
            console.log('start OK', result);
        })
        .catch(error => {
            console.warn('start fail', error);
            this.setState({supported: false});
        })

        if (Platform.OS === 'android') {
            NfcManager.getLaunchTagEvent()
            .then(tag => {
                console.log('launch tag', tag);
                if (tag) {
                    this.setState({ tag });
                }
            })
            .catch(err => {
                console.log(err);
            })
            NfcManager.isEnabled()
            .then(enabled => {
                this.setState({ enabled });
            })
            .catch(err => {
                console.log(err);
            })
        }
    }

    render() {
        let { supported, enabled, tag } = this.state;
        return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>{`Is NFC supported ? ${supported}`}</Text>
        <Text>{`Is NFC enabled (Android only)? ${enabled}`}</Text>

        <TouchableOpacity style={{ marginTop: 20 }} onPress={this._startDetection}>
        <Text style={{ color: 'blue' }}>Start Tag Detection</Text>
        </TouchableOpacity>

        <TouchableOpacity style={{ marginTop: 20 }} onPress={this._stopDetection}>
        <Text style={{ color: 'red' }}>Stop Tag Detection</Text>
        </TouchableOpacity>

        <TouchableOpacity style={{ marginTop: 20 }} onPress={this._clearMessages}>
        <Text>Clear</Text>
        </TouchableOpacity>

        <TouchableOpacity style={{ marginTop: 20 }} onPress={this._goToNfcSetting}>
        <Text >Go to NFC setting</Text>
        </TouchableOpacity>

        <Text style={{ marginTop: 20 }}>{`Current tag JSON: ${JSON.stringify(tag)}`}</Text>
        </View>
        )
    }

    _onTagDiscovered = tag => {
        console.log('Tag Discovered', tag);
        this.setState({ tag });
        let url = this._parseUri(tag);
        if (url) {
            Linking.openURL(url)
            .catch(err => {
                console.warn(err);
            })
        }
    }

    _startDetection = () => {
        NfcManager.registerTagEvent(this._onTagDiscovered)
        .then(result => {
            console.log('registerTagEvent OK', result)
        })
        .catch(error => {
            console.warn('registerTagEvent fail', error)
        })
    }

    _stopDetection = () => {
        NfcManager.unregisterTagEvent()
        .then(result => {
            console.log('unregisterTagEvent OK', result)
        })
        .catch(error => {
            console.warn('unregisterTagEvent fail', error)
        })
    }

    _clearMessages = () => {
        this.setState({tag: null});
    }

    _goToNfcSetting = () => {
        if (Platform.OS === 'android') {
            NfcManager.goToNfcSetting()
            .then(result => {
                console.log('goToNfcSetting OK', result)
            })
            .catch(error => {
                console.warn('goToNfcSetting fail', error)
            })
        }
    }

    _parseUri = (tag) => {
        let result = NdefParser.parseUri(tag.ndefMessage[0]),
        uri = result && result.uri;
        if (uri) {
            console.log('parseUri: ' + uri);
            return uri;
        }
        return null;
    }
}
export default NFC;

Body:
Be careful, NFC could not be available in all devices, so you have to check first:

  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
     if (nfcAdapter == null){
        Toast.makeText(this, "NFC not available", Toast.LENGTH_SHORT).show();
        return;
     }else{
          Toast.makeText(this, "NFC is avalable", Toast.LENGTH_SHORT).show();
     }
     ....
     ....
 }

If NFC is not present that will be the reason to get the error message:

Attempt to get length of null array on NfcManager.start()


问:
Attempt to connect to MS SQL Server with sql alchemy throwing error that user is empty string
Trying to connect to a MS SQL Server database with odbc and sqlalchemy to write a pandas.DataFrame to the database and getting an error that seems to imply that the user being used is an empty string (when one is provided the the connection string). Why would this be?

The relevant code snippet is:

```<code>import sqlalchemy

# setup db connection
server = 'myserver'
database = 'mydb'
table = 'mytable'
username = 'username'
password = 'password'
cnxn_str = 'DSN=MyMSSQLServer;DATABASE='+database+';UID='+username+';PWD='+password+';MultipleActiveResultSets=True;'

engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % cnxn_str)

# testing connection
cnxn = engine.connect()
...
</code>```

and the (abridged) error message thrown is:

```<code>---------------------------------------------------------------------------
InterfaceError                            Traceback (most recent call last)
<ipython-input-207-6807f223c9bb> in <module>()
     15
     16 #Sample select query
---> 17 cnxn = engine.connect()
     18 result = connection.execute("SELECT @@version;")
     19 for row in result:

/home/mapr/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py in connect(self, **kwargs)
   2016         """
   2017
-> 2018         return self._connection_cls(self, **kwargs)
   2019
   2020     def contextual_connect(self, close_with_result=False, **kwargs):
...
...
/home/mapr/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/strategies.py in connect(connection_record)
     95                         if connection is not None:
     96                             return connection
---> 97                 return dialect.connect(*cargs, **cparams)
     98
     99             creator = pop_kwarg('creator', connect)

/home/mapr/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/default.py in connect(self, *cargs, **cparams)
    383
    384     def connect(self, *cargs, **cparams):
--> 385         return self.dbapi.connect(*cargs, **cparams)
    386
    387     def create_connect_args(self, url):

InterfaceError: (pyodbc.InterfaceError) ('28000', u"[28000] [unixODBC][Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user ''. (18456) (SQLDriverConnect)")
</code>```

What is also weird to me is that this same connection string works successfully earlier in the code when used to read from the same sql server, but in that case using cnxn = pyodbc.connect(cnxn_str) to establish connection (would do the same here, but according to the docs I need to use sqlalchemy if I want to write to anything other than sqlite3).

Can anyone explain why this is happening and how to fix it? Thanks.

答:
Try to do it in a more "SQL Alchemy" way:

```<code># pyodbc
engine = sqlalchemy.create_engine('mssql+pyodbc://{}:{}@MyMSSQLServer'.format(username, password ))
</code>```

or

```<code># pymssql
engine = sqlalchemy.create_engine('mssql+pymssql://{}:{}@{}:{}/{}'.format(username, password, server, port, database))
</code>```

Body:
Trying to connect to a MS SQL Server database with odbc and sqlalchemy to write a pandas.DataFrame to the database and getting an error that seems to imply that the user being used is an empty string (when one is provided the the connection string). Why would this be?

The relevant code snippet is:

import sqlalchemy

# setup db connection
server = 'myserver'
database = 'mydb'
table = 'mytable'
username = 'username'
password = 'password'
cnxn_str = 'DSN=MyMSSQLServer;DATABASE='+database+';UID='+username+';PWD='+password+';MultipleActiveResultSets=True;'

engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % cnxn_str)

# testing connection
cnxn = engine.connect()
...

and the (abridged) error message thrown is:

---------------------------------------------------------------------------
InterfaceError                            Traceback (most recent call last)
<ipython-input-207-6807f223c9bb> in <module>()
     15
     16 #Sample select query
---> 17 cnxn = engine.connect()
     18 result = connection.execute("SELECT @@version;")
     19 for row in result:

/home/mapr/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py in connect(self, **kwargs)
   2016         """
   2017
-> 2018         return self._connection_cls(self, **kwargs)
   2019
   2020     def contextual_connect(self, close_with_result=False, **kwargs):
...
...
/home/mapr/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/strategies.py in connect(connection_record)
     95                         if connection is not None:
     96                             return connection
---> 97                 return dialect.connect(*cargs, **cparams)
     98
     99             creator = pop_kwarg('creator', connect)

/home/mapr/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/default.py in connect(self, *cargs, **cparams)
    383
    384     def connect(self, *cargs, **cparams):
--> 385         return self.dbapi.connect(*cargs, **cparams)
    386
    387     def create_connect_args(self, url):

InterfaceError: (pyodbc.InterfaceError) ('28000', u"[28000] [unixODBC][Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user ''. (18456) (SQLDriverConnect)")

What is also weird to me is that this same connection string works successfully earlier in the code when used to read from the same sql server, but in that case using cnxn = pyodbc.connect(cnxn_str) to establish connection (would do the same here, but according to the docs I need to use sqlalchemy if I want to write to anything other than sqlite3).

Can anyone explain why this is happening and how to fix it? Thanks.

Body:
Try to do it in a more "SQL Alchemy" way:

# pyodbc
engine = sqlalchemy.create_engine('mssql+pyodbc://{}:{}@MyMSSQLServer'.format(username, password ))

or

# pymssql
engine = sqlalchemy.create_engine('mssql+pymssql://{}:{}@{}:{}/{}'.format(username, password, server, port, database))


问:
SSRS Report Render report in PDF Via URL
I have an SSRS2016 Report that I'm able to connect to in the browser:
http://vmbksa69901mcz/reports_ssrs1d/report/DAS/CDO_Suite/AccruedInterestRpt

But I want to be able to export to pdf by the url. This article states that this is possible:
https://learn.microsoft.com/en-us/sql/reporting-services/export-a-report-using-url-access

So, when I try to put in this url:
http://vmbksa69901mcz/reports_ssrs1d?/DAS/CDO_Suite/AccruedInterestRpt&rs:Format=PDF

It does not work.. It just brings me to the home page of the SSRS Site, and changes the url to:
http://vmbksa69901mcz/reports_ssrs1d/browse/

I don't see what I'm doing wrong here.

答:
When you use a URL to pass commands you need to use the Web Service URL reportserver path in the URL not the web portals URL.

If you run the Reporting Services Configuration Manager and look under "Web Service URL" you see a different address.

By default the web portal (SSRS home page as you called it) will be at http://myServer/Reports

But the Web Service URL by default is
http://myServer/Reportserver


问:
Getting ping error with aptana plugin for STS
I am getting a weird ping error with the aptana studio plugin and eclipse?  Has anyone else hit this issue?

the error is:
An internal error occurred during: "Sending Ping...".
java.lang.NullPointerException

答:
go to Window > Preferences > General > Startup and Shutdown and deactivate “Aptana Studio Core User Interface”

More notes here: https://aptanastudio.tenderapp.com/discussions/problems/472-aptana-studio-20-sending-ping-error-on-startup/page/1

ContentLicense: CC BY-SA 2.5


问:
C++ error: no match for call to '(std::list<int>) (int&)'
I have a piece of script to count the highest possible sum of list elements while retaining the pattern: higher-lower-higher-lower-higher etc.

```<code>#include <algorithm>
#include <stdio.h>
#include <list>

using namespace std;

int main() {
    int n=0;
    bool g = false;
    int d = 1000000;
    list<int> a(d,0);
    int b;

    for (int x=0; x<n; x++) {  //load the list elements
        scanf("%d", &b);
        a.push_back(b);
    }

    for (int i=0; a(n) == a(n+1); i++) {
        a.remove(n+1);  //this is to remove any (consecutive) duplicates
    }

    if (a(n) > a(n+1)) {
        g = false;
    } else {
        g = true;
    }

while (n+1 < d) {
    if (g) {
        if (!(a(n) < a(n+1))) {
            a.remove(n+1);
            continue;
        } else {
            n = n+1;
            g = !g;
            continue;
        }
    } else {
        if (!(a(n) > a(n+1))) {
            a.remove(n+1);
        } else {
            n = n+1;
            g = !g;
            continue;
        }
    }
}
long long sum = 0 ;
for (int i = 0 ; i < a.count(); i++) {
   sum += a(i);
}

printf("%lld ", sum);

return 0;
}
</code>```

However, at compilation attempt it throws no match for call to '(std::list<int>) (int&)' everywhere where I am trying to compare list elements.

What am I doing wrong?

答:
a(n) is not valid.  std::list does not have a call operator (or a subscript operator, which is what I assume you intended to use).  std::list does not provide random access.

If you need random access, use a container that provides it, such as std::vector.  Then you can access items using a[n] notation.

Body:
I have a piece of script to count the highest possible sum of list elements while retaining the pattern: higher-lower-higher-lower-higher etc.

#include <algorithm>
#include <stdio.h>
#include <list>

using namespace std;

int main() {
    int n=0;
    bool g = false;
    int d = 1000000;
    list<int> a(d,0);
    int b;

    for (int x=0; x<n; x++) {  //load the list elements
        scanf("%d", &b);
        a.push_back(b);
    }

    for (int i=0; a(n) == a(n+1); i++) {
        a.remove(n+1);  //this is to remove any (consecutive) duplicates
    }

    if (a(n) > a(n+1)) {
        g = false;
    } else {
        g = true;
    }

while (n+1 < d) {
    if (g) {
        if (!(a(n)  a(n+1))) {
            a.remove(n+1);
        } else {
            n = n+1;
            g = !g;
            continue;
        }
    }
}
long long sum = 0 ;
for (int i = 0 ; i < a.count(); i++) {
   sum += a(i);
}

printf("%lld ", sum);

return 0;
}

However, at compilation attempt it throws no match for call to '(std::list<int>) (int&)' everywhere where I am trying to compare list elements.

What am I doing wrong?


问:
vba check if subform is on screen
I want to call a function that updates the Content of a subform, only if the spefic subform is visible on screen. I tried it with .IsLoaded but this seems not to work. At least not like this:

```<code>If CurrentProject.AllForms(frm_BT_Halbzeug.Form.loadHalbzeug(Me.hidden_bauteil_id)).IsLoaded Then
        Call Me.frm_BT_Halbzeug.Form.loadHalbzeug(Me.hidden_bauteil_id)
End If
</code>```

Unfortunately the subform is called everytime I update the mainform. How can I correct this? Help is appreciated.
Best regards,
Eric

答:
```<code>Dim obj As AccessObject
Dim dbs As Object

Set dbs = Application.CurrentProject

' Search for open AccessObject objects in AllForms collection.
For Each obj In dbs.AllForms
    If obj.IsLoaded = True Then
        'Debug.Print obj.Name
        If obj.Name = "frmSubform" Then    'your main form
            If Forms!frmSubform!sfrmSubform.Form.Visible Then    'subform
                'Debug.Print "visible"
                 'do something.
            Else
                'Debug.Print "not visible"
            End If
        End If
    End If
Next obj

Set dbs = Nothing
</code>```

Title: vba check if subform is on screen

Body:
I want to call a function that updates the Content of a subform, only if the spefic subform is visible on screen. I tried it with .IsLoaded but this seems not to work. At least not like this:

If CurrentProject.AllForms(frm_BT_Halbzeug.Form.loadHalbzeug(Me.hidden_bauteil_id)).IsLoaded Then
        Call Me.frm_BT_Halbzeug.Form.loadHalbzeug(Me.hidden_bauteil_id)
End If

Unfortunately the subform is called everytime I update the mainform. How can I correct this? Help is appreciated.
Best regards,
Eric


问:
c++ Printing from a struct
I'm working on something and the gist of what I have to do is essentially:

1) Declare a struct named partType that has two members: name (holds the name of a
part) and code (holds a whole number).

2) Declare two variables of type partType.

3) Prompt the user to enter the name and code of the first item and store them
into the corresponding variable.

4) Prompt the user to enter the name and code of the second item and store them
into the corresponding variable.

5) Compare the items by code and display an output like the one shown in the
examples below:

Example 1:
Enter name and code of item1: bolt 22222

Enter name and code of item2: nut 11111

bolt goes after nut in the inventory

Example 2:
Enter name and code of item1: bolt 11111

Enter name and code of item2: nut 22222

bolt goes before nut in the inventory

The current code that I have is:

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

using namespace std;

struct partType {
    string name;
    int code;
};

int main() {

    partType nam, num;

    cout << "enter name and code of item1: ";
    cin >> nam.name >> num.code;
    cout << "enter name and code for item2: ";
    cin >> nam.name >> num.code;

    if (num.code > num.code) {
        cout << nam.name << " goes after " << nam.name;
    }
    else if (num.code < num.code) {
        cout << nam.name << " goes before " << nam.name;
    }
    else {
        cout << "tie";
    }

    system("pause");
    return 0;
}
</code>```

I feel that I shouldn't be using the nam and num twice because it'll overwrite it but I'm not completely sure on how to fix it

答:
Reading your code, you seem to be mixing up your nam and num variables.

```<code>partType nam, num;
</code>```

This line creates two partType variables, one called nam and the other called num.

```<code>cout << "enter name and code of item1: ";
cin >> nam.name >> num.code;
</code>```

Watch out! You prompt for the name and code for the first item, but you place the input for the code into the second variable!

```<code>cout << "enter name and code for item2: ";
cin >> nam.name >> num.code;
</code>```

Instead of setting both fields of the second variable, num, you are only setting the code field of the second variable, but setting the name field of the first variable, and furthermore you are overwriting the data that was inputted from the first input prompt.

```<code>if (num.code > num.code) {
    cout << nam.name << " goes after " << nam.name;
}
else if (num.code < num.code) {
    cout << nam.name << " goes before " << nam.name;
}
</code>```

You are comparing an expression to itself. You should do num.code < nam.code and vice versa instead.

Title: c++ Printing from a struct

Body:
I'm working on something and the gist of what I have to do is essentially:

1) Declare a struct named partType that has two members: name (holds the name of a
part) and code (holds a whole number).

2) Declare two variables of type partType.

3) Prompt the user to enter the name and code of the first item and store them
into the corresponding variable.

4) Prompt the user to enter the name and code of the second item and store them
into the corresponding variable.

5) Compare the items by code and display an output like the one shown in the
examples below:

Example 1:
Enter name and code of item1: bolt 22222

Enter name and code of item2: nut 11111

bolt goes after nut in the inventory

Example 2:
Enter name and code of item1: bolt 11111

Enter name and code of item2: nut 22222

bolt goes before nut in the inventory

The current code that I have is:

#include <iostream>
#include <string>

using namespace std;

struct partType {
    string name;
    int code;
};

int main() {

    partType nam, num;

    cout << "enter name and code of item1: ";
    cin >> nam.name >> num.code;
    cout << "enter name and code for item2: ";
    cin >> nam.name >> num.code;

    if (num.code > num.code) {
        cout << nam.name << " goes after " << nam.name;
    }
    else if (num.code < num.code) {
        cout << nam.name << " goes before " << nam.name;
    }
    else {
        cout << "tie";
    }

    system("pause");
    return 0;
}

I feel that I shouldn't be using the nam and num twice because it'll overwrite it but I'm not completely sure on how to fix it

Body:
Reading your code, you seem to be mixing up your nam and num variables.

partType nam, num;

This line creates two partType variables, one called nam and the other called num.

cout << "enter name and code of item1: ";
cin >> nam.name >> num.code;

Watch out! You prompt for the name and code for the first item, but you place the input for the code into the second variable!

cout << "enter name and code for item2: ";
cin >> nam.name >> num.code;

Instead of setting both fields of the second variable, num, you are only setting the code field of the second variable, but setting the name field of the first variable, and furthermore you are overwriting the data that was inputted from the first input prompt.

if (num.code > num.code) {
    cout << nam.name << " goes after " << nam.name;
}
else if (num.code < num.code) {
    cout << nam.name << " goes before " << nam.name;
}

You are comparing an expression to itself. You should do num.code < nam.code and vice versa instead.


问:
Javascript functions related to HTML/CSS elements

FIXED! I CHANGED "#slide" to ".slide", that was the problem. Thanks everyone!

Hello, people of Stack Overflow. I have encountered a problem with my code, and it doesn't seem to be hiding the elements when it should be.

Javascript:

```<code>let sliderImages = document.querySelectorAll('#slide'),
     arrowRight = document.querySelector(".next"),
     arrowLeft = document.querySelector(".prev"),
     current = 0;
//            reset all images
function reset(){
    for(let i = 0; i < sliderImages.length; i++){
        // "let" means make a variable which will only be used in the LOCAL scope.
        sliderImages[i].style.display = "none";
    }
}
function startSlide(){
    reset();
}
startSlide();
function test(){
    console.log("hello!") // to prove that this file is running
}
test();
</code>```

The result I'm expecting is for all the images/things with div "#slide" to be invisible.

Instead, I get no change on the webpage. If posting the HTML would help, I will. I have checked, and I believe there to be no typos in the names.

答:
Element IDs must be unique on the page. You seem to have more than one #slide, so my suggestion is to change from ID to class, so your divs will be:

```<code><div class="slide">...</div>
</code>```

This way, you can select them by simply using:

```<code>let sliderImages = document.querySelectorAll('.slide');
</code>```

Then iterating over them with:

```<code>sliderImages.forEach(function(sliImg) {
  sliImg.style.display = "none";
});
</code>```

Body:
FIXED! I CHANGED "#slide" to ".slide", that was the problem. Thanks everyone!

Hello, people of Stack Overflow. I have encountered a problem with my code, and it doesn't seem to be hiding the elements when it should be.

Javascript:

let sliderImages = document.querySelectorAll('#slide'),
     arrowRight = document.querySelector(".next"),
     arrowLeft = document.querySelector(".prev"),
     current = 0;
//            reset all images
function reset(){
    for(let i = 0; i < sliderImages.length; i++){
        // "let" means make a variable which will only be used in the LOCAL scope.
        sliderImages[i].style.display = "none";
    }
}
function startSlide(){
    reset();
}
startSlide();
function test(){
    console.log("hello!") // to prove that this file is running
}
test();

The result I'm expecting is for all the images/things with div "#slide" to be invisible.

Instead, I get no change on the webpage. If posting the HTML would help, I will. I have checked, and I believe there to be no typos in the names.

Body:
Element IDs must be unique on the page. You seem to have more than one #slide, so my suggestion is to change from ID to class, so your divs will be:

<div class="slide">...</div>

This way, you can select them by simply using:

let sliderImages = document.querySelectorAll('.slide');

Then iterating over them with:

sliderImages.forEach(function(sliImg) {
  sliImg.style.display = "none";
});


问:
Retrieve the minimum value of a column from the max value of another column
I have a hive table t1 that looks like this:

```
ID   Score1    score2
1     4         11
1     5         12
1     5         13
2     3         14
2     3         15
2     2         12
2     2         11
3     6         10
3     6         11
3     6         12
```

I want for each ID, to select the max value of score1, and if the max value exists more than once, then from the rows that contain max(score1) I want to get min(score2).

So, I want the minimum score2 of the maximum score1 rows, the results should be something like this

```
ID    Score1    score2
1     5         12
2     3         14
3     6         10
```

Most of the ideas I have turn this to be a very complicated query, and I think there is a simple solution for it that I am not able to find yet.

Any ideas?

答:
```<code>select id, min(score2)
from table1 t
inner join (
   select id, max(score1) maxscore1 group by id
    )  d on t.id = d.id and t.score1 = d.maxscore1
group by t.id
having count(*) > 1 # if the max value exists more than once
</code>```

an alternative query, if the db does support "analyic functions", is

```<code>select
     id, min(score2)
from (
      select id, score1, score2
            , count(case when score1 = max(score1) over(partition by id) then 1 end) count_max
      from table1
      ) d
where count_max > 1 -- if the max value exists more than once
group by
     id
</code>```

Body:
I have a hive table t1 that looks like this:

ID   Score1    score2
1     4         11
1     5         12
1     5         13
2     3         14
2     3         15
2     2         12
2     2         11
3     6         10
3     6         11
3     6         12

I want for each ID, to select the max value of score1, and if the max value exists more than once, then from the rows that contain max(score1) I want to get min(score2).

So, I want the minimum score2 of the maximum score1 rows, the results should be something like this

ID    Score1    score2
1     5         12
2     3         14
3     6         10

Most of the ideas I have turn this to be a very complicated query, and I think there is a simple solution for it that I am not able to find yet.

Any ideas?

Body:
select id, min(score2)
from table1 t
inner join (
   select id, max(score1) maxscore1 group by id
    )  d on t.id = d.id and t.score1 = d.maxscore1
group by t.id
having count(*) > 1 # if the max value exists more than once

an alternative query, if the db does support "analyic functions", is

select
     id, min(score2)
from (
      select id, score1, score2
            , count(case when score1 = max(score1) over(partition by id) then 1 end) count_max
      from table1
      ) d
where count_max > 1 -- if the max value exists more than once
group by
     id


问:
Users address logic in laravel
I have 2 tables in my laravel application users and addresses and both of them crud currently working, what i want to do is:

Set several address for each user (DONE)

Set Primary address (Ability of choose in order settings and profile page)

Question is:

Do I need 3rd table such as address_user to get user and address id or as it is now i just can add primary column to address table and let it be?

here is what i have:

user model

```<code>public function addresses(){
       return $this->hasMany(Address::class);
    }
</code>```

Address model

```<code>public function user(){
     return $this->belongsTo(User::class);
  }
</code>```

Address table

```<code>Schema::create('addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->string('address');
            $table->string('city');
            $table->string('postalcode')->nullable();
            $table->string('province');
            $table->integer('user_id')->unsigned();
            $table->timestamps();
        });
        Schema::table('addresses', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users');
        });
</code>```

This is how i print data currently in users index

```<code><td class="text-center">
  <ol>
    @foreach($user->addresses as $uad)
       <li>{{$uad->address}}<br>{{$uad->city}},{{$uad->postalcode}},{{$uad->province}}</li>
    @endforeach
  </ol>
</td>
</code>```

UPDATE

So base on suggestions I added column is_primary to my addresses table and I can set is to 0 and 1 in order to get users primary address, BUT

Now I am in my user edit page and i have 2 address belongs to user
  with id 1 now I want to change selected primary address to another
  address but i am in user profile edit how do I update my address table
  is_primary column while my form route is users.update and not addresses_update ?

UPDATE 2

I've made some changes and here it is:

Users table have address_id column

Addresses table NO HAVE is_primary column anymore.
why? because user could set many address as primary! with this way user only can set 1 address as primary which will get id of that address.

Issue

1- I cannot get user primary address (don't know how!)

here is how i get user addresses:

```<code>@foreach($user->addresses as $address)
  <p>
    {{$address->address}}<br>
    {{$address->city}}, {{$address->province}}<br>
    {{$address->country}}<br>
    {{$address->postalcode}}
  </p>
@endforeach
</code>```

But I'm not able to get user primary address.

答:
If you want to have it so that one user can have many addresses but also that an one address can belong to many users then a many to many relationship using a pivot table like the address_user suggested would work fine. This is useful if you're trying to avoid duplicate data or you want to account for several people sharing an address.

As for allowing a user to have a primary address, you've got the right idea. Just add a column to your users table that points at their primary address in the addresses table and that should be it. If you go for the many to many approach you could add another field in the pivot table to flag an address as being the user's primary.

Re: Update 2.

With the changes you have made it should be quite easy to get the user's primary address. You have a few options. If you're looping through the user's addresses, you could simply compare the $user->primary_address_id (or in your case address_id) field to the $address->id:

```<code>@foreach ($user->addresses as $address)
  @if ($address->id == $user->primary_address_id)
    <p>Do something with your primary address</p>
  @endif
  <p>
    {{ $address->address }}<br>
    {{ $address->city }}, {{ $address->province }}<br>
    {{ $address->country }}<br>
    {{ $address->postalcode }}
  </p>
@endforeach
</code>```

I would recommend adding a method to your User model to help you with this. Something like this would do the trick:

```<code>class User extends Model
{
    // ..

    public function isPrimaryAddress(Address $address)
    {
        return $this->primary_address_id == $address->id;
    }
}
</code>```

That way you can replace if ($address->id == $user->primary_address_id) in the above template code with @if ($user->isPrimaryAddress($address)). That helps to keep your code more readable.

Now, if you wanted to, you could also add another relation to your user model to get your user's primary address:

```<code>class User extends Model
{
    // ..

    public function primaryAddress()
    {
        return $this->hasOne(Address::class, 'id', 'primary_address_id');
    }
}
</code>```

Then, if you want to get a user's primary address you just need to do this:

```<code>$primaryAddress = $user->primary_address;
</code>```

Title: Users address logic in laravel

Body:
I have 2 tables in my laravel application users and addresses and both of them crud currently working, what i want to do is:

Set several address for each user (DONE)

Set Primary address (Ability of choose in order settings and profile page)

Question is:

Do I need 3rd table such as address_user to get user and address id or as it is now i just can add primary column to address table and let it be?

here is what i have:

user model

public function addresses(){
       return $this->hasMany(Address::class);
    }

Address model

public function user(){
     return $this->belongsTo(User::class);
  }

Address table

Schema::create('addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->string('address');
            $table->string('city');
            $table->string('postalcode')->nullable();
            $table->string('province');
            $table->integer('user_id')->unsigned();
            $table->timestamps();
        });
        Schema::table('addresses', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users');
        });

This is how i print data currently in users index

    @foreach($user->addresses as $uad)

{{$uad->address}}
{{$uad->city}},{{$uad->postalcode}},{{$uad->province}}

    @endforeach

UPDATE

So base on suggestions I added column is_primary to my addresses table and I can set is to 0 and 1 in order to get users primary address, BUT

Now I am in my user edit page and i have 2 address belongs to user
  with id 1 now I want to change selected primary address to another
  address but i am in user profile edit how do I update my address table
  is_primary column while my form route is users.update and not addresses_update ?

UPDATE 2

I've made some changes and here it is:

Users table have address_id column

Addresses table NO HAVE is_primary column anymore.
why? because user could set many address as primary! with this way user only can set 1 address as primary which will get id of that address.

Issue

1- I cannot get user primary address (don't know how!)

here is how i get user addresses:

@foreach($user->addresses as $address)

    {{$address->address}}

    {{$address->city}}, {{$address->province}}

    {{$address->country}}

    {{$address->postalcode}}

@endforeach

But I'm not able to get user primary address.

Body:
If you want to have it so that one user can have many addresses but also that an one address can belong to many users then a many to many relationship using a pivot table like the address_user suggested would work fine. This is useful if you're trying to avoid duplicate data or you want to account for several people sharing an address.

As for allowing a user to have a primary address, you've got the right idea. Just add a column to your users table that points at their primary address in the addresses table and that should be it. If you go for the many to many approach you could add another field in the pivot table to flag an address as being the user's primary.

Re: Update 2.

With the changes you have made it should be quite easy to get the user's primary address. You have a few options. If you're looping through the user's addresses, you could simply compare the $user->primary_address_id (or in your case address_id) field to the $address->id:

@foreach ($user->addresses as $address)
  @if ($address->id == $user->primary_address_id)
    <p>Do something with your primary address</p>
  @endif
  <p>
    {{ $address->address }}<br>
    {{ $address->city }}, {{ $address->province }}<br>
    {{ $address->country }}<br>
    {{ $address->postalcode }}
  </p>
@endforeach

I would recommend adding a method to your User model to help you with this. Something like this would do the trick:

class User extends Model
{
    // ..

    public function isPrimaryAddress(Address $address)
    {
        return $this->primary_address_id == $address->id;
    }
}

That way you can replace if ($address->id == $user->primary_address_id) in the above template code with @if ($user->isPrimaryAddress($address)). That helps to keep your code more readable.

Now, if you wanted to, you could also add another relation to your user model to get your user's primary address:

class User extends Model
{
    // ..

    public function primaryAddress()
    {
        return $this->hasOne(Address::class, 'id', 'primary_address_id');
    }
}

Then, if you want to get a user's primary address you just need to do this:

$primaryAddress = $user->primary_address;