问:
H2OGridSearch H2OGBM pyspark: NullPointerException in extractH2OParameters
I'm trying to run a grid search for Gradient Boosting Machine in pyspark with H2O Sparkling Water.

Produced a reproducible example with the famous iris dataset.

```<code>from pysparkling import H2OContext, H2OConf
import pyspark
from pyspark.sql.types import StructType, StructField, FloatType, StringType
from pyspark.conf import SparkConf
from pyspark.sql import SQLContext
conf = SparkConf()
conf.setMaster("local").setAppName("test")
conf.set("spark.sql.shuffle.partitions", 3)
conf.set("spark.default.parallelism", 3)
conf.set("spark.debug.maxToStringFields", 100)
sc = pyspark.SparkContext(conf=conf)
sqlContext = SQLContext(sc)
hc = H2OContext.getOrCreate(sc, H2OConf(sc).set_internal_cluster_mode())
schema = StructType([
    StructField("sepal_length", FloatType(), True),
    StructField("sepal_width", FloatType(), True),
    StructField("petal_length", FloatType(), True),
    StructField("petal_width", FloatType(), True),
    StructField("class", StringType(), True)])
iris_df = sqlContext.read \
        .format('com.databricks.spark.csv') \
        .option('header', 'false') \
        .option('delimiter', ',') \
        .schema(schema) \
        .load('../../../../Downloads/iris.data')
</code>```

If I try to follow this page of H2O docs and just translate to python

```<code>gbm_params = {'learnRate': [0.01, 0.1],
              'ntrees': [100 , 200, 300, 500]}
gbm_grid = H2OGridSearch()\
    .setLabelCol("class") \
    .setHyperParameters(gbm_params)\
    .setAlgo(H2OGBM().setMaxDepth(30))

model_pipeline = Pipeline().setStages([gbm_grid])
model = model_pipeline.fit(iris_df)
</code>```

I get an internal NullPointerException, I guess there's something missing in the configuration.

```<code>Py4JJavaError: An error occurred while calling o111.fit.
: java.lang.NullPointerException
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.extractH2OParameters(H2OGridSearch.scala:352)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.fit(H2OGridSearch.scala:64)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Unknown Source)
</code>```

If I try to rewrite it in a different way, I get a different error,

```<code>gbm_grid = H2OGridSearch(algo=H2OGBM().setMaxDepth(30),
                         hyperParameters={'learnRate': [0.01, 0.1]},
                         withDetailedPredictionCol=True,
                         labelCol='class',
                         stoppingMetric="AUC")
model_pipeline = Pipeline().setStages([gbm_grid])
model = model_pipeline.fit(iris_df)
</code>```

This is the output, no matter how do I change the hyperparameters,

```<code>Py4JJavaError: An error occurred while calling o1817.fit.
: java.lang.NoSuchFieldException: learnRate
    at java.lang.Class.getField(Unknown Source)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.findField(H2OGridSearch.scala:170)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.processHyperParams(H2OGridSearch.scala:154)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.fit(H2OGridSearch.scala:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Unknown Source)
</code>```

The following works, however it is not useful since there is no grid,

```<code>gbm_grid = H2OGridSearch(algo=H2OGBM().setMaxDepth(30),
                         #hyperParameters=gbm_params,
                         withDetailedPredictionCol=True,
                         labelCol='class',
                         stoppingMetric="AUC")
model_pipeline = Pipeline().setStages([gbm_grid])
model = model_pipeline.fit(iris_df)
model.stages[0].transform(iris_df).head()
</code>```

And finally, just to be sure that learnRate is a parameter of H2OGBM, this also works,

```<code>gbm_model = H2OGBM(labelCol='class',
                   withDetailedPredictionCol=True).setLearnRate(0.01).setMaxDepth(5).setNtrees(100)

model_pipeline = Pipeline().setStages([gbm_model])
model = model_pipeline.fit(iris_df)
model.stages[0].transform(iris_df).head()
</code>```

EDIT: missing imports

```<code>from pyspark.ml.pipeline import Pipeline
from ai.h2o.sparkling.ml.algos import H2OGridSearch
from ai.h2o.sparkling.ml.algos import H2OGBM
</code>```

and sparking water version

```<code>h2o-pysparkling-2-4       3.28.0.1-1               pypi_0    pypi
</code>```

EDIT after comments for Spark/H2O/Java versions

Spark: 2.4.4

H2O: 3.28.0.3

Java: 1.8.0_232

EDIT java -version

```<code>openjdk version "1.8.0_242"
OpenJDK Runtime Environment (build 1.8.0_242-8u242-b08-0ubuntu3~16.04-b08)
OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)
</code>```

Get the same error if I use learn_rate instead of learnRate.

```<code>gbm_params = {'learnRate': [0.01, 0.1],
              'ntrees': [100 , 200, 300, 500]}
gbm_grid = H2OGridSearch()\
    .setLabelCol("class") \
    .setHyperParameters(gbm_params)\
    .setAlgo(H2OGBM().setMaxDepth(30))

model_pipeline = Pipeline().setStages([gbm_grid])
model = model_pipeline.fit(iris_df)
</code>```0

...

```<code>gbm_params = {'learnRate': [0.01, 0.1],
              'ntrees': [100 , 200, 300, 500]}
gbm_grid = H2OGridSearch()\
    .setLabelCol("class") \
    .setHyperParameters(gbm_params)\
    .setAlgo(H2OGBM().setMaxDepth(30))

model_pipeline = Pipeline().setStages([gbm_grid])
model = model_pipeline.fit(iris_df)
</code>```1

答: Why not use a workaround and utilize H2O UI to create the grid? There's a checkbox to make your chosen parameter griddable, and you can supply the parameter values as a comma-separated list via the web form where you would normally put a single value.</p>

Body:
I'm trying to run a grid search for Gradient Boosting Machine in pyspark with H2O Sparkling Water.

Produced a reproducible example with the famous iris dataset.

from pysparkling import H2OContext, H2OConf
import pyspark
from pyspark.sql.types import StructType, StructField, FloatType, StringType
from pyspark.conf import SparkConf
from pyspark.sql import SQLContext
conf = SparkConf()
conf.setMaster("local").setAppName("test")
conf.set("spark.sql.shuffle.partitions", 3)
conf.set("spark.default.parallelism", 3)
conf.set("spark.debug.maxToStringFields", 100)
sc = pyspark.SparkContext(conf=conf)
sqlContext = SQLContext(sc)
hc = H2OContext.getOrCreate(sc, H2OConf(sc).set_internal_cluster_mode())
schema = StructType([
    StructField("sepal_length", FloatType(), True),
    StructField("sepal_width", FloatType(), True),
    StructField("petal_length", FloatType(), True),
    StructField("petal_width", FloatType(), True),
    StructField("class", StringType(), True)])
iris_df = sqlContext.read \
        .format('com.databricks.spark.csv') \
        .option('header', 'false') \
        .option('delimiter', ',') \
        .schema(schema) \
        .load('../../../../Downloads/iris.data')

If I try to follow this page of H2O docs and just translate to python

gbm_params = {'learnRate': [0.01, 0.1],
              'ntrees': [100 , 200, 300, 500]}
gbm_grid = H2OGridSearch()\
    .setLabelCol("class") \
    .setHyperParameters(gbm_params)\
    .setAlgo(H2OGBM().setMaxDepth(30))

model_pipeline = Pipeline().setStages([gbm_grid])
model = model_pipeline.fit(iris_df)

I get an internal NullPointerException, I guess there's something missing in the configuration.

Py4JJavaError: An error occurred while calling o111.fit.
: java.lang.NullPointerException
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.extractH2OParameters(H2OGridSearch.scala:352)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.fit(H2OGridSearch.scala:64)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Unknown Source)

If I try to rewrite it in a different way, I get a different error,

gbm_grid = H2OGridSearch(algo=H2OGBM().setMaxDepth(30),
                         hyperParameters={'learnRate': [0.01, 0.1]},
                         withDetailedPredictionCol=True,
                         labelCol='class',
                         stoppingMetric="AUC")
model_pipeline = Pipeline().setStages([gbm_grid])
model = model_pipeline.fit(iris_df)

This is the output, no matter how do I change the hyperparameters,

Py4JJavaError: An error occurred while calling o1817.fit.
: java.lang.NoSuchFieldException: learnRate
    at java.lang.Class.getField(Unknown Source)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.findField(H2OGridSearch.scala:170)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.processHyperParams(H2OGridSearch.scala:154)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.fit(H2OGridSearch.scala:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Unknown Source)

The following works, however it is not useful since there is no grid,

gbm_grid = H2OGridSearch(algo=H2OGBM().setMaxDepth(30),
                         #hyperParameters=gbm_params,
                         withDetailedPredictionCol=True,
                         labelCol='class',
                         stoppingMetric="AUC")
model_pipeline = Pipeline().setStages([gbm_grid])
model = model_pipeline.fit(iris_df)
model.stages[0].transform(iris_df).head()

And finally, just to be sure that learnRate is a parameter of H2OGBM, this also works,

gbm_model = H2OGBM(labelCol='class',
                   withDetailedPredictionCol=True).setLearnRate(0.01).setMaxDepth(5).setNtrees(100)

model_pipeline = Pipeline().setStages([gbm_model])
model = model_pipeline.fit(iris_df)
model.stages[0].transform(iris_df).head()

EDIT: missing imports

from pyspark.ml.pipeline import Pipeline
from ai.h2o.sparkling.ml.algos import H2OGridSearch
from ai.h2o.sparkling.ml.algos import H2OGBM

and sparking water version

h2o-pysparkling-2-4       3.28.0.1-1               pypi_0    pypi

EDIT after comments for Spark/H2O/Java versions

Spark: 2.4.4

H2O: 3.28.0.3

Java: 1.8.0_232

EDIT java -version

openjdk version "1.8.0_242"
OpenJDK Runtime Environment (build 1.8.0_242-8u242-b08-0ubuntu3~16.04-b08)
OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)

Get the same error if I use learn_rate instead of learnRate.

gbm_grid = H2OGridSearch(algo=H2OGBM().setMaxDepth(30),
                         hyperParameters={'learn_rate': [0.01, 0.1]},
                         withDetailedPredictionCol=True,
                         labelCol='class',
                         stoppingMetric="AUC")
model_pipeline = Pipeline().setStages([gbm_grid])
model = model_pipeline.fit(iris_df)

...

Py4JJavaError: An error occurred while calling o1376.fit.
: java.lang.NoSuchFieldException: learn_rate
    at java.lang.Class.getField(Class.java:1703)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.findField(H2OGridSearch.scala:170)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.processHyperParams(H2OGridSearch.scala:154)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.fit(H2OGridSearch.scala:71)
    at ai.h2o.sparkling.ml.algos.H2OGridSearch.fit(H2OGridSearch.scala:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)


来源: stackexchange

问:
Copy text to clipboard now that execCommand("copy") is obsolete
I just saw on the Mozilla page that execCommand() is obsolete https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

"This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it."

This is what I currently use to copy text to the user's clipboard when the user clicks a "copy text" button. Is there another way to do it?

```<code> var input = // input element with the text
 input.focus();
 input.setSelectionRange(0,99999);
 document.execCommand("copy");
 input.blur();
</code>```

Edit: This How do I copy to the clipboard in JavaScript? does not answer the question. It suggests the same obsolete solution.

答:
From Klaycon's comment to the question. The replacement is the Clipboard API. It is not implemented in all browsers, but most.

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API

```<code>// In this example, the text to copy would be in an element with id = textcopy

var text_to_copy = document.getElementById("textcopy").innerHTML;

if (!navigator.clipboard){
    // use old commandExec() way
} else{
    navigator.clipboard.writeText(text_to_copy).then(
        function(){
            alert("yeah!"); // success
        })
      .catch(
         function() {
            alert("err"); // error
      });
}
</code>```

For some browsers (like Firefox) this only works when initiated by a user action. So, put the code inside a button listener, for example.

I tested this (Feb 2020) in (Windows) Chrome, Firefox, new Edge, Opera, iOS Safari, iOS Chrome, iOS app webview. Clipboard writeText works great.

ContentLicense: CC BY-SA 4.0

Body:
I just saw on the Mozilla page that execCommand() is obsolete https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

"This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it."

This is what I currently use to copy text to the user's clipboard when the user clicks a "copy text" button. Is there another way to do it?

 var input = // input element with the text
 input.focus();
 input.setSelectionRange(0,99999);
 document.execCommand("copy");
 input.blur();

Edit: This How do I copy to the clipboard in JavaScript? does not answer the question. It suggests the same obsolete solution.

Body:
From Klaycon's comment to the question. The replacement is the Clipboard API. It is not implemented in all browsers, but most.

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API

// In this example, the text to copy would be in an element with id = textcopy

var text_to_copy = document.getElementById("textcopy").innerHTML;

if (!navigator.clipboard){
    // use old commandExec() way
} else{
    navigator.clipboard.writeText(text_to_copy).then(
        function(){
            alert("yeah!"); // success
        })
      .catch(
         function() {
            alert("err"); // error
      });
}

For some browsers (like Firefox) this only works when initiated by a user action. So, put the code inside a button listener, for example.

I tested this (Feb 2020) in (Windows) Chrome, Firefox, new Edge, Opera, iOS Safari, iOS Chrome, iOS app webview. Clipboard writeText works great.


问:
How to find the .app file to submit application to AppStore?
I am attempting to submit an application to the AppStore but I am running into some trouble. When I build the application am unable to find the .app file.

In xCode4, I expand the Products folder and myapp.app file is red and right clicking on it doesn't allow me to select Show in Finder.

How to solve this?

答: Choose "Build and Archive" to submit to the App Store. After the app finishes building, the Organizer should popup and allow you to submit/share or validate the app. Obviously, you want the Submit option.</p>

ContentLicense: CC BY-SA 3.0


问:
AWS S3 bucket - Moving all xmls files form one S3 bucker to Another S3 bucker using Python lamda
In my case, I wanted to read all XML form my s3bucket/ parsing then move all parsed files to the same s3Bucker/

for me parsing logic is working fine but I am not able to move all files.
this is the example I am trying to use

```<code>**s3 = boto3.resource('s3')
src_bucket = s3.Bucket('bucket1')
dest_bucket = s3.Bucket('bucket2')
for obj in src_bucket.objects.all():
    filename= obj.key.split('/')[-1]
    dest_bucket.put_object(Key='sample/' + filename, Body=obj.get()["Body"].read())**
</code>```

above code is not working for me at all (I have to give s3 folder full access and for testing given public full access as well).

Thanks

答: Check out this answer. You could use python endshwith() function and pass ".xml" to it, get a list of those files and copy them to the destination bucket and then delete them from the source bucket.

Body:
In my case, I wanted to read all XML form my s3bucket/ parsing then move all parsed files to the same s3Bucker/

for me parsing logic is working fine but I am not able to move all files.
this is the example I am trying to use

**s3 = boto3.resource('s3')
src_bucket = s3.Bucket('bucket1')
dest_bucket = s3.Bucket('bucket2')
for obj in src_bucket.objects.all():
    filename= obj.key.split('/')[-1]
    dest_bucket.put_object(Key='sample/' + filename, Body=obj.get()["Body"].read())**

above code is not working for me at all (I have to give s3 folder full access and for testing given public full access as well).

Thanks


问:
Multiplying Pandas df by 2 constants which creates 2 dfs
I'm new to pandas and currently have a df that looks like this:

```<code>                  p1        p2        p3        p4
dates
2019-12-01  0.0000468  0.0000455    0.00004  0.0000323
2019-12-02  0.0000401  0.0000353  0.0000333  0.0000318
</code>```

and another df that looks like this:

```<code>0    680.068
1    319.932
Name: constantValue, dtype: float64
</code>```

What is the fastest way for me to take the first df, multiply it by each constant and create 2 dfs of the same form as the first but multiplied through for each element?

In terms of efficiency, should I split into 2 dfs or introduce some sort of MultiIndex?

Also the constant number could change, so it could return 3 constants which would result in 3 dfs, 4 constants 4 dfs etc

Any advice is appreciated

答:
Ok, so you have one DataFrame that you want to multiply it by the values of a a distinct Series (because your constant table looks more like a pandas Series than a DataFrame).

There are no efficiency problem here:

iterating a Series is fast

multiplying a DataFrame with a scalar value is fast (the pandas or numpy word is vectorizable), provided the columns datatypes are compatible with the multiplication with a float.

Here you only have (as much as I can guess) floating point columns and a DatatimeIndex for the dates index which will not be affected.

The simplest way IMHO would be to build a list of DataFrames. Assuming the original DataFrame is df and the constant is the Series constants:

```<code>df_list = [df * val for val in constants]
</code>```

Body:
I'm new to pandas and currently have a df that looks like this:

                  p1        p2        p3        p4
dates
2019-12-01  0.0000468  0.0000455    0.00004  0.0000323
2019-12-02  0.0000401  0.0000353  0.0000333  0.0000318

and another df that looks like this:

0    680.068
1    319.932
Name: constantValue, dtype: float64

What is the fastest way for me to take the first df, multiply it by each constant and create 2 dfs of the same form as the first but multiplied through for each element?

In terms of efficiency, should I split into 2 dfs or introduce some sort of MultiIndex?

Also the constant number could change, so it could return 3 constants which would result in 3 dfs, 4 constants 4 dfs etc

Any advice is appreciated

Body:
Ok, so you have one DataFrame that you want to multiply it by the values of a a distinct Series (because your constant table looks more like a pandas Series than a DataFrame).

There are no efficiency problem here:

iterating a Series is fast

multiplying a DataFrame with a scalar value is fast (the pandas or numpy word is vectorizable), provided the columns datatypes are compatible with the multiplication with a float.

Here you only have (as much as I can guess) floating point columns and a DatatimeIndex for the dates index which will not be affected.

The simplest way IMHO would be to build a list of DataFrames. Assuming the original DataFrame is df and the constant is the Series constants:

df_list = [df * val for val in constants]


问:
Android kotlin coroutines return object from lifecycle scopes
I have a function getNewProduct that it should be return an object of type ProductCats. Inside this function I call a Async method and cause of it I should call it by coroutine scopes. this is codes:

```<code>    private fun addProductCatAsync(pc: ProductCats) = viewModelScope.async {
        withContext(Dispatchers.Default){
            productService.addProductCatToServer(pc)
        }
    }

    fun getNewProduct(pc: ProductCats) = viewModelScope.launch{

        if (_newProduct.value == null) {
            val res = addProductCatAsync(pc).await()
            _newProduct.value = res
            println("NEW PRODUCT INSIDE COROUTINE: ${_newProduct.value}")
            return@launch res
        }
        return@launch _newProduct.value
    }
</code>```

but i got this error on compile time, from lines of return: required: Unit, found: ProductCats?. How can I convert getNewProduct function and make it return my desired object instead ob job?

答:
If you want take result, you can use async instead launch</p>

```<code>fun getNewProduct(pc: ProductCats) = viewModelScope.async {
if (_newProduct.value == null) {
    val res = addProductCatAsync(pc).await()
    _newProduct.value = res
    println("NEW PRODUCT INSIDE COROUTINE: ${_newProduct.value}")
}
_newProduct.value
}.await()
</code>```

Body:
I have a function getNewProduct that it should be return an object of type ProductCats. Inside this function I call a Async method and cause of it I should call it by coroutine scopes. this is codes:

    private fun addProductCatAsync(pc: ProductCats) = viewModelScope.async {
        withContext(Dispatchers.Default){
            productService.addProductCatToServer(pc)
        }
    }

    fun getNewProduct(pc: ProductCats) = viewModelScope.launch{

        if (_newProduct.value == null) {
            val res = addProductCatAsync(pc).await()
            _newProduct.value = res
            println("NEW PRODUCT INSIDE COROUTINE: ${_newProduct.value}")
            return@launch res
        }
        return@launch _newProduct.value
    }

but i got this error on compile time, from lines of return: required: Unit, found: ProductCats?. How can I convert getNewProduct function and make it return my desired object instead ob job?

Body:
If you want take result, you can use async instead launch

fun getNewProduct(pc: ProductCats) = viewModelScope.async {
if (_newProduct.value == null) {
    val res = addProductCatAsync(pc).await()
    _newProduct.value = res
    println("NEW PRODUCT INSIDE COROUTINE: ${_newProduct.value}")
}
_newProduct.value
}.await()


问:
Size of pointer variable in a structure
```<code>int main()
{
    struct
    {
        char *name_pointer;
        char all[13];
        int foo;
    } record;

    printf("%d\n",sizeof(record.all));
    printf("%d\n",sizeof(record.foo));
    printf("%d\n",sizeof(record));

    return 0;
}
</code>```

I want the size of the pointer vatiable "*name_pointer" in the structure....

答:
use the following code:</p>

```<code>printf("%d\n", (int) sizeof(record->name_pointer)/4);
</code>```

Title: Size of pointer variable in a structure

Body:
int main()
{
    struct
    {
        char *name_pointer;
        char all[13];
        int foo;
    } record;

    printf("%d\n",sizeof(record.all));
    printf("%d\n",sizeof(record.foo));
    printf("%d\n",sizeof(record));

    return 0;
}

I want the size of the pointer vatiable "*name_pointer" in the structure....

Body:
use the following code:

printf("%d\n", (int) sizeof(record->name_pointer)/4);


问:
Get index of clicked element using pure javascript
I need to know the index of clicked element. Can't figure out how to do it

```<code>for (i = 0; i < document.getElementById('my_div').children.length; i++) {
    document.getElementById('my_div').children[i].onclick = function(){'ALERT POSITION OF CLICKED CHILD'};
}
</code>```

this.index?

here is a example of what I am trying to do (it only gives back 6):

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body{margin:0;}
#container div{height:50px;line-height:50px; text-align:center}
</style>
</head>
<body>
<div id="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<script>
for (i = 0; i < document.getElementById('container').children.length; i++) {
    document.getElementById('container').children[i].onclick = function(){alert('Number ' + i + ' was clicked')};
}
</script>
</body>
</html>
</code>```

答:
I made a function to find the index.

function getElementIndex(el) {
  return [...el.parentElement.children].indexOf(el);
}
```
<p>Call it like this:</p>
<pre class="lang-js prettyprint-override"><code>const index = getElementIndex(element);
</code>```

Body:
I need to know the index of clicked element. Can't figure out how to do it

for (i = 0; i < document.getElementById('my_div').children.length; i++) {
    document.getElementById('my_div').children[i].onclick = function(){'ALERT POSITION OF CLICKED CHILD'};
}

this.index?

here is a example of what I am trying to do (it only gives back 6):

<!DOCTYPE html>

<meta charset="utf-8" />
<title>Untitled Document</title>

1

2

3

4

5

6

Body:
I made a function to find the index.

function getElementIndex(el) {
  return [...el.parentElement.children].indexOf(el);
}

Call it like this:

const index = getElementIndex(element);


问:
Getting a child by using its id which build at runtime
I have a table and its tbody is adding rows at runtime with icons(delete and update),
Now I want when I click on delete icon, I can get the innerHTML by using the id not an index.
I can use this to get the innerHTML by using index
event.target.parentNode.parentElement.parentElement.children[0].innerHTML;

but what I want is to get the child by using it child id which created at runtime not in HTML and build before??

Can anyone help me with this.
Thanks in advance.

答:
It is so simple;
assign a unique ID to the HTML element and then grab it with the document.getElementById('id').innerHTML

Here is an example below.

```<code><!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to change the color of this paragraph.</p>

<button onclick="myFunction()"><p>Try it</p></button>

<script>
function myFunction() {
  var x = document.getElementById("demo").innerHTML;
    console.log(x);
}
</script>

</body>
</html>
</code>```

For further assistance please visit
https://www.w3schools.com/jsref/met_document_getelementbyid.asp

Body:
It is so simple;
assign a unique ID to the HTML element and then grab it with the document.getElementById('id').innerHTML

Here is an example below.

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to change the color of this paragraph.</p>

<button onclick="myFunction()"><p>Try it</p></button>

<script>
function myFunction() {
  var x = document.getElementById("demo").innerHTML;
    console.log(x);
}
</script>

</body>
</html>

For further assistance please visit
https://www.w3schools.com/jsref/met_document_getelementbyid.asp


问:
Spring MVC project only redirected to tomcat page instead using intellij. How to solve?
I am using spring framework 5.0.4 and tomcat server 9.0.2.

And its a maven project.

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/applicationContext.xml
    </param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
</web-app>
</code>```

dispatcher-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/cache/spring-tx.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<mvc:annotation-driven/>

<context:component-scan base-package="com.project.springbase"/>

<!-- This is the location under /webapp/resources -->
<mvc:resources mapping="/resources/**" location="/resources/" />

<!-- Can also use the default maven resources folder with subfolder name-->
<!--<mvc:resources mapping="/resources/**" location="classpath:/foo/" />-->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<!--<tx:annotation-driven transaction-manager="transactionManager"/>-->

</beans>
</code>```

applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/tx/spring-context-4.0.xsd">

<bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="/WEB-INF/datasource-cfg.properties" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
      p:driverClassName="${jdbc.driverClassName}"
      p:url="${jdbc.url}"
      p:username="${jdbc.username}"
      p:password="${jdbc.password}" />
 </beans>
</code>```

Here is my intellij server console when deploying project:

And here is the browser output:

Everytime i deploy or run the project this page comes instead of my index.

And here is my home controller along with the project strcture:

With all my configurations, whenever i run the project, it shows the tomcat page on localhost:8080 instead of my project index.jsp.

What could be the possible reason?

答:
Try this tutorial, it helped me. also change change your port number

Step 1 create Spring project on IntelliJ

Additional libraries

Spring MVC and

Java EE: Web Application

Step 2
in web.xml
- change

```<code><servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.form</url-pattern>
</code>```

- to

```<code><servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</code>```

Step 3
Edit your dispatcher-servlet.xml

```<code> <context:component-scan base-package="com.springdemo" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</code>```

Step 4
Create your Controller.java

Step 5
Add Tomcat Server

Run > Edit Configuration > Click "+" > Tomcat Server > Local

Still inside Run/Debug Configurations dialog box

Warning: No artifacts marked for deployment > Click Fix

on Application context: "/" remove name_war_exploded

under Server I change my URL tohttp://localhost:8082/

Also on HTTP Port: 8082

Step 6

File > Project Structure > Problems (2) >

Click Fix > add all all missing dependancies

Step 7

delete index.jsp in directory web

create a new index.jsp in directory web > WEB-INF > views

Body:
I am using spring framework 5.0.4 and tomcat server 9.0.2.

And its a maven project.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/applicationContext.xml
    </param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
</web-app>

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/cache/spring-tx.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<mvc:annotation-driven/>

<context:component-scan base-package="com.project.springbase"/>

<mvc:resources mapping="/resources/**" location="/resources/" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/tx/spring-context-4.0.xsd">

<bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="/WEB-INF/datasource-cfg.properties" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
      p:driverClassName="${jdbc.driverClassName}"
      p:url="${jdbc.url}"
      p:username="${jdbc.username}"
      p:password="${jdbc.password}" />
 </beans>

Here is my intellij server console when deploying project:

And here is the browser output:

Everytime i deploy or run the project this page comes instead of my index.

And here is my home controller along with the project strcture:

With all my configurations, whenever i run the project, it shows the tomcat page on localhost:8080 instead of my project index.jsp.

What could be the possible reason?

Body:
Try this tutorial, it helped me. also change change your port number

Step 1 create Spring project on IntelliJ

Additional libraries

Spring MVC and

Java EE: Web Application

Step 2
in web.xml
- change

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.form</url-pattern>

- to

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>

Step 3
Edit your dispatcher-servlet.xml

 <context:component-scan base-package="com.springdemo" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>

Step 4
Create your Controller.java

Step 5
Add Tomcat Server

Run > Edit Configuration > Click "+" > Tomcat Server > Local

Still inside Run/Debug Configurations dialog box

Warning: No artifacts marked for deployment > Click Fix

on Application context: "/" remove name_war_exploded

under Server I change my URL tohttp://localhost:8082/

Also on HTTP Port: 8082

Step 6

File > Project Structure > Problems (2) >

Click Fix > add all all missing dependancies

Step 7

delete index.jsp in directory web

create a new index.jsp in directory web > WEB-INF > views


问:
How to Duplicate last character using regex
My question is how to duplicate last character of each line.

Example:

```<code>hello
hello2
hello$$
</code>```

after replace

```<code>helloo
hello22
hello$$$
</code>```

答:
This is to duplicate the last character of each line of yourfile

```<code>sed 's/.$/&&/' yourfile
</code>```

Body:
My question is how to duplicate last character of each line.

Example:

hello
hello2
hello$$

after replace

helloo
hello22
hello$$$

Body:
This is to duplicate the last character of each line of yourfile

sed 's/.$/&&/' yourfile


问:
Postgresql, for each userid in table loop insert x times
I can't figure out how to insert x amount of times from a WITH table.
I want to insert one coupon for every ticket they got.
What I want to do is following:

```<code>WITH tic AS (
   SELECT userid,
        sum(price * ticketamount) AS total_price,
        sum(ticketamount) As amount_of_tickets
   FROM piljetter_system.soldtickets tic
   WHERE consertid = 7
   GROUP BY userid
)
UPDATE piljetter_system.users usr
   SET pesetas = pesetas + tic.total_price
FROM tic
WHERE usr.userid = tic.userid;
</code>```

For each userId in tic do the insert below times amount_of_tickets. Like a loop for each userid do insert x times.

```<code>INSERT INTO piljetter_system.coupons (tic.userid)
</code>```

Every coupon will get a unique number as default.

I'm thankful for what you can help me with.

Edit: Is this something I can do with generate_series()?

答:
So I mixed your two answers together to be able to do what I wanted. Here is my complete version that works for me.</p>

```<code>WITH tic AS (
   SELECT userid,
        sum(price * ticketamount) AS total_price,
        sum(ticketamount) As amount_of_tickets
   FROM piljetter_system.soldtickets tic
   WHERE consertid = consertidi
   GROUP BY userid
),updated_tics AS (
UPDATE piljetter_system.users usr
   SET pesetas = pesetas + tic.total_price
    FROM tic
    WHERE usr.userid = tic.userid
RETURNING usr.userid, tic.amount_of_tickets)
    INSERT INTO piljetter_system.coupons (userid)
   SELECT updated_tics.userid
   FROM updated_tics CROSS JOIN LATERAL
        generate_series(1, updated_tics.amount_of_tickets) gs(n);
</code>```

Body:
I can't figure out how to insert x amount of times from a WITH table.
I want to insert one coupon for every ticket they got.
What I want to do is following:

WITH tic AS (
   SELECT userid,
        sum(price * ticketamount) AS total_price,
        sum(ticketamount) As amount_of_tickets
   FROM piljetter_system.soldtickets tic
   WHERE consertid = 7
   GROUP BY userid
)
UPDATE piljetter_system.users usr
   SET pesetas = pesetas + tic.total_price
FROM tic
WHERE usr.userid = tic.userid;

For each userId in tic do the insert below times amount_of_tickets. Like a loop for each userid do insert x times.

INSERT INTO piljetter_system.coupons (tic.userid)

Every coupon will get a unique number as default.

I'm thankful for what you can help me with.

Edit: Is this something I can do with generate_series()?

Body:
So I mixed your two answers together to be able to do what I wanted. Here is my complete version that works for me.

WITH tic AS (
   SELECT userid,
        sum(price * ticketamount) AS total_price,
        sum(ticketamount) As amount_of_tickets
   FROM piljetter_system.soldtickets tic
   WHERE consertid = consertidi
   GROUP BY userid
),updated_tics AS (
UPDATE piljetter_system.users usr
   SET pesetas = pesetas + tic.total_price
    FROM tic
    WHERE usr.userid = tic.userid
RETURNING usr.userid, tic.amount_of_tickets)
    INSERT INTO piljetter_system.coupons (userid)
   SELECT updated_tics.userid
   FROM updated_tics CROSS JOIN LATERAL
        generate_series(1, updated_tics.amount_of_tickets) gs(n);


问:
C# How can I assign one identifier to multiple substrings without using If statements?
I created a program that removes homonyms from two strings. Then it compares the two strings to see if they are equal. It works well, but I am having a problem.

I have a huge array of Homonyms. This isn't the full list:

```<code>string[] Homonyms = new string[] {
        "to", "too", "two", "for", "four", "theyre", "there", "their", "see", "sea", "by", "buy", "bye", "past", "passed",
        "witch", "which", "whose", "whos", "hole", "whole", "right", "write", "serial", "cereal", "principle", "principal",
</code>```

These two strings need to be equal:

```<code>s1 = "There are three seas";
s2 = "Their are 3 sees";
</code>```

These two strings should not be equal:

```<code>s1 = "The bee is by the sea";
s2 = "The sea is by the bee";
</code>```

I could create hundreds of If statements like this:

```<code>if (word == "sea" || word == "see")
        word = "ID123"; // identify which homonym
</code>```

Do you know how I can do this easily without hundreds of If statements?

答:
As suggested in the comments the fact that a word exists in the homonym array doesn't mean that two words are indeed homonyms of each other.

With that in mind what we have to do is to create a container that does groups the homonyms words.

I have created an exhaustive list of homonyms in a text file grab it here

The text file can be added into your solution.

So the a huge array of Homonyms problem is solved.

As you can see each line in the file contains the homonyms that refer to each other ( they are separated by a '/' ) - now we can traverse the file and store them into an object:

```<code>    public class Mapping
    {
        public char Sort { get; set; }
        public List<string> Homonyms { get; set; }
    }
</code>```

For example there/they’re/their will be stored in the same object.

The logic will be simple and it assumes that the two strings (s1 and s2) have the same numbers of words.

We analyse one word at the time from both strings(wordString1 and wordString2). If the word are the same is all good.

If the words are not the same - we search the list of mapping and see if it contains wordString1. If that is the case we check whether the same object contain wordString2.

If so wordString1 and wordString2 are homonyms and we continue the analysis. Otherwise we stop as it is obvious that the string s1 and s2 are not the same.

Here you can see both examples provided. Note that 3 and three are not considered homonyms in the English dictionary - therefor I have removed them. Feel free to add your numeric mapping if necessary.

Here is the complete code:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ConsoleApp2
{
    public class Program
    {
        public class Mapping
        {
            public char Sort { get; set; }
            public List<string> Homonyms { get; set; }
        }

        static void Main()
        {
            bool areTheSame = true;
            var string1 = "There are seas";
            var string2 = "Their are sees";
            //var string1 = "The bee is by the sea";
            //var string2 = "The sea is by the bee";

            var s1 = string1.Split(' ').Select(x => x.ToLower()).ToArray();
            var s2 = string2.Split(' ').Select(x => x.ToLower()).ToArray();

            List<string> homonyms = File.ReadAllLines(@"C:\Users\Alex\source\repos\ConsoleApp2\ConsoleApp2\TextFile1.txt").ToList();
            List<Mapping> mapping = new List<Mapping>();

            foreach (string item in homonyms)
            {
                var g = item.Split('/');
                Mapping element = new Mapping();
                element.Sort = g[0].ToUpper()[0];
                element.Homonyms = new List<string>();
                element.Homonyms.AddRange(g.Select(x => x.ToLower()).ToList());

                mapping.Add(element);
            }

            Console.WriteLine("Analising...'{0}' and '{1}'", string1,string2);

            for (int i = 0; i < s1.Count(); i++)
            {
                string wordString1 = s1[i];
                string wordString2 = s2[i];
                Console.WriteLine("Word '{0}' and word '{1}'", wordString1, wordString2);

                if (wordString1 != wordString2)
                {
                    //check whether they are Homonyms
                    var sort = wordString1.ToUpper()[0];
                    var potentiallHomonym = mapping.Where(item => item.Sort == sort && item.Homonyms.Contains(wordString1)).ToList().FirstOrDefault();

                    if (potentiallHomonym != null)
                    {
                        if (potentiallHomonym.Homonyms.Contains(wordString2))
                        {
                            Console.WriteLine("Those words are Homonyms, enter to continue analising.");
                            Console.ReadLine();
                        }
                        else
                        {
                            areTheSame = false;
                            Console.WriteLine("Those words are not Homonyms.");
                            Console.ReadLine();
                            break;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Those words are the same");
                    Console.ReadLine();
                }
            }

            if (areTheSame)
            {
                Console.WriteLine("The strings are the same");
            }

            else
            {
                Console.WriteLine("The strings are not the same");
            }

            Console.ReadLine();
        }
    }
}
</code>```

Body:
I created a program that removes homonyms from two strings. Then it compares the two strings to see if they are equal. It works well, but I am having a problem.

I have a huge array of Homonyms. This isn't the full list:

string[] Homonyms = new string[] {
        "to", "too", "two", "for", "four", "theyre", "there", "their", "see", "sea", "by", "buy", "bye", "past", "passed",
        "witch", "which", "whose", "whos", "hole", "whole", "right", "write", "serial", "cereal", "principle", "principal",

These two strings need to be equal:

s1 = "There are three seas";
s2 = "Their are 3 sees";

These two strings should not be equal:

s1 = "The bee is by the sea";
s2 = "The sea is by the bee";

I could create hundreds of If statements like this:

if (word == "sea" || word == "see")
        word = "ID123"; // identify which homonym

Do you know how I can do this easily without hundreds of If statements?

Body:
As suggested in the comments the fact that a word exists in the homonym array doesn't mean that two words are indeed homonyms of each other.

With that in mind what we have to do is to create a container that does groups the homonyms words.

I have created an exhaustive list of homonyms in a text file grab it here

The text file can be added into your solution.

So the a huge array of Homonyms problem is solved.

As you can see each line in the file contains the homonyms that refer to each other ( they are separated by a '/' ) - now we can traverse the file and store them into an object:

    public class Mapping
    {
        public char Sort { get; set; }
        public List<string> Homonyms { get; set; }
    }

For example there/they’re/their will be stored in the same object.

The logic will be simple and it assumes that the two strings (s1 and s2) have the same numbers of words.

We analyse one word at the time from both strings(wordString1 and wordString2). If the word are the same is all good.

If the words are not the same - we search the list of mapping and see if it contains wordString1. If that is the case we check whether the same object contain wordString2.

If so wordString1 and wordString2 are homonyms and we continue the analysis. Otherwise we stop as it is obvious that the string s1 and s2 are not the same.

Here you can see both examples provided. Note that 3 and three are not considered homonyms in the English dictionary - therefor I have removed them. Feel free to add your numeric mapping if necessary.

Here is the complete code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ConsoleApp2
{
    public class Program
    {
        public class Mapping
        {
            public char Sort { get; set; }
            public List<string> Homonyms { get; set; }
        }

        static void Main()
        {
            bool areTheSame = true;
            var string1 = "There are seas";
            var string2 = "Their are sees";
            //var string1 = "The bee is by the sea";
            //var string2 = "The sea is by the bee";

            var s1 = string1.Split(' ').Select(x => x.ToLower()).ToArray();
            var s2 = string2.Split(' ').Select(x => x.ToLower()).ToArray();

            List<string> homonyms = File.ReadAllLines(@"C:\Users\Alex\source\repos\ConsoleApp2\ConsoleApp2\TextFile1.txt").ToList();
            List<Mapping> mapping = new List<Mapping>();

            foreach (string item in homonyms)
            {
                var g = item.Split('/');
                Mapping element = new Mapping();
                element.Sort = g[0].ToUpper()[0];
                element.Homonyms = new List<string>();
                element.Homonyms.AddRange(g.Select(x => x.ToLower()).ToList());

                mapping.Add(element);
            }

            Console.WriteLine("Analising...'{0}' and '{1}'", string1,string2);

            for (int i = 0; i < s1.Count(); i++)
            {
                string wordString1 = s1[i];
                string wordString2 = s2[i];
                Console.WriteLine("Word '{0}' and word '{1}'", wordString1, wordString2);

                if (wordString1 != wordString2)
                {
                    //check whether they are Homonyms
                    var sort = wordString1.ToUpper()[0];
                    var potentiallHomonym = mapping.Where(item => item.Sort == sort && item.Homonyms.Contains(wordString1)).ToList().FirstOrDefault();

                    if (potentiallHomonym != null)
                    {
                        if (potentiallHomonym.Homonyms.Contains(wordString2))
                        {
                            Console.WriteLine("Those words are Homonyms, enter to continue analising.");
                            Console.ReadLine();
                        }
                        else
                        {
                            areTheSame = false;
                            Console.WriteLine("Those words are not Homonyms.");
                            Console.ReadLine();
                            break;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Those words are the same");
                    Console.ReadLine();
                }
            }

            if (areTheSame)
            {
                Console.WriteLine("The strings are the same");
            }

            else
            {
                Console.WriteLine("The strings are not the same");
            }

            Console.ReadLine();
        }
    }
}


问:
Run nginx in static IP of server
Sorry for my bad English, I can't explain it well.

I have a VPS with Windows Server 2012 with Nginx and run a Node server at port 4000 and React client at port 3000.

In remote desktop website run at localhost address but when I use static IP of server in other device, I get any response from server.

This site can’t be reached XXX.XXX.192.176 took too long to respond.

I setup IIS and connected to the server, but when IIS is started, nginx can't start.

nginx is configured as follows:

```<code>worker_processes  1;

events {
  worker_connections  1024;
}

http {
  include       mime.types;
  default_type  application/octet-stream;

  sendfile        on;

  keepalive_timeout  65;

  server {
    listen 80;
    server_name  _;

    location /api {
        proxy_pass http://localhost:4000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
    location /socket.io {
            proxy_pass http://localhost:4000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
    }
    location / {
            proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   html;
    }
  }
}

</code>```

答:
Finally I solved the problem:

I just add IP of server as server_name and checked the windows firewall for port 80.

```<code>server {
    listen 80;
    server_name  XXX.XXX.192.176; // IP of server

    location /api {
        proxy_pass http://localhost:4000;
    }
    location /socket.io {
            proxy_pass http://localhost:4000;
    }
    location / {
            proxy_pass http://localhost:3000;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   html;
    }
  }
</code>```

Title: Run nginx in static IP of server

Body:
Sorry for my bad English, I can't explain it well.

I have a VPS with Windows Server 2012 with Nginx and run a Node server at port 4000 and React client at port 3000.

In remote desktop website run at localhost address but when I use static IP of server in other device, I get any response from server.

This site can’t be reached XXX.XXX.192.176 took too long to respond.

I setup IIS and connected to the server, but when IIS is started, nginx can't start.

nginx is configured as follows:

worker_processes  1;

events {
  worker_connections  1024;
}

http {
  include       mime.types;
  default_type  application/octet-stream;

  sendfile        on;

  keepalive_timeout  65;

  server {
    listen 80;
    server_name  _;

    location /api {
        proxy_pass http://localhost:4000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
    location /socket.io {
            proxy_pass http://localhost:4000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
    }
    location / {
            proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   html;
    }
  }
}

Body:
Finally I solved the problem:

I just add IP of server as server_name and checked the windows firewall for port 80.

server {
    listen 80;
    server_name  XXX.XXX.192.176; // IP of server

    location /api {
        proxy_pass http://localhost:4000;
    }
    location /socket.io {
            proxy_pass http://localhost:4000;
    }
    location / {
            proxy_pass http://localhost:3000;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   html;
    }
  }


问:
Efficiently getting a last line of file in Python
I am trying to make a plugin for a video-game, and all inputs the program takes are taken from a log-file provided by the server. (the plugin is running in windows)

Sometimes, the server appends the log-file too quickly and my script isn't able to keep up.
I do have a separate thread continiously reading the file.
I've tried several solutions like:

```<code>def get_line():
last_line = ""
with open(mypath1 + "log.log", "r") as f:
    for line in f:
        pass
    last_line = line[:-1]
    return last_line
</code>```

But it isn't quite quick enough. I am in no way a professional programmer, just learning as i go.
Any suggestions would be much appreciated

答:
Try keeping the file open and only continue reading instead of always rereading from the start of the file:

```<code>def get_line(f=open('log.log')):
    for line in f:
        pass
    return line[:-1]
</code>```

Demo (also runnable at repl.it):

```<code>def write(*lines):
    with open('log.log', 'a') as f:
        for line in lines:
            print(line, file=f)

write('foo', 'bar', 'last1')
print(get_line())
write('foo', 'bar', 'last2')
print(get_line())
</code>```

Output:

```<code>last1
last2
</code>```

More robust version that returns an empty string if the file is empty, and repeats the previous last line if that's still the last line (i.e., if there are no new lines):

```<code>def get_line(f=open('log.log'), cache=['']):
    for cache[0] in f:
        pass
    return cache[0][:-1]
</code>```

Demo at repli.it.

Body:
I am trying to make a plugin for a video-game, and all inputs the program takes are taken from a log-file provided by the server. (the plugin is running in windows)

Sometimes, the server appends the log-file too quickly and my script isn't able to keep up.
I do have a separate thread continiously reading the file.
I've tried several solutions like:

def get_line():
last_line = ""
with open(mypath1 + "log.log", "r") as f:
    for line in f:
        pass
    last_line = line[:-1]
    return last_line

But it isn't quite quick enough. I am in no way a professional programmer, just learning as i go.
Any suggestions would be much appreciated

Body:
Try keeping the file open and only continue reading instead of always rereading from the start of the file:

def get_line(f=open('log.log')):
    for line in f:
        pass
    return line[:-1]

Demo (also runnable at repl.it):

def write(*lines):
    with open('log.log', 'a') as f:
        for line in lines:
            print(line, file=f)

write('foo', 'bar', 'last1')
print(get_line())
write('foo', 'bar', 'last2')
print(get_line())

Output:

last1
last2

More robust version that returns an empty string if the file is empty, and repeats the previous last line if that's still the last line (i.e., if there are no new lines):

def get_line(f=open('log.log'), cache=['']):
    for cache[0] in f:
        pass
    return cache[0][:-1]

Demo at repli.it.


问:
Cannot delete a file from s3 with boto3
I am trying to permanently delete a file from S3, using boto3. My buckets are not using versioning.

I have tried two ways:

def remove_aws_object(bucket_name, item_key):
    ''' Provide bucket name and item key, remove from S3
    '''
    s3_client = boto3.client('s3',
                             aws_access_key_id=AWS_ACCESS_KEY,
                             aws_secret_access_key=AWS_SECRET)
    delete = s3_client.delete_object(Bucket=bucket_name, Key=item_key)
    print(delete)
{'ResponseMetadata': {'RequestId': '61F3C195D373B0C5', 'HostId': 'pigcx1wtIN+Y8RU3zJKliWXcXrHXHzpdAOuGBL64x3V9YefQbWXPZi9B/9F', 'HTTPStatusCode': 204, 'HTTPHeaders': {'x-amz-id-2': 'pigcx1wtIN+Y8RU3zJKliWXcXrHXHzpdAOuGBL64x3V9YefQbWXPZi9B/9FLazUSsCds8f4=', 'x-amz-request-id': '61F3C195D373B0C5', 'date': 'Thu, 13 Feb 2020 09:07:50 GMT', 'server': 'AmazonS3'}, 'RetryAttempts': 0}}
```

<p>As well as via the Object:</p>

<pre class="lang-python prettyprint-override"><code>def remove_aws_object(bucket_name, item_key):
    ''' Provide bucket name and item key, remove from S3
    '''
    s3_client = boto3.resource('s3',
                             aws_access_key_id=AWS_ACCESS_KEY,
                             aws_secret_access_key=AWS_SECRET)

    my_object = s3_client.Object(bucket_name, item_key)
    a = my_object.delete()
    print(a)
    {'ResponseMetadata': {'RequestId': '6074B9CA870773CE', 'HostId': 'rQoK+x+xcjAw2T3DpTHMWQb4Gq6DzPJy2qFoFHQCYoGwb8/p7700+Nk+6gBIERN', 'HTTPStatusCode': 204, 'HTTPHeaders': {'x-amz-id-2': 'rQoK+x+xcjAw2TKK833DpTHMWQb4Gq6DzPJy2qFoFHQCYoGwb8/p7700+Nk+6gBIE', 'x-amz-request-id': '6074B9CA870773CE', 'date': 'Thu, 13 Feb 2020 12:02:36 GMT', 'x-amz-version-id': 'null', 'x-amz-delete-marker': 'true', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'DeleteMarker': True, 'VersionId': 'null'}
</code>```

Both methods work without error, but do not remove the file, I can still see it in the S3 console and I then have to manually delete it. Am I doing something wrong?

答: Are you sure the file in question exists? By your response, you get HttpStatusCode: 204 which means that there is no content available with the parameters you've sent. Can you show an example of your Bucket/key values? I.e. show the exact structure of the string you are passing to those variables?

Title: Cannot delete a file from s3 with boto3

Body:
I am trying to permanently delete a file from S3, using boto3. My buckets are not using versioning.

I have tried two ways:

def remove_aws_object(bucket_name, item_key):
    ''' Provide bucket name and item key, remove from S3
    '''
    s3_client = boto3.client('s3',
                             aws_access_key_id=AWS_ACCESS_KEY,
                             aws_secret_access_key=AWS_SECRET)
    delete = s3_client.delete_object(Bucket=bucket_name, Key=item_key)
    print(delete)
{'ResponseMetadata': {'RequestId': '61F3C195D373B0C5', 'HostId': 'pigcx1wtIN+Y8RU3zJKliWXcXrHXHzpdAOuGBL64x3V9YefQbWXPZi9B/9F', 'HTTPStatusCode': 204, 'HTTPHeaders': {'x-amz-id-2': 'pigcx1wtIN+Y8RU3zJKliWXcXrHXHzpdAOuGBL64x3V9YefQbWXPZi9B/9FLazUSsCds8f4=', 'x-amz-request-id': '61F3C195D373B0C5', 'date': 'Thu, 13 Feb 2020 09:07:50 GMT', 'server': 'AmazonS3'}, 'RetryAttempts': 0}}

As well as via the Object:

def remove_aws_object(bucket_name, item_key):
    ''' Provide bucket name and item key, remove from S3
    '''
    s3_client = boto3.resource('s3',
                             aws_access_key_id=AWS_ACCESS_KEY,
                             aws_secret_access_key=AWS_SECRET)

    my_object = s3_client.Object(bucket_name, item_key)
    a = my_object.delete()
    print(a)
    {'ResponseMetadata': {'RequestId': '6074B9CA870773CE', 'HostId': 'rQoK+x+xcjAw2T3DpTHMWQb4Gq6DzPJy2qFoFHQCYoGwb8/p7700+Nk+6gBIERN', 'HTTPStatusCode': 204, 'HTTPHeaders': {'x-amz-id-2': 'rQoK+x+xcjAw2TKK833DpTHMWQb4Gq6DzPJy2qFoFHQCYoGwb8/p7700+Nk+6gBIE', 'x-amz-request-id': '6074B9CA870773CE', 'date': 'Thu, 13 Feb 2020 12:02:36 GMT', 'x-amz-version-id': 'null', 'x-amz-delete-marker': 'true', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'DeleteMarker': True, 'VersionId': 'null'}

Both methods work without error, but do not remove the file, I can still see it in the S3 console and I then have to manually delete it. Am I doing something wrong?


问:
Azure Devops Pipelines Test Attachments for successful tests
As noted here:
https://learn.microsoft.com/en-us/azure/devops/pipelines/test/review-continuous-test-results-after-build?view=azure-devops#tests-tab

If you use the Visual Studio Test task to run tests, diagnostic output logged from tests (using any of Console.WriteLine, Trace.WriteLine or TestContext.WriteLine methods), will appear as an attachment for a failed test.

How can I enforce Azure Devops pipelines to publish attachments for successful tests?

Update

riQQ pointed to the another stackoverflow question:Azure DevOps: Console output for green tests is missing
Proposed solution doesn't help me, because they solved using TestContext. We are using xUnit, and there is no TestContext for xUnit.

答:
How can I enforce Azure Devops pipelines to publish attachments for
  successful tests?

Sorry but as I know this is not supported behavior for VSTest Task. It's by design that only failed tests should have the log as attachment. And after my check, no extensions in Marketplace extends this kind of option.

So if you do want this option, you may consider using rest api like what riQQ suggests above. Or you can post a new feature request in DC forum, it it gets enough votes, the team would consider it seriously.

Hope it helps :)


问:
How to correctly create a link for a custom form in functions.php
I'm trying to create my own form in functions.php. I've done a lot of research and found it safest to do a form using Post / Redirect / Get to avoid Resubmits POST request. Everything works fine. The form sends POST, the action file processes everything, saves it to SESSION and redirects it back. The form is on the page: http://plovarnaluhacovice.icreation.cz/my-account/zustatek-kreditu/

But my problem is that I don't want the link "Send" to have a link: http://plovarnaluhacovice.icreation.cz/wp-content/themes/Divi_Child/process.php, but http://plovarnaluhacovice.icreation.cz/my-account/zustatek-kreditu/process.php for security reasons.

To make it a little complicated I use the WooCommerce plugin and this page (/zustatek-kreditu/) is added to the WooCommerce "My Account" page menu (photo).

Form:

```<code><form action="http://plovarnaluhacovice.icreation.cz/wp-content/themes/Divi_Child/process.php" method="post">
    <p>Uživatelské jméno: <br><input type="text" name="username" /></p>
    <p>Heslo: <br><input type="password" name="password" /></p>
    <br><button type="submit" name="save">Přidat</button>
</form>
</code>```

File structure:

wp-content/themes/
1. Divi_Child
    2. functions.php
    3. process.php

Custom WooCommerce menu:

```<code>//ZŮSTATEK KREDITU

// ------------------

// 1. Register new endpoint to use for My Account page

// Note: Resave Permalinks or it will give 404 error

function zustatek_kreditu_endpoint() {
    add_rewrite_endpoint( 'zustatek-kreditu', EP_ROOT | EP_PAGES );
}

add_action( 'init', 'zustatek_kreditu_endpoint' );

// ------------------

// 2. Add new query var

function zustatek_kreditu_query_vars( $vars ) {
    $vars[] = 'zustatek-kreditu';
    return $vars;
}

add_filter( 'query_vars', 'zustatek_kreditu_query_vars', 0 );

// ------------------

// 3. Insert the new endpoint into the My Account menu

function zustatek_kreditu_link_my_account( $items ) {
    $items['zustatek-kreditu'] = 'Zůstatek kreditu';
    return $items;
}

add_filter( 'woocommerce_account_menu_items', 'zustatek_kreditu_link_my_account' );

// ------------------

// 4. Add content to the new endpoint

?>
    <form action="http://plovarnaluhacovice.icreation.cz/wp-content/themes/Divi_Child/process.php" method="post">
        <p>Uživatelské jméno: <br><input type="text" name="username" /></p>
        <p>Heslo: <br><input type="password" name="password" /></p>
        <br><button type="submit" name="save">Přidat</button>
    </form>
<?php

add_action( 'woocommerce_account_zustatek-kreditu_endpoint', 'hlavniMetoda' );
</code>```

process.php file:

```<code><?php

require_once __DIR__ . '/../../../wp-config.php';
global $wp;
global $wpdb;
$current_user_id = wp_get_current_user()->ID;

if (isset($_POST['save'])) {
    if($current_user_id > 0) {
        $username = $_POST['username'];
        $password = $_POST['password'];

        $dotaz = "INSERT INTO {$wpdb->prefix}abonent(username, password, ID_users) VALUES('{$username}', '{$password}', {$current_user_id})";
        $result = $wpdb->query($dotaz);

        if($result) {
            $_SESSION['zprava'] = "Přidáno";
        }
        else {
            $_SESSION['zprava'] = "Chyba.";
        }
    }
    header("Location: http://plovarnaluhacovice.icreation.cz/muj-ucet/zustatek-kreditu");
}
?>
</code>```

答:
The simplest solution is to create a page template in wp add it to your theme folder under the name "Page-process.php" and place all the coding of process.php into this template and add the following text to the top of this template:

Create a wp page and select this template on itas the page template on under the
"Page Attributes" meta box.

On your form code replace the action URL tot the page you just created and linked to the new page template you created.

action="http://plovarnaluhacovice.icreation.cz/wp-content/themes/Divi_Child/process.php"

Recap:
You are going to replace your "porcess.php" with a normal page on WordPress that is going to use the page PHP codes you placed on "process.php" but this privilege will allow you to run your code withing a wp page and not directly on a theme PHP file.

Thanks, let me know what happens!! :)

Body:
I'm trying to create my own form in functions.php. I've done a lot of research and found it safest to do a form using Post / Redirect / Get to avoid Resubmits POST request. Everything works fine. The form sends POST, the action file processes everything, saves it to SESSION and redirects it back. The form is on the page: http://plovarnaluhacovice.icreation.cz/my-account/zustatek-kreditu/

But my problem is that I don't want the link "Send" to have a link: http://plovarnaluhacovice.icreation.cz/wp-content/themes/Divi_Child/process.php, but http://plovarnaluhacovice.icreation.cz/my-account/zustatek-kreditu/process.php for security reasons.

To make it a little complicated I use the WooCommerce plugin and this page (/zustatek-kreditu/) is added to the WooCommerce "My Account" page menu (photo).

Form:

<form action="http://plovarnaluhacovice.icreation.cz/wp-content/themes/Divi_Child/process.php" method="post">

Uživatelské jméno:
<input type="text" name="username" />

Heslo:
<input type="password" name="password" />

<button type="submit" name="save">Přidat</button>
</form>

File structure:

wp-content/themes/
1. Divi_Child
    2. functions.php
    3. process.php

Custom WooCommerce menu:

//ZŮSTATEK KREDITU

// ------------------

// 1. Register new endpoint to use for My Account page

// Note: Resave Permalinks or it will give 404 error

function zustatek_kreditu_endpoint() {
    add_rewrite_endpoint( 'zustatek-kreditu', EP_ROOT | EP_PAGES );
}

add_action( 'init', 'zustatek_kreditu_endpoint' );

// ------------------

// 2. Add new query var

function zustatek_kreditu_query_vars( $vars ) {
    $vars[] = 'zustatek-kreditu';
    return $vars;
}

add_filter( 'query_vars', 'zustatek_kreditu_query_vars', 0 );

// ------------------

// 3. Insert the new endpoint into the My Account menu

function zustatek_kreditu_link_my_account( $items ) {
    $items['zustatek-kreditu'] = 'Zůstatek kreditu';
    return $items;
}

add_filter( 'woocommerce_account_menu_items', 'zustatek_kreditu_link_my_account' );

// ------------------

// 4. Add content to the new endpoint

?>
    <form action="http://plovarnaluhacovice.icreation.cz/wp-content/themes/Divi_Child/process.php" method="post">

Uživatelské jméno:
<input type="text" name="username" />

Heslo:
<input type="password" name="password" />

<button type="submit" name="save">Přidat</button>
    </form>
<?php

add_action( 'woocommerce_account_zustatek-kreditu_endpoint', 'hlavniMetoda' );

process.php file:

<?php

require_once __DIR__ . '/../../../wp-config.php';
global $wp;
global $wpdb;
$current_user_id = wp_get_current_user()->ID;

if (isset($_POST['save'])) {
    if($current_user_id > 0) {
        $username = $_POST['username'];
        $password = $_POST['password'];

        $dotaz = "INSERT INTO {$wpdb->prefix}abonent(username, password, ID_users) VALUES('{$username}', '{$password}', {$current_user_id})";
        $result = $wpdb->query($dotaz);

        if($result) {
            $_SESSION['zprava'] = "Přidáno";
        }
        else {
            $_SESSION['zprava'] = "Chyba.";
        }
    }
    header("Location: http://plovarnaluhacovice.icreation.cz/muj-ucet/zustatek-kreditu");
}
?>


问:
How to make just one mysql connection with PDO
I'm trying to make just one connection with my code down below.

Inside func.php I added function __construct but does not work. Error:

Uncaught Error: Call to protected method dbh::connect() from context 'getPosts'.

I read some articles and I don't really understand where function __construct should be placed. Inside my connect.php or func.php?

```<code>public $conn;

public function __construct() {
    $this->conn = new dbh();
    $this->conn = $this->conn->connect();

}
</code>```

MY code:
connect.php

```<code>    class dbh{

        private $host = "localhost";
        private $user = "root";
        private $pwd = "12345";
        private $dbname = "posts";

        protected function connect() {
            $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
            $pdo = new PDO ($dsn, $this->user, $this->pwd);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            return $pdo;

    }
}
</code>```

func.php

```<code>class PostsData extends dbh{

    public function getPosts() {

            $sql = "SELECT * FROM posts_tbl";
            $stmt = $this->connect()->prepare($sql);
            $stmt->execute();
            $result = $stmt->fetchAll((PDO::FETCH_OBJ));

            return $result;
    }

    public function addPost($filter_author, $filter_title, $filter_txt) {

            $sql = "INSERT INTO posts_tbl (post_author, post_title, post_txt) VALUES (?, ?, ?, ?)";
            $stmt = $this->connect()->prepare($sql);
            $stmt->execute([$filter_author, $filter_title, $filter_txt]);

        }

    }
</code>```

答:
```<code>class PostsData extends dbh{

private $conn;

public function __construct() {
$this->conn = new dbh();
$this->conn = $this->conn->connect();

}

   public function getPosts() {

            $sql = "SELECT * FROM posts_tbl";
            $stmt = $this->connect()->prepare($sql);
            $stmt->execute();
            $result = $stmt->fetchAll((PDO::FETCH_OBJ));

            return $result;

    }

    public function addPost($filter_author, $filter_title, $filter_txt) {

            $sql = "INSERT INTO posts_tbl (post_author, post_title, post_txt) VALUES (?, ?, ?, ?)";
            $stmt = $this->connect()->prepare($sql);
            $stmt->execute([$filter_author, $filter_title, $filter_txt]);

        }

    }

$post = new PostsData();
$posts = $post->getPosts();

foreach ($posts as $post) {

echo $post->post_title;

}
</code>```

Body:
I'm trying to make just one connection with my code down below.

Inside func.php I added function __construct but does not work. Error:

Uncaught Error: Call to protected method dbh::connect() from context 'getPosts'.

I read some articles and I don't really understand where function __construct should be placed. Inside my connect.php or func.php?

public $conn;

public function __construct() {
    $this->conn = new dbh();
    $this->conn = $this->conn->connect();

}

MY code:
connect.php

    class dbh{

        private $host = "localhost";
        private $user = "root";
        private $pwd = "12345";
        private $dbname = "posts";

        protected function connect() {
            $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
            $pdo = new PDO ($dsn, $this->user, $this->pwd);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            return $pdo;

    }
}

func.php

class PostsData extends dbh{

    public function getPosts() {

            $sql = "SELECT * FROM posts_tbl";
            $stmt = $this->connect()->prepare($sql);
            $stmt->execute();
            $result = $stmt->fetchAll((PDO::FETCH_OBJ));

            return $result;
    }

    public function addPost($filter_author, $filter_title, $filter_txt) {

            $sql = "INSERT INTO posts_tbl (post_author, post_title, post_txt) VALUES (?, ?, ?, ?)";
            $stmt = $this->connect()->prepare($sql);
            $stmt->execute([$filter_author, $filter_title, $filter_txt]);

        }

    }


问:
After $npm install, Getting Error: Cannot find module '../lib/utils/unsupported.js'
I just came back to work on a React project after working in the Rails environment and found that I cannot run any NPM commands in my Mac terminal. I've tried all the remedies that I have come across but none have worked. The bigger issue is what caused this and how can I avoid it again.

Here is the error. What do I need to do? Please help.

```<code>$npm install

internal/modules/cjs/loader.js:550
    throw err;
    ^

Error: Cannot find module '../lib/utils/unsupported.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
    at Function.Module._load (internal/modules/cjs/loader.js:475:25)
    at Module.require (internal/modules/cjs/loader.js:598:17)
    at require (internal/modules/cjs/helpers.js:11:18)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:19:21
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:92:3)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
</code>```

I have tried the following:

```<code>$brew update
$brew uninstall node
$brew install node
</code>```

After which the following commands come up as so when $which npm was unknown command before:

```<code>$which npm
/usr/local/bin/npm

$which node
/usr/local/bin/node
</code>```

I even tried running:

```<code>/usr/local/bin/npm -v
</code>```

but get the same error as above while

```<code>/usr/local/bin/node -v
v9.11.1
</code>```

works fine.

added the following to my .zshrc file:

```<code>export PATH=/usr/local/bin/node:$PATH
export PATH=/usr/local/bin/npm:$PATH
</code>```

I have also tried:

```<code>$brew uninstall --force node
$brew link --overwrite node
Warning: Already linked: /usr/local/Cellar/node/9.11.1
To relink: brew unlink node && brew link node

$rm -rf /usr/local/lib/node_modules/npm
</code>```

then,

```<code>$node install
</code>```

but that does not work, either.

```<code>$echo $NODE_PATH
</code>```

does come up empty, so I may need to added the following to my .bashrc.

```<code>export PATH="/usr/local/bin/npm:/usr/local/bin/node:/usr/local/bin:$PATH"
</code>```

That does not work either.

答:
In my case, this happened after I performed a machine-wide clean-up of all node_modules folders. I had node installed with nvm and I started getting this error, no matter what node-related action I wanted to trigger:

```<code>Error: Cannot find module '../lib/utils/unsupported.js'
</code>```

I solved it by doing the following:

Restarted my computer

Uninstalled nvm

Installed a different node version

Body:
I just came back to work on a React project after working in the Rails environment and found that I cannot run any NPM commands in my Mac terminal. I've tried all the remedies that I have come across but none have worked. The bigger issue is what caused this and how can I avoid it again.

Here is the error. What do I need to do? Please help.

$npm install

internal/modules/cjs/loader.js:550
    throw err;
    ^

Error: Cannot find module '../lib/utils/unsupported.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
    at Function.Module._load (internal/modules/cjs/loader.js:475:25)
    at Module.require (internal/modules/cjs/loader.js:598:17)
    at require (internal/modules/cjs/helpers.js:11:18)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:19:21
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:92:3)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)

I have tried the following:

$brew update
$brew uninstall node
$brew install node

After which the following commands come up as so when $which npm was unknown command before:

$which npm
/usr/local/bin/npm

$which node
/usr/local/bin/node

I even tried running:

/usr/local/bin/npm -v

but get the same error as above while

/usr/local/bin/node -v
v9.11.1

works fine.

added the following to my .zshrc file:

export PATH=/usr/local/bin/node:$PATH
export PATH=/usr/local/bin/npm:$PATH

I have also tried:

$brew uninstall --force node
$brew link --overwrite node
Warning: Already linked: /usr/local/Cellar/node/9.11.1
To relink: brew unlink node && brew link node

$rm -rf /usr/local/lib/node_modules/npm

then,

$node install

but that does not work, either.

$echo $NODE_PATH

does come up empty, so I may need to added the following to my .bashrc.

export PATH="/usr/local/bin/npm:/usr/local/bin/node:/usr/local/bin:$PATH"

That does not work either.

Body:
In my case, this happened after I performed a machine-wide clean-up of all node_modules folders. I had node installed with nvm and I started getting this error, no matter what node-related action I wanted to trigger:

Error: Cannot find module '../lib/utils/unsupported.js'

I solved it by doing the following:

Restarted my computer

Uninstalled nvm

Installed a different node version


问:
Is Eclipse's ecj compiler extensible?
I am interested in modifying Java syntax and some implicit paradigms. Since I develop with Eclipse which provides it's own compiler, which can also be used standalone, I was wondering if it wasn't possible to extend ecj to respect additional grammar rules (and correctly handle them).

My syntactical changes are all resolvable by removing elements from the AST and creating some new ones, so I assume that what I want to do is possible without diving into bytecode.

Essentially, what I want to do could be done by 'virtually' modifying the source code before the actual compilation. However I suspect that doing so would mess up the source mapping, which would make debugging a hell.

On a sidenote: I am aware of project Lombok, which extends and alters class compilation, however Lombok uses annotations only, and does not modify syntax, strictly speaking. So what I want to do is more invasive to the language specs.

答:
As Object Teams has been mentioned in comments:

(1) Object Teams itself extends JDT for its own language OT/J which is an extension of Java. This is done in a dual strategy:

We maintain a fork of org.eclipse.jdt.core. While this is quite heavy lifting it successfully demonstrates that the JDT architecture is suitable for modification.

We use our own concepts of role objects to non-invasively adapt the behavior of other parts of the IDE (notably org.eclipse.jdt.ui) to reflect the semantics of OT/J

(2) I have a few (oldish) blog posts that demonstrate how OT/J can be used for creating non-invasive variants of JDT including support for extended syntax:

IDE for your own language embedded in Java? (part 1)

IDE for your own language embedded in Java? (part 2)

Get for free what Coin doesn’t buy you

Disclaimer: I am author of OT/J and lead of its implementation, and later became a committer on Eclipse JDT.

For further questions, there's a forum.

Title: Is Eclipse's ecj compiler extensible?


问:
PermissionError: Permission denied to reading CSV File in Python
Simply I wanted to read the csv file that I converted from Data Frame after read the another csv file and same time I tried to remove header from in it.

Then I got the error below one :

```<code>PermissionError: [Errno 13] Permission denied: 'X_Data.csv'
</code>```

My python code :

```<code>import pandas as pd
import numpy as np

df = pd.read_csv('input_doc.csv').replace(' ?', np.nan).dropna()

data_X = df.iloc[:, 1:15].values
data_Y = df.iloc[:, :1].values

clean_X = pd.DataFrame(data_X);
clean_Y = pd.DataFrame(data_Y);

clean_X.to_csv("X_Data.csv", index=False)
clean_Y.to_csv("Y_Data.csv", index=False)

X = pd.read_csv("X_Data.csv", encoding="utf-8", header=1)
Y = pd.read_csv("Y_Data.csv", encoding="utf-8", header=1)
</code>```

Also I got the same error without removing header when reading.

I found several issues that similar to my problem , but those won't fix my problem.

I coded on Anaconda Spyder Editor in Windows 10.

How can I read this file without getting this error? What am I missing?

Thank you so much! Any Help would be appreciated!

答: In my case, I have not opened the file exactly but I have uploaded the same file in another application and that is the issue. So it was not allowed to read that file from another application. Once I close/refresh other application, python application able to read without any permission error.</p>

Body:
Simply I wanted to read the csv file that I converted from Data Frame after read the another csv file and same time I tried to remove header from in it.

Then I got the error below one :

PermissionError: [Errno 13] Permission denied: 'X_Data.csv'

My python code :

import pandas as pd
import numpy as np

df = pd.read_csv('input_doc.csv').replace(' ?', np.nan).dropna()

data_X = df.iloc[:, 1:15].values
data_Y = df.iloc[:, :1].values

clean_X = pd.DataFrame(data_X);
clean_Y = pd.DataFrame(data_Y);

clean_X.to_csv("X_Data.csv", index=False)
clean_Y.to_csv("Y_Data.csv", index=False)

X = pd.read_csv("X_Data.csv", encoding="utf-8", header=1)
Y = pd.read_csv("Y_Data.csv", encoding="utf-8", header=1)

Also I got the same error without removing header when reading.

I found several issues that similar to my problem , but those won't fix my problem.

I coded on Anaconda Spyder Editor in Windows 10.

How can I read this file without getting this error? What am I missing?

Thank you so much! Any Help would be appreciated!


问:
How to use android.view.ViewDebug static methods?
I tried to use ViewDebug.startHierarchyTracing method but it just do nothing since it checks ViewDebug.TRACE_HIERARCHY and returns immediately if it is false.
Actually this is expected behavior according to JavaDoc:

This method will return immediately if TRACE_HIERARCHY is false.

The problem is that TRACE_HIERARCHY is declared in the source as a boolean constant with a value of false:

```<code>/**
 * Enables or disables view hierarchy tracing. Any invoker of
 * {@link #trace(View, android.view.ViewDebug.HierarchyTraceType)} should first
 * check that this value is set to true as not to affect performance.
 */
public static final boolean TRACE_HIERARCHY = false;
</code>```

There are also startRecyclerTracing, startMotionEventTracing (hidden from public API) methods that depends on TRACE_RECYCLER and TRACE_MOTION_EVENTS constants respectively (which are also set to false).

So I wonder whether it is possible to use ViewDebug class at all or it is intended to be used in custom Android builds only? And if so are there such custom (debug?) builds for Emulator available?

答: Based on this Dianne Hackborn comment I can assume ViewDebug is useful only in custom Android builds (with modified values of ViewDebug constants). It seems however that no prebuilt system images with enabled ViewDebug functionality is available for the emulator.

Body:
I tried to use ViewDebug.startHierarchyTracing method but it just do nothing since it checks ViewDebug.TRACE_HIERARCHY and returns immediately if it is false.
Actually this is expected behavior according to JavaDoc:

This method will return immediately if TRACE_HIERARCHY is false.

The problem is that TRACE_HIERARCHY is declared in the source as a boolean constant with a value of false:

/**
 * Enables or disables view hierarchy tracing. Any invoker of
 * {@link #trace(View, android.view.ViewDebug.HierarchyTraceType)} should first
 * check that this value is set to true as not to affect performance.
 */
public static final boolean TRACE_HIERARCHY = false;

There are also startRecyclerTracing, startMotionEventTracing (hidden from public API) methods that depends on TRACE_RECYCLER and TRACE_MOTION_EVENTS constants respectively (which are also set to false).

So I wonder whether it is possible to use ViewDebug class at all or it is intended to be used in custom Android builds only? And if so are there such custom (debug?) builds for Emulator available?


问:
How to use same backgroundcolors out of an array to unknown data in chartjs?
I am generating a bar chart via chartjs. I have a predefined backgroundcolor array with 5 colors. I don't know how much data I get from my sql query. But I would like to use the predifened backgroundcolor. As soon as I have more than 5 data records, the other bars are not displayed correctly. Bar no 1 to 5 displayed correctly. All bars after no 5 are displayed like grey/black. How can I realize, that bar #6 gets the backgroundcolor of #1 and #7 gets the backgroundcolor of #2 and so on...?</p>

```<code>var chartdata = {
labels: name,
datasets: [{
    label: 'My Label here',
    //backgroundColor: ['#3066be', '#2de1c2','#87bcde','#907ad6','#845a6d'],
    backgroundColor:[
        "rgba(255, 159, 64, 0.2)", //orange
        "rgba(255, 205, 86, 0.2)", //yellow
        "rgba(75, 192, 192, 0.2)", // green
        "rgba(54, 162, 235, 0.2)", // blue
        "rgba(153, 102, 255, 0.2)"], //purple
    borderColor:[
        "rgb(255, 159, 64)", //orange
        "rgb(255, 205, 86)", //yellow
        "rgb(75, 192, 192)", //green
        "rgb(54, 162, 235)", //blue
        "rgb(153, 102, 255)"], //purple
    borderWidth: 2,
    hoverBackgroundColor: [
        "rgba(255, 159, 64, 0.4)", //orange
        "rgba(255, 205, 86, 0.4)", //yellow
        "rgba(75, 192, 192, 0.4)", // green
        "rgba(54, 162, 235, 0.4)", // blue
        "rgba(153, 102, 255, 0.4)"], //purple
    data: marks
    }]};
</code>```

答:
I used the ajax request wrongly. So I could not identify the length of the data coming from the request.
I solved it like this:</p>

```<code>$.post("some_file.php", '', function(data) {
    iDependOnMyParameter(data);
});

function iDependOnMyParameter(param) {
    // You should do your work here that depends on the result of the request!
    alert(param)
}
</code>```

Body:
I am generating a bar chart via chartjs. I have a predefined backgroundcolor array with 5 colors. I don't know how much data I get from my sql query. But I would like to use the predifened backgroundcolor. As soon as I have more than 5 data records, the other bars are not displayed correctly. Bar no 1 to 5 displayed correctly. All bars after no 5 are displayed like grey/black. How can I realize, that bar #6 gets the backgroundcolor of #1 and #7 gets the backgroundcolor of #2 and so on...?

var chartdata = {
labels: name,
datasets: [{
    label: 'My Label here',
    //backgroundColor: ['#3066be', '#2de1c2','#87bcde','#907ad6','#845a6d'],
    backgroundColor:[
        "rgba(255, 159, 64, 0.2)", //orange
        "rgba(255, 205, 86, 0.2)", //yellow
        "rgba(75, 192, 192, 0.2)", // green
        "rgba(54, 162, 235, 0.2)", // blue
        "rgba(153, 102, 255, 0.2)"], //purple
    borderColor:[
        "rgb(255, 159, 64)", //orange
        "rgb(255, 205, 86)", //yellow
        "rgb(75, 192, 192)", //green
        "rgb(54, 162, 235)", //blue
        "rgb(153, 102, 255)"], //purple
    borderWidth: 2,
    hoverBackgroundColor: [
        "rgba(255, 159, 64, 0.4)", //orange
        "rgba(255, 205, 86, 0.4)", //yellow
        "rgba(75, 192, 192, 0.4)", // green
        "rgba(54, 162, 235, 0.4)", // blue
        "rgba(153, 102, 255, 0.4)"], //purple
    data: marks
    }]};

Body:
I used the ajax request wrongly. So I could not identify the length of the data coming from the request.
I solved it like this:

$.post("some_file.php", '', function(data) {
    iDependOnMyParameter(data);
});

function iDependOnMyParameter(param) {
    // You should do your work here that depends on the result of the request!
    alert(param)
}


问:
How to extract a json object only using basic commands like sed/awk in shell?
Like this:
I have a json file with below format:

```<code>{
    "Item": {
        "summary": {
            "B": "ABCDE"
        },
        "name": {
            "S": "sider"
        },
        "age": {
            "N": "1"
        },
        "data": {
            "B": "abcde"
        }
    }
}
</code>```

How can I get the object "Item" only using existed commands like sed/awk without installing any external tools in shell?

expected output:

```<code>{
    "summary": {
        "B": "ABCDE"
    },
    "name": {
        "S": "sider"
    },
    "age": {
        "N": "1"
    },
    "data": {
        "B": "abcde"
    }
}
</code>```

答:
Idiomatically, it'd be incorrect to manipulate a nested data format like JSON with line-aware tools like sed/awk. However if you're limited in your choice, then the best approach is following:

convert multi-line file to a single line

using awk/sed extract your Item

Here's a sed based solution:

```<code>bash $ <file.json tr '\n' ' ' | sed -E 's/^ *{ *"Item": +//; s/ *}$//'
</code>```

Body:
Like this:
I have a json file with below format:

{
    "Item": {
        "summary": {
            "B": "ABCDE"
        },
        "name": {
            "S": "sider"
        },
        "age": {
            "N": "1"
        },
        "data": {
            "B": "abcde"
        }
    }
}

How can I get the object "Item" only using existed commands like sed/awk without installing any external tools in shell?

expected output:

{
    "summary": {
        "B": "ABCDE"
    },
    "name": {
        "S": "sider"
    },
    "age": {
        "N": "1"
    },
    "data": {
        "B": "abcde"
    }
}

Body:
Idiomatically, it'd be incorrect to manipulate a nested data format like JSON with line-aware tools like sed/awk. However if you're limited in your choice, then the best approach is following:

convert multi-line file to a single line

using awk/sed extract your Item

Here's a sed based solution:

bash $ <file.json tr '\n' ' ' | sed -E 's/^ *{ *"Item": +//; s/ *}$//'