问:
ElasticsearchSinkConnector object mapping can't be changed from nested to non-nested
I'm streaming my data from kafka topic into elasticsearch. But it's throwing this error from connector {\"type\":\"illegal_argument_exception\",\"reason\":\"object mapping [search_data] can't be changed from nested to non-nested\"}

But when I take the message from topic and add document manually using elasticsearch api, it is working fine.

Does kafka-connect-elasticsearch not support nested object type?

Please help me reply on this as I am stuck here for days.

Elasticsearch version: 7.6.2

Kafka Connect Image: confluentinc/cp-kafka-connect:5.4.2

Below is my configuration for connector.

```<code>{
    "connector.class": "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
    "tasks.max": "1",
    "topics": "es_sink_products",
    "key.ignore": "false",
    "schema.ignore": "true",
    "connection.url": "localhost:9200",
    "type.name": "kafka-connect",
    "name": "product-elasticsearch-sink",
    "key.converter": "org.apache.kafka.connect.storage.StringConverter"
}
</code>```

Elasticsearch Schema

```<code>{
  "mappings": {
    "properties": {
      "search_result_data": {
        "properties": {
          "product_id": {"type": "long"},
          "product_name": {"type": "text"},
        }
      },
      "search_data":{
        "type": "nested",
        "include_in_parent": false,
        "properties": {
          "product_id": {"type": "long"},
          "full_text": {
            "type": "text",
          },
        }
      }
    }
  }
}
</code>```

Sample message from topic es_sink_products

```<code>{
    "search_data": {
        "product_id": 1,
        "full_text": "Product 1"
    },
    "search_result_data": {
        "product_id": 1,
        "product_name": "Product Name 1"
    }
}
</code>```

This is the full error from connector

"org.apache.kafka.connect.errors.ConnectException: Exiting WorkerSinkTask due to unrecoverable exception.\n\tat org.apache.kafka.connect.runtime.WorkerSinkTask.deliverMessages(WorkerSinkTask.java:561)\n\tat org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:322)\n\tat org.apache.kafka.connect.runtime.WorkerSinkTask.iteration(WorkerSinkTask.java:224)\n\tat org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:192)\n\tat org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:177)\n\tat org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:227)\n\tat java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n\tat java.lang.Thread.run(Thread.java:748)\nCaused by: org.apache.kafka.connect.errors.ConnectException: Bulk request failed: [{\"type\":\"illegal_argument_exception\",\"reason\":\"object mapping [search_data] can't be changed from nested to non-nested\"}]\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkTask.handleMalformedDoc(BulkProcessor.java:479)\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkTask.execute(BulkProcessor.java:433)\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkTask.call(BulkProcessor.java:389)\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkTask.call(BulkProcessor.java:375)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n\tat java.lang.Thread.run(Thread.java:748)\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkProcessorThread.run(BulkProcessor.java:370)\n"

答:
This error is thrown when a non-nested mapping was previously set and you're trying to update that mapping w/ nested types.

What you could do now is:

Drop the index

Set the nested mapping (what you called Elasticsearch Schema above) once

Start the kafka stream with the option "schema.ignore": "false"

Reason: changing non-nested to nested is considered a 'breaking change' because of the way payloads get indexed.

Body:
I'm streaming my data from kafka topic into elasticsearch. But it's throwing this error from connector {\"type\":\"illegal_argument_exception\",\"reason\":\"object mapping [search_data] can't be changed from nested to non-nested\"}

But when I take the message from topic and add document manually using elasticsearch api, it is working fine.

Does kafka-connect-elasticsearch not support nested object type?

Please help me reply on this as I am stuck here for days.

Elasticsearch version: 7.6.2

Kafka Connect Image: confluentinc/cp-kafka-connect:5.4.2

Below is my configuration for connector.

{
    "connector.class": "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
    "tasks.max": "1",
    "topics": "es_sink_products",
    "key.ignore": "false",
    "schema.ignore": "true",
    "connection.url": "localhost:9200",
    "type.name": "kafka-connect",
    "name": "product-elasticsearch-sink",
    "key.converter": "org.apache.kafka.connect.storage.StringConverter"
}

Elasticsearch Schema

{
  "mappings": {
    "properties": {
      "search_result_data": {
        "properties": {
          "product_id": {"type": "long"},
          "product_name": {"type": "text"},
        }
      },
      "search_data":{
        "type": "nested",
        "include_in_parent": false,
        "properties": {
          "product_id": {"type": "long"},
          "full_text": {
            "type": "text",
          },
        }
      }
    }
  }
}

Sample message from topic es_sink_products

{
    "search_data": {
        "product_id": 1,
        "full_text": "Product 1"
    },
    "search_result_data": {
        "product_id": 1,
        "product_name": "Product Name 1"
    }
}

This is the full error from connector

"org.apache.kafka.connect.errors.ConnectException: Exiting WorkerSinkTask due to unrecoverable exception.\n\tat org.apache.kafka.connect.runtime.WorkerSinkTask.deliverMessages(WorkerSinkTask.java:561)\n\tat org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:322)\n\tat org.apache.kafka.connect.runtime.WorkerSinkTask.iteration(WorkerSinkTask.java:224)\n\tat org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:192)\n\tat org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:177)\n\tat org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:227)\n\tat java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n\tat java.lang.Thread.run(Thread.java:748)\nCaused by: org.apache.kafka.connect.errors.ConnectException: Bulk request failed: [{\"type\":\"illegal_argument_exception\",\"reason\":\"object mapping [search_data] can't be changed from nested to non-nested\"}]\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkTask.handleMalformedDoc(BulkProcessor.java:479)\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkTask.execute(BulkProcessor.java:433)\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkTask.call(BulkProcessor.java:389)\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkTask.call(BulkProcessor.java:375)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n\tat java.lang.Thread.run(Thread.java:748)\n\tat io.confluent.connect.elasticsearch.bulk.BulkProcessor$BulkProcessorThread.run(BulkProcessor.java:370)\n"


来源: stackexchange

问:
SocketTimeoutException: Connect Timed Out for using RestAssured from TeamCity
I have tried below :

Increased connection time out through code

RestAssuredConfig newConfig = RestAssured.config() .httpClient(HttpClientConfig.httpClientConfig().setParam(CoreConnectionPNames.CONNECTION_TIMEOUT, 12000).setParam(CoreConnectionPNames.SO_TIMEOUT, 12000));

Added User-Agent in request header

Checked same api call manually from local system and remote agent-
both gives same result.

But I am getting java.net.SocketTimeoutException: connect timed out while it is working from local system and not from Teamcity agent execution

Please help

答:
The problem is that TeamCity has a timeout of its own, which has not been changed through your code. You can change this property by setting an internal property in Administration > diagnostics > internal properties.

Here is the property to add:
teamcity.agentServer.connectionTimeout=12000

Here is the documentation for TeamCity startup properties.

I also read through this Youtrack ticket with a similar issue.

ContentLicense: CC BY-SA 4.0


问:
T-SQL query to show table definition?
What is a query that will show me the full definition, including indexes and keys for a SQL Server table?  I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio.  But SQLCMD is always an option.

UPDATE:  I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime.  Is there something else I am missing with sp_help?

Here is what I call:

sp_help airports

Note that I really do want the DDL that defines the table.

答: As an addition to Barry's answer. The sp_help can also be used by itself to iterate all of the objects in a particular database. You also have sp_helptext for your arsenal, which scripts out programmatic elements, like stored procedures.</p>

ContentLicense: CC BY-SA 3.0

Title: T-SQL query to show table definition?


问:
Is there difference between creating a wrapped BigInt or Symbol with the "new" keyword in JavaScript?
I have examined the wrapped symbol objects using the following code.

```<code>const symObj = Object(sym);
const symObjNew = new Object(sym);
// I can see no difference between symObj and symObjNew

console.log(`typeof symObj === 'object' is ${typeof symObj === 'object'}`); // true
console.log(`typeof symObjNew === 'object' is ${typeof symObjNew === 'object'}`); // true
</code>```

I have also examined the symObj and symObjNew in devtools using node --inspect-brk. I don't see any difference between them. The same is true of BigInt.

答:
TL;DR

There is no difference between new Object(realthing) and Object(realthing). They do the same thing.

Much longer answer

When it comes to JS, reading the spec is always a good idea, although it can be incredibly hard to figure out what things mean. So, let's dive into this: in this case, we want the rules for how Object() works:

19.1.1The Object Constructor

The Object constructor:

is the intrinsic object %Object%.

is the initial value of the Object property of the global object.

creates a new ordinary object when called as a constructor.

performs a type conversion when called as a function rather than as a constructor.

is designed to be subclassable. It may be used as the value of an extends clause of a class definition.

So we have two cases to look at: Object(sym), and new Object(sym).

What happens for Object(sym)?

19.1.1.1 Object([ value ])

When the Object function is called with optional argument value, the following steps are taken:

If NewTarget is neither undefined nor the active function, then
     Return ? OrdinaryCreateFromConstructor(NewTarget, "%ObjectPrototype%").

If value is null, undefined or not supplied, return ObjectCreate(%ObjectPrototype%).

Return ! ToObject(value).

(Note that ? and ! here are not "code", they are spec syntax. ! means "this operation will always return a normal value whereas ? may return an abnormal value)

In this case, we didn't use new, so step 1 doesn't apply. The value is not nullish, so step 2 doesn't apply, and we end up executing step 3: we perform a type conversion so we end up with a new object for which typeof will now say "object", no matter what it was before, but with the original data preserved as value.

What happens for new Object(sym)?

Looking at 19.1.1.1 again, we're using new this time, so we might expect step 1 to kick in: after all, there is a NewTarget (by definition: we used new so there is a NewTarget), but it turns out the NewTarget is the Object function itself, making NewTarget the active function, and so step 1a does not kick in.

We also have a value, and it's not nullish, so step 2 doesn't kick in, and we again run step 3: type conversion.

So Object(sym) and new Object(sym) do exactly the same thing, just for subtly different reasons.

So how does ToObject work?

Looking at the spec again:

7.1.13ToObject ( argument )

The abstract operation ToObject converts argument to a value of type Object according to Table 12:

Undefined  Throw a TypeError exception.

Null   Throw a TypeError exception.

Boolean    Return a new Boolean object whose [[BooleanData]] internal slot is set to argument. See 19.3 for a description of Boolean objects.

Number     Return a new Number object whose [[NumberData]] internal slot is set to argument. See 20.1 for a description of Number objects.

String     Return a new String object whose [[StringData]] internal slot is set to argument. See 21.1 for a description of String objects.

Symbol     Return a new Symbol object whose [[SymbolData]] internal slot is set to argument. See 19.4 for a description of Symbol objects.

Object     Return argument.

So the first observation should be that "if it's an object, ToObject does nothing". That's of course not the case for your Object(sym), so what happens for it?

A new object gets built, with its type set to object (irrespective of what the input value type is), and this new object's prototype will be set to match whatever the input value's prototype was. Then the new object's internal value literally gets copied over from the input value that's getting converted.

But we're not quite done

typeof is useless for testing "what a thing is".

Remember that almost everything in JS is an object, and typeof will only tells you the basic type of something. As such, there are only six answers it can give you:

object

function

string

symbol

number

undefined

That's it. The typeof operator tells you nothing about the what the most specific type is, instead it tells you what the most generic type is.

For the specific type, either use thing.constructor.name to find out which constructor function actually got used to build the thing you're examining, or use thing.__proto__ to get a reference to that type. Or, if you have the type already and merely need to test to see if "thing is a ...", use the instanceof operator:

```<code>> typeof 3
"number"

> typeof Object(3)
"object"

> Object(3).constructor.name
"Number"

> Object(3).__proto__
Number { 0 }

> Object(3) instanceof Number
true
</code>```

Body:
I have examined the wrapped symbol objects using the following code.

const symObj = Object(sym);
const symObjNew = new Object(sym);
// I can see no difference between symObj and symObjNew

console.log(`typeof symObj === 'object' is ${typeof symObj === 'object'}`); // true
console.log(`typeof symObjNew === 'object' is ${typeof symObjNew === 'object'}`); // true

I have also examined the symObj and symObjNew in devtools using node --inspect-brk. I don't see any difference between them. The same is true of BigInt.

Body:
TL;DR

There is no difference between new Object(realthing) and Object(realthing). They do the same thing.

Much longer answer

When it comes to JS, reading the spec is always a good idea, although it can be incredibly hard to figure out what things mean. So, let's dive into this: in this case, we want the rules for how Object() works:

19.1.1The Object Constructor

The Object constructor:

is the intrinsic object %Object%.

is the initial value of the Object property of the global object.

creates a new ordinary object when called as a constructor.

performs a type conversion when called as a function rather than as a constructor.

is designed to be subclassable. It may be used as the value of an extends clause of a class definition.

So we have two cases to look at: Object(sym), and new Object(sym).

What happens for Object(sym)?

19.1.1.1 Object([ value ])

When the Object function is called with optional argument value, the following steps are taken:

If NewTarget is neither undefined nor the active function, then
     Return ? OrdinaryCreateFromConstructor(NewTarget, "%ObjectPrototype%").

If value is null, undefined or not supplied, return ObjectCreate(%ObjectPrototype%).

Return ! ToObject(value).

(Note that ? and ! here are not "code", they are spec syntax. ! means "this operation will always return a normal value whereas ? may return an abnormal value)

In this case, we didn't use new, so step 1 doesn't apply. The value is not nullish, so step 2 doesn't apply, and we end up executing step 3: we perform a type conversion so we end up with a new object for which typeof will now say "object", no matter what it was before, but with the original data preserved as value.

What happens for new Object(sym)?

Looking at 19.1.1.1 again, we're using new this time, so we might expect step 1 to kick in: after all, there is a NewTarget (by definition: we used new so there is a NewTarget), but it turns out the NewTarget is the Object function itself, making NewTarget the active function, and so step 1a does not kick in.

We also have a value, and it's not nullish, so step 2 doesn't kick in, and we again run step 3: type conversion.

So Object(sym) and new Object(sym) do exactly the same thing, just for subtly different reasons.

So how does ToObject work?

Looking at the spec again:

7.1.13ToObject ( argument )

The abstract operation ToObject converts argument to a value of type Object according to Table 12:

Undefined  Throw a TypeError exception.

Null   Throw a TypeError exception.

Boolean    Return a new Boolean object whose [[BooleanData]] internal slot is set to argument. See 19.3 for a description of Boolean objects.

Number     Return a new Number object whose [[NumberData]] internal slot is set to argument. See 20.1 for a description of Number objects.

String     Return a new String object whose [[StringData]] internal slot is set to argument. See 21.1 for a description of String objects.

Symbol     Return a new Symbol object whose [[SymbolData]] internal slot is set to argument. See 19.4 for a description of Symbol objects.

Object     Return argument.

So the first observation should be that "if it's an object, ToObject does nothing". That's of course not the case for your Object(sym), so what happens for it?

A new object gets built, with its type set to object (irrespective of what the input value type is), and this new object's prototype will be set to match whatever the input value's prototype was. Then the new object's internal value literally gets copied over from the input value that's getting converted.

But we're not quite done

typeof is useless for testing "what a thing is".

Remember that almost everything in JS is an object, and typeof will only tells you the basic type of something. As such, there are only six answers it can give you:

object

function

string

symbol

number

undefined

That's it. The typeof operator tells you nothing about the what the most specific type is, instead it tells you what the most generic type is.

For the specific type, either use thing.constructor.name to find out which constructor function actually got used to build the thing you're examining, or use thing.__proto__ to get a reference to that type. Or, if you have the type already and merely need to test to see if "thing is a ...", use the instanceof operator:

> typeof 3
"number"

> typeof Object(3)
"object"

> Object(3).constructor.name
"Number"

> Object(3).__proto__
Number { 0 }

> Object(3) instanceof Number
true


问:
Compilers and argument order of evaluation in C++
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?

Classic Example:

```<code>int i = 0;
foo(i++, i++);
</code>```

Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).

答:
Last time I saw differences was between VS2005 and GCC 3.x on an x86 hardware in 2007.
So it's (was?) a very likely situation. So I never rely on evaluation order anymore. Maybe it's better now.</p>

OwnerDisplayName: Cypherjb

Body:
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?

Classic Example:

int i = 0;
foo(i++, i++);

Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).

OwnerDisplayName: Robert Gould

ContentLicense: CC BY-SA 2.5


问:
Create a string array where the index “value” is a string
Already looked in the forum but was not able to find anything similar.

I would like to create a string array where the index “value” is a string.

For instance:

```<code>MyArray(“abc”)=1
MyArray(“def”)=2
MyArray(“ghi”)=3
</code>```

Is there a way to do this in VBA or can I achieve the same in a different way?

答:
A Dictionary Introduction

A Simple Example

```<code>Sub DictIntroduction()

    Dim InitText As Variant, InitNumbers As Variant
    InitText = Array("abc", "def", "ghi")
    InitNumbers = Array(1, 2, 3)

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")

    Dim i As Long
    For i = 0 To UBound(InitText)
        dict.Add InitText(i), InitNumbers(i)
    Next

    Dim Key As Variant
    For Each Key In dict.Keys
        Debug.Print Key, dict(Key)
    Next

    Debug.Print dict("abc")
    Debug.Print dict("def")
    Debug.Print dict("ghi")

End Sub
</code>```

To find out more about the dictionary visit the following links:

Excel VBA Dictionary - A Complete Guide (Article)

Excel VBA Dictionary (YouTube Playlist)

Body:
Already looked in the forum but was not able to find anything similar.

I would like to create a string array where the index “value” is a string.

For instance:

MyArray(“abc”)=1
MyArray(“def”)=2
MyArray(“ghi”)=3

Is there a way to do this in VBA or can I achieve the same in a different way?

Body:
A Dictionary Introduction

A Simple Example

Sub DictIntroduction()

    Dim InitText As Variant, InitNumbers As Variant
    InitText = Array("abc", "def", "ghi")
    InitNumbers = Array(1, 2, 3)

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")

    Dim i As Long
    For i = 0 To UBound(InitText)
        dict.Add InitText(i), InitNumbers(i)
    Next

    Dim Key As Variant
    For Each Key In dict.Keys
        Debug.Print Key, dict(Key)
    Next

    Debug.Print dict("abc")
    Debug.Print dict("def")
    Debug.Print dict("ghi")

End Sub

To find out more about the dictionary visit the following links:

Excel VBA Dictionary - A Complete Guide (Article)

Excel VBA Dictionary (YouTube Playlist)


问:
Extract value from all objects with similar names to a table in R
I have a bunch of R objects, all of their names starting with abund_envir_reduc . I need to extract their value in $statistic to a data frame, with the first column being the name of the object and the second its corresponding statistic value.

Object examples ($statistic class is "numeric"):

```<code>abund_envir_reduc_4$statistic
[1] 0.0071
abund_envir_reduc_2_6_7$statistic
[1] 0.214
abund_envir_reduc_2_2$statistic
[1] 0.056
abund_envir_reduc_7_8_6_2_5$statistic
[1] 0.522
abund_envir_reduc_1_2_3$statistic
[1] 0.2031
</code>```

Desired output:

```<code>ID                            STATISTIC
abund_envir_reduc_4           0.0071
abund_envir_reduc_2_6_7       0.214
abund_envir_reduc_2_2         0.056
abund_envir_reduc_7_8_6_2_5   0.522
abund_envir_reduc_1_2_3       0.2031
</code>```

答:
Here's an approach with mget and bind_rows:

```<code>library(dplyr)
lapply(mget(ls(pattern = "abund_envir_reduc_.+")),
       function(x){list(STATISTIC = x$statistic)}) %>%
  bind_rows(.id = "ID")
## A tibble: 5 x 2
#  ID                          STATISTIC
#  <chr>                           <dbl>
#1 abund_envir_reduc_1_2_3        0.203
#2 abund_envir_reduc_2_2          0.056
#3 abund_envir_reduc_2_6_7        0.214
#4 abund_envir_reduc_4            0.0071
#5 abund_envir_reduc_7_8_6_2_5    0.522
</code>```

Data Setup:

```<code>abund_envir_reduc_4 <- abund_envir_reduc_2_6_7 <- abund_envir_reduc_2_2 <- abund_envir_reduc_7_8_6_2_5 <- abund_envir_reduc_1_2_3 <- list()
abund_envir_reduc_4$statistic <- 0.0071
abund_envir_reduc_2_6_7$statistic <- 0.214
abund_envir_reduc_2_2$statistic <- 0.056
abund_envir_reduc_7_8_6_2_5$statistic <- 0.522
abund_envir_reduc_1_2_3$statistic <- 0.2031
</code>```

Body:
I have a bunch of R objects, all of their names starting with abund_envir_reduc . I need to extract their value in $statistic to a data frame, with the first column being the name of the object and the second its corresponding statistic value.

Object examples ($statistic class is "numeric"):

abund_envir_reduc_4$statistic
[1] 0.0071
abund_envir_reduc_2_6_7$statistic
[1] 0.214
abund_envir_reduc_2_2$statistic
[1] 0.056
abund_envir_reduc_7_8_6_2_5$statistic
[1] 0.522
abund_envir_reduc_1_2_3$statistic
[1] 0.2031

Desired output:

ID                            STATISTIC
abund_envir_reduc_4           0.0071
abund_envir_reduc_2_6_7       0.214
abund_envir_reduc_2_2         0.056
abund_envir_reduc_7_8_6_2_5   0.522
abund_envir_reduc_1_2_3       0.2031

Body:
Here's an approach with mget and bind_rows:

library(dplyr)
lapply(mget(ls(pattern = "abund_envir_reduc_.+")),
       function(x){list(STATISTIC = x$statistic)}) %>%
  bind_rows(.id = "ID")
## A tibble: 5 x 2
#  ID                          STATISTIC
#  <chr>                           <dbl>
#1 abund_envir_reduc_1_2_3        0.203
#2 abund_envir_reduc_2_2          0.056
#3 abund_envir_reduc_2_6_7        0.214
#4 abund_envir_reduc_4            0.0071
#5 abund_envir_reduc_7_8_6_2_5    0.522

Data Setup:

abund_envir_reduc_4 <- abund_envir_reduc_2_6_7 <- abund_envir_reduc_2_2 <- abund_envir_reduc_7_8_6_2_5 <- abund_envir_reduc_1_2_3 <- list()
abund_envir_reduc_4$statistic <- 0.0071
abund_envir_reduc_2_6_7$statistic <- 0.214
abund_envir_reduc_2_2$statistic <- 0.056
abund_envir_reduc_7_8_6_2_5$statistic <- 0.522
abund_envir_reduc_1_2_3$statistic <- 0.2031


问:
Show empty rows in a select SQLite query using pd.read_sql
I want to create a pandas dataframe using a list of codes to search information in a SQLite table related to those codes. I know how to make the SQLite query giving a list of codes. The thing I want to add and I don't know how to do it is to add an empty row for those codes that we don't have information with the code and all the rest of the data empty, instead of ignoring that code as SQLite does. Here is an schematic example:

```<code>Code     atributes
a        data
b        data
empty    -
c        data
c        data
</code>```

where empty means a code that does not appear in the database.

Thanks in advance!

答:
Simply left join merge on a data frame of all codes where any mismatches will render NaN in all columns:

```<code>df_codes = pd.DataFrame({'Code': mylistofcodes})

df_sql = df_codes.merge(df_sql, on='Code', how='left')
</code>```

Alternatively, you can run a LEFT JOIN merge in SQL using a one-column temp table of all codes where NULL renders in mismatched columns. You can then run below query with pd.read_sql:

SELECT c.Code, t.attributes
FROM myCodes c
LEFT JOIN myTable t
  ON t.Code = c.Code
```

Body:
I want to create a pandas dataframe using a list of codes to search information in a SQLite table related to those codes. I know how to make the SQLite query giving a list of codes. The thing I want to add and I don't know how to do it is to add an empty row for those codes that we don't have information with the code and all the rest of the data empty, instead of ignoring that code as SQLite does. Here is an schematic example:

Code     atributes
a        data
b        data
empty    -
c        data
c        data

where empty means a code that does not appear in the database.

Thanks in advance!

Body:
Simply left join merge on a data frame of all codes where any mismatches will render NaN in all columns:

df_codes = pd.DataFrame({'Code': mylistofcodes})

df_sql = df_codes.merge(df_sql, on='Code', how='left')

Alternatively, you can run a LEFT JOIN merge in SQL using a one-column temp table of all codes where NULL renders in mismatched columns. You can then run below query with pd.read_sql:

SELECT c.Code, t.attributes
FROM myCodes c
LEFT JOIN myTable t
  ON t.Code = c.Code


问:
const_defined? vs. defined? in Ruby
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

```<code>if defined? :String
</code>```

or I can write

```<code>if self.class.const_defined? :String
</code>```

Is there a situation where I these two ways of testing would make a difference? Note that I don't ask about the case where I have an explicit receiver, such as MyModule.const_defined? :Something, but only for the case where I want to test whether a certain constant (which in my case happens to be a constant denoting a class) is already defined.

答:
defined? is a keyword that will check if an expression exists in the current scope.

const_defined? is a method that will check if a constant exists through the ancestor chain of the receiver.

```<code>planet = "Earth"

class Experiment
  def diff
    ""
  end

  def show
    puts "defined" if defined?(diff)
    puts "Earth not found" if !defined?(planet)
    puts "String constant defined" if self.class.const_defined?(:String)
  end
end

Experiment.new.show
#=> defined
#=> Earth not found
#=> String constant defined

p Experiment.ancestors #=> [Experiment, Object, Kernel, BasicObject]
p String.superclass #=> Object
</code>```

Here's an example of situations where this will make a difference:

Using defined?(Nothing's printed)

```<code>class Lab
  class Coco
  end
end

class Experiment

  def diff
    ""
  end

  def show
    puts "defined" if defined?(Coco) #=> Nothing printed
  end
end

Experiment.new.show
</code>```

Using self.class.const_defined? (Something's printed)

```<code>class Lab
  class Coco
  end
end

class Experiment < Lab

  def diff
    ""
  end

  def show
    puts "defined" if self.class.const_defined? :Coco #=> defined
  end
end

Experiment.new.show
p Experiment.ancestors #=> [Experiment, Lab, Object, Kernel, BasicObject] We find 'Lab' class in the ancestor chain.
</code>```

Title: const_defined? vs. defined? in Ruby

Body:
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

if defined? :String

or I can write

if self.class.const_defined? :String

Is there a situation where I these two ways of testing would make a difference? Note that I don't ask about the case where I have an explicit receiver, such as MyModule.const_defined? :Something, but only for the case where I want to test whether a certain constant (which in my case happens to be a constant denoting a class) is already defined.

Body:
defined? is a keyword that will check if an expression exists in the current scope.

const_defined? is a method that will check if a constant exists through the ancestor chain of the receiver.

planet = "Earth"

class Experiment
  def diff
    ""
  end

  def show
    puts "defined" if defined?(diff)
    puts "Earth not found" if !defined?(planet)
    puts "String constant defined" if self.class.const_defined?(:String)
  end
end

Experiment.new.show
#=> defined
#=> Earth not found
#=> String constant defined

p Experiment.ancestors #=> [Experiment, Object, Kernel, BasicObject]
p String.superclass #=> Object

Here's an example of situations where this will make a difference:

Using defined?(Nothing's printed)

class Lab
  class Coco
  end
end

class Experiment

  def diff
    ""
  end

  def show
    puts "defined" if defined?(Coco) #=> Nothing printed
  end
end

Experiment.new.show

Using self.class.const_defined? (Something's printed)

class Lab
  class Coco
  end
end

class Experiment < Lab

  def diff
    ""
  end

  def show
    puts "defined" if self.class.const_defined? :Coco #=> defined
  end
end

Experiment.new.show
p Experiment.ancestors #=> [Experiment, Lab, Object, Kernel, BasicObject] We find 'Lab' class in the ancestor chain.


问:
Not able to download Cloudera
I am trying to find a link to download cloudera zip file on VMWare , but unable to get any.

Tried searching on google , on cloudera website , but in vain.

Can somebody share some views on it.

答:
Seems Cloudera no longer supports Quickstart VM. I too faced this issue a month ago. I finally found a link to archived version here: https://www.youtube.com/watch?v=nnvheRZYLP4

In the description of the above link, you will find the Google drive link for Cloudera 5.13.0. That's all i was able to find.

Title: Not able to download Cloudera


问:
How can I read values of a pointer, being this pointer the return of a function?
This would be my code:

```<code>uint8_t* send(uint16_t sw){

uint8_t sw8[2];
uint8_t* data= NULL;

sw8[0]=sw>>8;
sw8[1]=sw&0xFF;

memcpy(data,sw,2);

return data;

}

main(){
uint8_t * resp;

resp = send(x6A00);
}
</code>```

If sw is 0x6A00 for example, *data will be 6A, and I want it to be 6A00!!!!

答:
```<code>uint8_t* data= NULL;
...
memcpy(data,sw,2);
</code>```

Here, you pass null to memcpy. The behaviour of the program is undefined.

I want [*data] to be 6A00!!!!

Then data must point to some array. You can achieve this by initialising the pointer. Exactly how you should do that depends on what you're trying to do.

I want data to point to the sw8. But if I put data=sw8, i will get &sw8[0], i don't access to the whole array, right?

Sure you do. You can simply use data[1] to access the second element.

However, if you do this, then you shouldn't return data because sw8 is an automatic variable within the function, and therefore its lifetime ends and it is automatically destroyed by the end of the function. Therefore returning a pointer to it always returns an invalid pointer.

Body:
This would be my code:

uint8_t* send(uint16_t sw){

uint8_t sw8[2];
uint8_t* data= NULL;

sw8[0]=sw>>8;
sw8[1]=sw&0xFF;

memcpy(data,sw,2);

return data;

}

main(){
uint8_t * resp;

resp = send(x6A00);
}

If sw is 0x6A00 for example, *data will be 6A, and I want it to be 6A00!!!!

Body:
uint8_t* data= NULL;
...
memcpy(data,sw,2);

Here, you pass null to memcpy. The behaviour of the program is undefined.

I want [*data] to be 6A00!!!!

Then data must point to some array. You can achieve this by initialising the pointer. Exactly how you should do that depends on what you're trying to do.

I want data to point to the sw8. But if I put data=sw8, i will get &sw8[0], i don't access to the whole array, right?

Sure you do. You can simply use data[1] to access the second element.

However, if you do this, then you shouldn't return data because sw8 is an automatic variable within the function, and therefore its lifetime ends and it is automatically destroyed by the end of the function. Therefore returning a pointer to it always returns an invalid pointer.


问:
Docker mac symfony 3 very slow
I'm starting a new project with Symfony 3 and I want to use Docker for the development environment. We will work on this project with a dozen developers so I want to have an easy install process.

Here's my docker-compose.yml

```<code>version: '2'
services:
db:
    image: mysql
    ports:
        - "3307:3306"
    environment:
        MYSQL_ROOT_PASSWORD: root
        MYSQL_DATABASE: mydb
        MYSQL_USER: root
        MYSQL_PASSWORD: root
php:
    build: ./php-fpm
    expose:
        - "9001"
    volumes:
        - .:/var/www/project
        - ./var/logs:/var/www/project/app/logs
    links:
        - db
nginx:
    build: ./nginx
    ports:
        - "8001:80"
    links:
        - php
    volumes_from:
        - php
    volumes:
        -  ./var/logs/nginx/:/var/log/nginx
</code>```

I installed the recent Docker for Mac application (beta). The big issue is that my symfony app is very very slow (a simple page takes more than 5 seconds). The same app with MAMP is much faster (500ms max). Is this a know issue of Docker ? How can I debug it ?

答:
It's possible to get performance with Docker for Mac almost as fast as native shared volumes with Linux by using Mutagen. A benchmark is available here.

I created a full example for a Symfony project, it can be used for any type of project in any language.

Title: Docker mac symfony 3 very slow

Body:
I'm starting a new project with Symfony 3 and I want to use Docker for the development environment. We will work on this project with a dozen developers so I want to have an easy install process.

Here's my docker-compose.yml

version: '2'
services:
db:
    image: mysql
    ports:
        - "3307:3306"
    environment:
        MYSQL_ROOT_PASSWORD: root
        MYSQL_DATABASE: mydb
        MYSQL_USER: root
        MYSQL_PASSWORD: root
php:
    build: ./php-fpm
    expose:
        - "9001"
    volumes:
        - .:/var/www/project
        - ./var/logs:/var/www/project/app/logs
    links:
        - db
nginx:
    build: ./nginx
    ports:
        - "8001:80"
    links:
        - php
    volumes_from:
        - php
    volumes:
        -  ./var/logs/nginx/:/var/log/nginx

I installed the recent Docker for Mac application (beta). The big issue is that my symfony app is very very slow (a simple page takes more than 5 seconds). The same app with MAMP is much faster (500ms max). Is this a know issue of Docker ? How can I debug it ?


问:
Running a bash script using a Kubenetes Service
I am not sure how dumb or un-reasonable this question is, but we are trying to see if we can do this in any way.

I have a .bash file. And I want to run this when I invoke a url.

Let's take the url is https://domainname.com/jobapi
When I invoke this on the browser, this should invoke a .bash script on the container.

Is this really possible?
If it is possible, want to know if I need to add this script as a deployment or a job?

答:
The first step, before looking at Kubernetes, is to configure a web server to run your script. This could be a generic web server like nginx or Apache, and you could add your script as a CGI script. There's plenty of tutorials out there that explain how to write CGI scripts.

Depending on the requirements of your application, a simple HTTP hook server might be a better match. Have a look at, for example, https://github.com/adnanh/webhook.

Either way, try this out with just Docker first, before trying to create a pod and potentially a service and an ingress in Kubernetes.

In a second step, to be able to access your service (the server invoking your script), you need to create a pod, probably through a deployment, and potentially a service and an ingress for it.

Kubernetes jobs are for running a script (or other program) once. They're most useful to automate maintaince tasks for your application.


问:
Swift String from an enum
I'm trying to get the text here to read the contents of the privacyNotice text String which is stored in the Content enum extension of Chat.Message.Incoming. The below does not compile at this point:

```<code>private func renderPolicy(
        isEnabled: Bool,
        resource: ChosenResource<Notice>,
        message: Chat.Message.Incoming,
        ) -> Node<NodeId> {
        return Node(
            component: Component.Message(
                ....
                text: message.content.privacyNotice.text,
                ....
        )
    }

</code>```

This is the extension:

```<code>extension Chat.Message.Incoming {
    public enum Content {
        case text(message: String, style: Style)
        case response(message: String)
        case privacyNotice(text: String, resource: ChosenResource<Notice>)
    }
}
</code>```

In the console when I hit a breakpoint and type po message.content I get the below:

```<code>(lldb) po message.content
▿ Content
  ▿ privacyNotice : 2 elements
    - text : "Privacy"
    ▿ resource : ChosenResource<Notice>
      - generator : (Function)
</code>```

So how do I navigate the error I get when I type out po message.content.privacyNotice.text, which is what I would expect to return Privacy, and therefore enable me to input this in the renderPolicy function:

```<code>(lldb) po message.content.privacyNotice.text
error: <EXPR>:3:9: error: enum case 'privacyNotice' cannot be used as an instance member
message.content.privacyNotice.text
~~~~~~~~^~~~~~~
        Chat.Message.Incoming.Content.

error: <EXPR>:3:31: error: value of type '(String, ChosenResource<Notice>) -> Chat.Message.Incoming.Content' has no member 'text'
message.content.privacyNotice.text
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^~~~
</code>```

TIA

答:
In your renderPolicy function, message.content is simply of type Content, it isn't guaranteed to be of case privacyNotice, it could also be text or response, neither of which have text associated value.

So in order to access that associated value, you need to make sure that message.content is actually of case privacyNotice - which you can do using if case ....

```<code>private func renderPolicy(
    isEnabled: Bool,
    resource: ChosenResource<Notice>,
    message: Chat.Message.Incoming,
    ) -> Node<NodeId> {
    if case .privacyNotice(text: let text, resource: _) = message.content {
        return Node(
        component: Component.Message(
            ....
            text: text,
            ....
        )
    } else {
       // handle the other casese
    }

}
</code>```

Title: Swift String from an enum

Body:
I'm trying to get the text here to read the contents of the privacyNotice text String which is stored in the Content enum extension of Chat.Message.Incoming. The below does not compile at this point:

private func renderPolicy(
        isEnabled: Bool,
        resource: ChosenResource<Notice>,
        message: Chat.Message.Incoming,
        ) -> Node<NodeId> {
        return Node(
            component: Component.Message(
                ....
                text: message.content.privacyNotice.text,
                ....
        )
    }

This is the extension:

extension Chat.Message.Incoming {
    public enum Content {
        case text(message: String, style: Style)
        case response(message: String)
        case privacyNotice(text: String, resource: ChosenResource<Notice>)
    }
}

In the console when I hit a breakpoint and type po message.content I get the below:

(lldb) po message.content
▿ Content
  ▿ privacyNotice : 2 elements
    - text : "Privacy"
    ▿ resource : ChosenResource<Notice>
      - generator : (Function)

So how do I navigate the error I get when I type out po message.content.privacyNotice.text, which is what I would expect to return Privacy, and therefore enable me to input this in the renderPolicy function:

(lldb) po message.content.privacyNotice.text
error: <EXPR>:3:9: error: enum case 'privacyNotice' cannot be used as an instance member
message.content.privacyNotice.text
~~~~~~~~^~~~~~~
        Chat.Message.Incoming.Content.

error: <EXPR>:3:31: error: value of type '(String, ChosenResource<Notice>) -> Chat.Message.Incoming.Content' has no member 'text'
message.content.privacyNotice.text
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^~~~

TIA

Body:
In your renderPolicy function, message.content is simply of type Content, it isn't guaranteed to be of case privacyNotice, it could also be text or response, neither of which have text associated value.

So in order to access that associated value, you need to make sure that message.content is actually of case privacyNotice - which you can do using if case ....

private func renderPolicy(
    isEnabled: Bool,
    resource: ChosenResource<Notice>,
    message: Chat.Message.Incoming,
    ) -> Node<NodeId> {
    if case .privacyNotice(text: let text, resource: _) = message.content {
        return Node(
        component: Component.Message(
            ....
            text: text,
            ....
        )
    } else {
       // handle the other casese
    }

}


问:
Adding FutureBuilder to ListView children property
I am currently reading some data from a textfile (async function) and displaying it using a ListView.

```<code>void readData() async {
  final file = await localFile;
  String body = await file.readAsString();
  if(body.isNotEmpty)
    ListData.tiles.addToStoredList(body);
}
</code>```

Since this is an async function, I decided to use FutureBuilder to get the list and display it

```<code>ListView(
    children : FutureBuilder <List<Widget>> ...
)
</code>```

doesn't seem to work. What is the alternative to display a list of widgets under a list view when I get data from an async function.

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

```<code>import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: Future.delayed(Duration(seconds: 2)),
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return Center(child: CircularProgressIndicator());
        }

        return ListView(
          children: [
            Container(height: 150, color: Colors.red),
            Container(height: 150, color: Colors.yellow),
            Container(height: 150, color: Colors.blue),
            Container(height: 150, color: Colors.orange),
            Container(height: 150, color: Colors.red),
          ],
        );
      },
    );
  }
}
</code>```

Body:
I am currently reading some data from a textfile (async function) and displaying it using a ListView.

void readData() async {
  final file = await localFile;
  String body = await file.readAsString();
  if(body.isNotEmpty)
    ListData.tiles.addToStoredList(body);
}

Since this is an async function, I decided to use FutureBuilder to get the list and display it

ListView(
    children : FutureBuilder <List<Widget>> ...
)

doesn't seem to work. What is the alternative to display a list of widgets under a list view when I get data from an async function.

Body:
You should try something like this

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: Future.delayed(Duration(seconds: 2)),
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return Center(child: CircularProgressIndicator());
        }

        return ListView(
          children: [
            Container(height: 150, color: Colors.red),
            Container(height: 150, color: Colors.yellow),
            Container(height: 150, color: Colors.blue),
            Container(height: 150, color: Colors.orange),
            Container(height: 150, color: Colors.red),
          ],
        );
      },
    );
  }
}


问:
How to create custom uitableview like that
I want to create uitableview like the following , also I need to add a third section that contains rows

any suggestion please

答:
<br>
You can take UITableview with style "Group" and can have 3 sections.   </p>


问:
Get axios call in reactjs
Below is the response I am getting after doing get call:

```<code>{
    "id": “12345”,
    “details”: {
        “name”: “sample doc”,
        “market: “sample market”
    }
}
</code>```

My Service Method:

```<code>ENDPOINTS = {
    product: "/market/product",
}
     getDetails(
            id: string
          ): Promise<{
            id: string;
          }> {
            const url = `${this.ENDPOINTS.PRODUCT}/${id}/name`;
            return http
              .get(url)
              .then((response) => {
                return response.data;
              })
              .catch((error) => {
                throw error;
              });
          }
</code>```

My component Method:

```<code>getTestingDone = () => {
    this.sampleService
      .getDetails(
        this.props.product.id,
      )
      .then((response) => {
        this.setState({
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };

        <TextInput
          labelText="name"
          type="text"
          name="keyname"
          value = {name}
        />
</code>```

I want to print the response in this input field. Not sure How to get the response from the server to the UI. Can anyone help me with this.Do i need to make a model class? and return it in response in service method?

答:
constructor() {
  this.state = {
    name: ''
  }
}

getTestingDone = () => {
  this.sampleService
    .getDetails(this.props.product.id)
    .then(({details: {name}}) => {
      this.setState(state => ({...state, name}));
    })
}

render() {
  const { name } = this.state;

  return <TextInput
    labelText="name"
    type="text"
    name="keyname"
    value = {name}/>
}
```

Title: Get axios call in reactjs

Body:
Below is the response I am getting after doing get call:

{
    "id": “12345”,
    “details”: {
        “name”: “sample doc”,
        “market: “sample market”
    }
}

My Service Method:

ENDPOINTS = {
    product: "/market/product",
}
     getDetails(
            id: string
          ): Promise<{
            id: string;
          }> {
            const url = `${this.ENDPOINTS.PRODUCT}/${id}/name`;
            return http
              .get(url)
              .then((response) => {
                return response.data;
              })
              .catch((error) => {
                throw error;
              });
          }

My component Method:

getTestingDone = () => {
    this.sampleService
      .getDetails(
        this.props.product.id,
      )
      .then((response) => {
        this.setState({
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };

        <TextInput
          labelText="name"
          type="text"
          name="keyname"
          value = {name}
        />

I want to print the response in this input field. Not sure How to get the response from the server to the UI. Can anyone help me with this.Do i need to make a model class? and return it in response in service method?


答:
You have to use a switch statement and apply Pattern Matching to determine your text value.

 private func renderPolicy(
    isEnabled: Bool,
    resource: ChosenResource<Notice>,
    message: Chat.Message.Incoming,
    ) -> Node<NodeId> {

    var nodeText: String

    switch message.content {
    case .response(let message):
        // you can unwrap like this or ...
        nodeText = message
    case let .privacyNotice(text, resource):
        // you can unwrap multiple wrapped values with a single 'let'
        nodeText = text
    case let .text(message, _):
        nodeText = message
    }

    return Node(
        component: Component.Message(
            ...
            text: nodeText,
            ....
    )
}
```

I hope that helps you, feel free to ask further questions.

Title: Swift String from an enum

Body:
You have to use a switch statement and apply Pattern Matching to determine your text value.

 private func renderPolicy(
    isEnabled: Bool,
    resource: ChosenResource<Notice>,
    message: Chat.Message.Incoming,
    ) -> Node<NodeId> {

    var nodeText: String

    switch message.content {
    case .response(let message):
        // you can unwrap like this or ...
        nodeText = message
    case let .privacyNotice(text, resource):
        // you can unwrap multiple wrapped values with a single 'let'
        nodeText = text
    case let .text(message, _):
        nodeText = message
    }

    return Node(
        component: Component.Message(
            ...
            text: nodeText,
            ....
    )
}

I hope that helps you, feel free to ask further questions.


问:
R user-defined function not seeing argument
I am trying to make a function in which I have to provide two arguments. For the first argument, I can enter anything, but for the second only the characters 'A' or 'B' are allowed. Then I wish to return both arguments in a list.

```<code>myFunction <- function(var1, var2){

  if(missing(var1) | var1 == ""){stop("First argument is missing")}
  if(missing(var2) | var2 != "A" | var2 != "B"){stop("Second argument is missing. Accepted values: 'A' or 'B'")}

  myList <- list("out1" = var1, "out2"=var2)
  return(myList)
}

myFunction("Hello world!", "A")
Error in myFunction("Hello world!", "A") :
  Second argument is missing. Accepted values: 'A' or 'B'
</code>```

What am I missing?

答:
It's your boolean logic.

```<code>var2 is missing = F
var2 != 'A' = F
var2 != 'B' = T
</code>```

F or F or T evaluates to T

Body:
I am trying to make a function in which I have to provide two arguments. For the first argument, I can enter anything, but for the second only the characters 'A' or 'B' are allowed. Then I wish to return both arguments in a list.

myFunction <- function(var1, var2){

  if(missing(var1) | var1 == ""){stop("First argument is missing")}
  if(missing(var2) | var2 != "A" | var2 != "B"){stop("Second argument is missing. Accepted values: 'A' or 'B'")}

  myList <- list("out1" = var1, "out2"=var2)
  return(myList)
}

myFunction("Hello world!", "A")
Error in myFunction("Hello world!", "A") :
  Second argument is missing. Accepted values: 'A' or 'B'

What am I missing?

Body:
It's your boolean logic.

var2 is missing = F
var2 != 'A' = F
var2 != 'B' = T

F or F or T evaluates to T


问:
javascript array and jsf/richfaces
I have the following code in javascript:

```<code>        <script type="text/javascript"
            src="#{facesContext.externalContext.requestContextPath}/js/sample-points.js"></script>

        <script type="text/javascript">//<![CDATA[
            var cloudmade = new CM.Tiles.CloudMade.Web({key: 'bbb'});
            var map = new CM.Map('cm-example', cloudmade);
            map.setCenter(new CM.LatLng(51.50874, 22.76367), 4);

            var markers = [];
            for (var i = 0; i < samplePoints.length; i++) {
                markers.push(new CM.Marker(new CM.LatLng(samplePoints[i][0], samplePoints[i][1])));
            }

            var clusterer = new CM.MarkerClusterer(map, {clusterRadius: 70});
            clusterer.addMarkers(markers);
        //]]></script>
</code>```

"samplePoints" is an array of coordinates which I can use to show markers on the map.

Map is showing here:

```<code><div id="cm-example" style="width: 99.5%; height: 600px"></div>
</code>```

How can I provide this array from jsf/richfaces without using file (e.g. I want to fetch those data from db, create array and send to this script)?

Thanks

答:
See this Link

using jsFunction you can load any data structure (e.g. Points), and on your clients side you get a javaScript data structure that you can easily access it (point.x).

Title: javascript array and jsf/richfaces

Body:
I have the following code in javascript:

"samplePoints" is an array of coordinates which I can use to show markers on the map.

Map is showing here:

How can I provide this array from jsf/richfaces without using file (e.g. I want to fetch those data from db, create array and send to this script)?

Thanks


问:
How to cache view for all users in Django
I'm trying to use a Memcached instance of AWS ElastiCache with a Django project.  It seems to be caching a view for a user, but if you come in on a different PC, it isn't cached until called from that PC (or same PC with different browser).

I'm not sure what I've got wrong.

Within settings.py I have

```<code>CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': os.environ.get('CACHE_LOCATION','127.0.0.1:11211'),
    }
}

MIDDLEWARE = [
    'core.middleware.DenyIndexMiddleware',
    'core.middleware.XForwardedForMiddleware',
    'core.middleware.PrimaryHostRedirectMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
    'masquerade.middleware.MasqueradeMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.contrib.sites.middleware.CurrentSiteMiddleware',
    'cms.middleware.user.CurrentUserMiddleware',
    'cms.middleware.page.CurrentPageMiddleware',
    'cms.middleware.toolbar.ToolbarMiddleware',
    'cms.middleware.language.LanguageCookieMiddleware',
    'cms.middleware.utils.ApphookReloadMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
]
</code>```

I've then  cached the views using cache_page

```<code>path('<str:service_type>/<str:location>/', cache_page(60*60)(views.canonical_search), name="canonical-search"),
</code>```

How do I cache the site so that the page is cached irrespective of the user?

EDIT
I've noticed that it never caches when using the user is logged in.

答:
Watch out for the Vary header, that cache_page() takes into account.

Usually, some middlewares may add a Vary header, for example :

CsrfViewMiddleware adds Cookie,

GZipMiddlewareadds Accept-Encoding

LanguageCookieMiddleware may add Accept-Language

meaning that as soon as you have a different Cookie (session), encoding, or language, you have a different version of cache for your page.

As for you case, the CsrfViewMiddleware may be the problem, you can add the decorator @csrf_exempt to your view so that the Vary: Cookie header is not set in the response.

More info at https://docs.djangoproject.com/en/3.0/topics/cache/#using-vary-headers

Body:
I'm trying to use a Memcached instance of AWS ElastiCache with a Django project.  It seems to be caching a view for a user, but if you come in on a different PC, it isn't cached until called from that PC (or same PC with different browser).

I'm not sure what I've got wrong.

Within settings.py I have

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': os.environ.get('CACHE_LOCATION','127.0.0.1:11211'),
    }
}

MIDDLEWARE = [
    'core.middleware.DenyIndexMiddleware',
    'core.middleware.XForwardedForMiddleware',
    'core.middleware.PrimaryHostRedirectMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
    'masquerade.middleware.MasqueradeMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.contrib.sites.middleware.CurrentSiteMiddleware',
    'cms.middleware.user.CurrentUserMiddleware',
    'cms.middleware.page.CurrentPageMiddleware',
    'cms.middleware.toolbar.ToolbarMiddleware',
    'cms.middleware.language.LanguageCookieMiddleware',
    'cms.middleware.utils.ApphookReloadMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
]

I've then  cached the views using cache_page

path('<str:service_type>/<str:location>/', cache_page(60*60)(views.canonical_search), name="canonical-search"),

How do I cache the site so that the page is cached irrespective of the user?

EDIT
I've noticed that it never caches when using the user is logged in.


问:
Representing vector field with ovals and color
I have a vector field which shows the direction of some ovals in different positions with different aspect ratio. I could plot it in Matlab by the below script:

```<code>[X, Y] = meshgrid(1:size(nx,1), 1:size(nx,2));
  quiver(X,Y, nx, ny, 'ShowArrowHead', 'Off','linewidth',1);
set(qh, 'Color', 'k');
</code>```

Where X and Y show positions in space and nx and ny show orientation of the ovals. Information on aspect ratio is inside nx and ny. So, sqrt(nx.^2+ny.^2) gives a magnitude that is between 0 and 1. If this magnitude is zero in some points, it means that in those points we have circle instead of ovals. If it is equal to 1 it means we have an elongated oval.
But it looks very basic. I want to have something in which each point in space I have a rotated oval where the color shows the aspect ratio. How can I do this in Matlab or python?

答:
You can create a grid of ellipse and apply a rotation matrix to each of them. Here is a minimal example:

[X0, Y0] = meshgrid(0:5,0:5);  % the initial grid
a        = 0.2;                % horizontal radius
b        = 0.4;                % vertical radius
t        = 0:0.01:2*pi;
rotmat   = @(phi) [cos(phi) sin(phi); -sin(phi) cos(phi)]; % A 2D anonymous rotation matrix

hold on
% For each point of the grid we plot an ellipse
for ii = 1:numel(X0)
    phi = mod((ii/20),2*pi);               % rotation by phi (in radian)
    XY  = rotmat(phi)*[a*cos(t);b*sin(t)]; % we apply the rotation to the ellipse equation
    x   = XY(1,:)+X0(ii);                  % Shift x with X0
    y   = XY(2,:)+Y0(ii);                  % Shift y with Y0
    fill(x,y,ii)                           % plot the ellipse
end
axis equal
```

And we obtain:

You just need to change the horizontal and vertical radius and phi according to nx and ny.

Body:
I have a vector field which shows the direction of some ovals in different positions with different aspect ratio. I could plot it in Matlab by the below script:

[X, Y] = meshgrid(1:size(nx,1), 1:size(nx,2));
  quiver(X,Y, nx, ny, 'ShowArrowHead', 'Off','linewidth',1);
set(qh, 'Color', 'k');

Where X and Y show positions in space and nx and ny show orientation of the ovals. Information on aspect ratio is inside nx and ny. So, sqrt(nx.^2+ny.^2) gives a magnitude that is between 0 and 1. If this magnitude is zero in some points, it means that in those points we have circle instead of ovals. If it is equal to 1 it means we have an elongated oval.
But it looks very basic. I want to have something in which each point in space I have a rotated oval where the color shows the aspect ratio. How can I do this in Matlab or python?

Body:
You can create a grid of ellipse and apply a rotation matrix to each of them. Here is a minimal example:

[X0, Y0] = meshgrid(0:5,0:5);  % the initial grid
a        = 0.2;                % horizontal radius
b        = 0.4;                % vertical radius
t        = 0:0.01:2*pi;
rotmat   = @(phi) [cos(phi) sin(phi); -sin(phi) cos(phi)]; % A 2D anonymous rotation matrix

hold on
% For each point of the grid we plot an ellipse
for ii = 1:numel(X0)
    phi = mod((ii/20),2*pi);               % rotation by phi (in radian)
    XY  = rotmat(phi)*[a*cos(t);b*sin(t)]; % we apply the rotation to the ellipse equation
    x   = XY(1,:)+X0(ii);                  % Shift x with X0
    y   = XY(2,:)+Y0(ii);                  % Shift y with Y0
    fill(x,y,ii)                           % plot the ellipse
end
axis equal

And we obtain:

You just need to change the horizontal and vertical radius and phi according to nx and ny.


问:
Bash Makefile update comments?
I need to make a shellscript that updates the comments in the C source code files for a project. I also need to add a new target to the Makefile in order to update the version number in the Makefile itself. I'll receive an (unknown name) zip file, which will have several files in it (named: calcmarks.h, calcmarks.c, correlation.c, globals.c, readmarks.c). This is what I currently have but am very confused on how to make this work

```<code>unzip $1
for file in calcmarks.h calcmarks.c correlation.c globals.c readmarks.c
do
e=`grep -oP '(?<= version )[0-9]+' file`
let f=$e+1
sed "s/version $e,/version $f, /" file  | sed "s/released.*/released $(date)/" > file
done
</code>```

I thought my shellscript would unzip the folder, and then for each of those files it will find the comment, replace the version number with the updated version number and then replace the old date with the current date, but it not working. I'm also uncertain about how I can make a new target in the Makefile to update the comment in the Makefile itself. Thank you!

答:
The problem is in the line

```<code>sed "s/version $e,/version $f, /" file  | sed "s/released.*/released $(date)/" > file
</code>```

because you are reading from the same file you are writing to. Because of the redirection you are emptying the file to write new contents at the same time you start reading.

This would fix that:

```<code>mv file file.bak
sed "s/version $e,/version $f, /" file.bak  | sed "s/released.*/released $(date)/" > file
rm file.bak
</code>```

But this would be cleaner:

```<code>sed -i "s/version $e,/version $f, /; s/released.*/released $(date)/" file
</code>```

Title: Bash Makefile update comments?

Body:
I need to make a shellscript that updates the comments in the C source code files for a project. I also need to add a new target to the Makefile in order to update the version number in the Makefile itself. I'll receive an (unknown name) zip file, which will have several files in it (named: calcmarks.h, calcmarks.c, correlation.c, globals.c, readmarks.c). This is what I currently have but am very confused on how to make this work

unzip $1
for file in calcmarks.h calcmarks.c correlation.c globals.c readmarks.c
do
e=`grep -oP '(?<= version )[0-9]+' file`
let f=$e+1
sed "s/version $e,/version $f, /" file  | sed "s/released.*/released $(date)/" > file
done

I thought my shellscript would unzip the folder, and then for each of those files it will find the comment, replace the version number with the updated version number and then replace the old date with the current date, but it not working. I'm also uncertain about how I can make a new target in the Makefile to update the comment in the Makefile itself. Thank you!

Body:
The problem is in the line

sed "s/version $e,/version $f, /" file  | sed "s/released.*/released $(date)/" > file

because you are reading from the same file you are writing to. Because of the redirection you are emptying the file to write new contents at the same time you start reading.

This would fix that:

mv file file.bak
sed "s/version $e,/version $f, /" file.bak  | sed "s/released.*/released $(date)/" > file
rm file.bak

But this would be cleaner:

sed -i "s/version $e,/version $f, /; s/released.*/released $(date)/" file


问:
How to cast Any[] to CustomType so that IntelliSense can be used to access the Properties in Angular/Typescript
We have one Angular service where we are calling the backend and getting the data and displaying it on UI.

```<code>export interface UserDataResponse { id: number; userName: string; }

AngularService_Method1() {
    return this.http.get<UserDataResponse[]>(this.appUrl + "/Application/Users")
   }
</code>```

AngularService_Method1() is written in Service layer which calls the Backend Users API to get the data. Here we clearly know how the response is. Hence, we are type casting the response as UserDataResponse[].

In Angular Component, I can get the Response and I can use this UserDataResponse[] and I can easily get the IntelliSense for id & userName properties.

We have another method in Service layer as AngularService_Method2() which returns the Array of Objects.

```<code>AngularService_Method2(someParameter:String) {
    return this.http.get<any[]>(this.appUrl + "/Application/someendpoint/" + someParameter)
}
</code>```

and here Response can be of anything any[].
It can be anything like below.
For Example - Response 1

```<code>[{"Id": 1,"Name": "Abc1","City": "Xyz1"},{"Id": 1,"Name": "Abc1","City": "Xyz1"}]
</code>```

Response 2 -

```<code>[{"EmployeeId": 100,"Email": "pqr@pqr.com","Rank": "aa1"},{"EmployeeId": 101,"Email": "xyz@pqr.com","Rank": "aa2"}]
</code>```

Question is How to cast Any[] to CustomType so that IntelliSense can be used to access the Properties in Angular/Typescript.

When Response 1 comes I should be able to access the Id,Name,City properties as IntelliSense in my Angular Component.

答:
While subscriping give the type

Eg:-

this.service.method.subscribe((data:Item[])=>//code);

Body:
We have one Angular service where we are calling the backend and getting the data and displaying it on UI.

export interface UserDataResponse { id: number; userName: string; }

AngularService_Method1() {
    return this.http.get<UserDataResponse[]>(this.appUrl + "/Application/Users")
   }

AngularService_Method1() is written in Service layer which calls the Backend Users API to get the data. Here we clearly know how the response is. Hence, we are type casting the response as UserDataResponse[].

In Angular Component, I can get the Response and I can use this UserDataResponse[] and I can easily get the IntelliSense for id & userName properties.

We have another method in Service layer as AngularService_Method2() which returns the Array of Objects.

AngularService_Method2(someParameter:String) {
    return this.http.get<any[]>(this.appUrl + "/Application/someendpoint/" + someParameter)
}

and here Response can be of anything any[].
It can be anything like below.
For Example - Response 1

[{"Id": 1,"Name": "Abc1","City": "Xyz1"},{"Id": 1,"Name": "Abc1","City": "Xyz1"}]

Response 2 -

[{"EmployeeId": 100,"Email": "pqr@pqr.com","Rank": "aa1"},{"EmployeeId": 101,"Email": "xyz@pqr.com","Rank": "aa2"}]

Question is How to cast Any[] to CustomType so that IntelliSense can be used to access the Properties in Angular/Typescript.

When Response 1 comes I should be able to access the Id,Name,City properties as IntelliSense in my Angular Component.


问:
How to change python version in Anaconda?
I am trying to get into deep learning. I installed Anaconda to use jupyter and generally not to care about installing all of those packages like matplotlib etc myself. But I cannot install tensorflow as it works only with Python  3.4, 3.5, or 3.6 but I have 3.7. After I read about it I installed python 3.6.8. I uninstalled Anaconda and installed it again, nothing changed. After that, I used this command

conda install python=3.6.8

to presumably install python 3.6.8 for it (I found this solution somewhere on the web). The command worked but didn't change anything. Please help

答: This is a bug of the macOS 10.14.6. I degrade the python version from 3.7.4 to 3.7.0 in Anaconda and it works. Here I share my solution. I solve this question in other website. Check the answer by clicking here(https://www.udemy.com/course/the-python-mega-course/learn/lecture/4775342#questions/11049798).</p>


问:
Problem with restriction in xsd
```<code><xs:restriction base="xs:any">
</code>```

Why cant I put restriction on any type like this?

答:
You can't put such restriction, because xs:any is not a type.

If you want to derive a new type by restriction and you want the base type to be just anything (elements or text) then use <xs:restriction base="xs:anyType">. If you are defining a simple type (text only), you can also use <xs:restriction base="xs:anySimpleType">

Title: Problem with restriction in xsd

Body:
<xs:restriction base="xs:any">

Why cant I put restriction on any type like this?


问:
Select only one checkbox from multiple checkbox columns in questionnaire style DataGridView
I've create an application which displays a DataGridView with a series of questions.
The dgv structure consists of one string column for the question text and three bool/checkbox columns for the answers (yes, no, N/A).
Each single question is displayed on its own row.

I would like my program to only allow the user to select only Yes, only No or only N/A on each row.

I think I would need to uncheck the other checkbox options when one option is checked but I'm not too sure on how to do this.

I've setup CellValueChanged and CellContentClick events but I'm unsure of the code needed to achieve the desired functionality.

DataGridView is bound to a DataTable.

Code I have so far:

```<code>private void dgvQuestions_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    int columnIndex = e.ColumnIndex;
    int rowIndex = e.RowIndex;

    DataGridViewCheckBoxCell chkYes = dgvQuestions.Rows[rowIndex].Cells[2] as DataGridViewCheckBoxCell;
    DataGridViewCheckBoxCell chkNo = dgvQuestions.Rows[rowIndex].Cells[3] as DataGridViewCheckBoxCell;
    DataGridViewCheckBoxCell chkNA = dgvQuestions.Rows[rowIndex].Cells[4] as DataGridViewCheckBoxCell;

    if (Convert.ToBoolean(chkYes.Value) == true)
    {

    }

    if (Convert.ToBoolean(chkNo.Value) == true)
    {

    }

    if (Convert.ToBoolean(chkNA.Value) == true)
    {

    }
}

private void dgvQuestions_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    dgvQuestions.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
</code>```

答:
It appears you have the CellContentClick set up properly, however, if there are other columns in the grid, then, it may be beneficial if you check to make sure that the cell whose content was clicked is actually one of the check box cells. Otherwise the code may be setting the cells value unnecessarily.

```<code>private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) {
  string colName = dataGridView1.Columns[e.ColumnIndex].Name;
  if (colName == "Yes" || colName == "No" || colName == "N/A") {
    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
  }
}
</code>```

In the CellValueChanged event, again the code should check for only the check box values. In addition, I would assume that at least ONE (1) of the cells MUST be checked. Example, if the “N/A” cell is originally checked, then the user “unchecks” that cell, then the row would have NO check boxes checked. This is the final check in the code such that if the user “unchecks” the “N/A” cell AND this leaves ALL check boxes “unchecked”, then, the code will “check” the “N/A” cell. Also, it is important to “turn OFF” the CellValueChanged event before we change any of the check box values IN the CellValueChanged event to avoid reentrant. Something like…

```<code>private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  if (e.RowIndex >= 0 && e.ColumnIndex >= 0) {
    string colName = dataGridView1.Columns[e.ColumnIndex].Name;
    bool checkValue;
    dataGridView1.CellValueChanged -= new DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
    switch (colName) {
      case "Yes":
        checkValue = (bool)dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value;
        if (checkValue == true) {
          dataGridView1.Rows[e.RowIndex].Cells["No"].Value = false;
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = false;
        }
        else {
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = true;
        }
        break;
      case "No":
        checkValue = (bool)dataGridView1.Rows[e.RowIndex].Cells["No"].Value;
        if (checkValue == true) {
          dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value = false;
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = false;
        }
        else {
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = true;
        }
        break;
      case "N/A":
        checkValue = (bool)dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value;
        if (checkValue == true) {
          dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value = false;
          dataGridView1.Rows[e.RowIndex].Cells["No"].Value = false;
        }
        else {
          if ((bool)dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value == false &&
              (bool)dataGridView1.Rows[e.RowIndex].Cells["No"].Value == false) {
            dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = true;
          }
        }
        break;
      default:
        break;
    }
    dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
  }
</code>```

Below is a simple example with the three columns “Yes”, “No” and “N/A” check box columns.

```<code>public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  dataGridView1.DataSource = GetTable();
}

private DataTable GetTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Yes", typeof(bool));
  dt.Columns.Add("No", typeof(bool));
  dt.Columns.Add("N/A", typeof(bool));
  for (int i = 0; i < 10; i++) {
    dt.Rows.Add(false, false, true);
  }
  return dt;
}
</code>```

Hope this helps.

Body:
I've create an application which displays a DataGridView with a series of questions.
The dgv structure consists of one string column for the question text and three bool/checkbox columns for the answers (yes, no, N/A).
Each single question is displayed on its own row.

I would like my program to only allow the user to select only Yes, only No or only N/A on each row.

I think I would need to uncheck the other checkbox options when one option is checked but I'm not too sure on how to do this.

I've setup CellValueChanged and CellContentClick events but I'm unsure of the code needed to achieve the desired functionality.

DataGridView is bound to a DataTable.

Code I have so far:

private void dgvQuestions_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    int columnIndex = e.ColumnIndex;
    int rowIndex = e.RowIndex;

    DataGridViewCheckBoxCell chkYes = dgvQuestions.Rows[rowIndex].Cells[2] as DataGridViewCheckBoxCell;
    DataGridViewCheckBoxCell chkNo = dgvQuestions.Rows[rowIndex].Cells[3] as DataGridViewCheckBoxCell;
    DataGridViewCheckBoxCell chkNA = dgvQuestions.Rows[rowIndex].Cells[4] as DataGridViewCheckBoxCell;

    if (Convert.ToBoolean(chkYes.Value) == true)
    {

    }

    if (Convert.ToBoolean(chkNo.Value) == true)
    {

    }

    if (Convert.ToBoolean(chkNA.Value) == true)
    {

    }
}

private void dgvQuestions_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    dgvQuestions.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

Body:
It appears you have the CellContentClick set up properly, however, if there are other columns in the grid, then, it may be beneficial if you check to make sure that the cell whose content was clicked is actually one of the check box cells. Otherwise the code may be setting the cells value unnecessarily.

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) {
  string colName = dataGridView1.Columns[e.ColumnIndex].Name;
  if (colName == "Yes" || colName == "No" || colName == "N/A") {
    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
  }
}

In the CellValueChanged event, again the code should check for only the check box values. In addition, I would assume that at least ONE (1) of the cells MUST be checked. Example, if the “N/A” cell is originally checked, then the user “unchecks” that cell, then the row would have NO check boxes checked. This is the final check in the code such that if the user “unchecks” the “N/A” cell AND this leaves ALL check boxes “unchecked”, then, the code will “check” the “N/A” cell. Also, it is important to “turn OFF” the CellValueChanged event before we change any of the check box values IN the CellValueChanged event to avoid reentrant. Something like…

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  if (e.RowIndex >= 0 && e.ColumnIndex >= 0) {
    string colName = dataGridView1.Columns[e.ColumnIndex].Name;
    bool checkValue;
    dataGridView1.CellValueChanged -= new DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
    switch (colName) {
      case "Yes":
        checkValue = (bool)dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value;
        if (checkValue == true) {
          dataGridView1.Rows[e.RowIndex].Cells["No"].Value = false;
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = false;
        }
        else {
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = true;
        }
        break;
      case "No":
        checkValue = (bool)dataGridView1.Rows[e.RowIndex].Cells["No"].Value;
        if (checkValue == true) {
          dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value = false;
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = false;
        }
        else {
          dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = true;
        }
        break;
      case "N/A":
        checkValue = (bool)dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value;
        if (checkValue == true) {
          dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value = false;
          dataGridView1.Rows[e.RowIndex].Cells["No"].Value = false;
        }
        else {
          if ((bool)dataGridView1.Rows[e.RowIndex].Cells["Yes"].Value == false &&
              (bool)dataGridView1.Rows[e.RowIndex].Cells["No"].Value == false) {
            dataGridView1.Rows[e.RowIndex].Cells["N/A"].Value = true;
          }
        }
        break;
      default:
        break;
    }
    dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
  }

Below is a simple example with the three columns “Yes”, “No” and “N/A” check box columns.

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  dataGridView1.DataSource = GetTable();
}

private DataTable GetTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Yes", typeof(bool));
  dt.Columns.Add("No", typeof(bool));
  dt.Columns.Add("N/A", typeof(bool));
  for (int i = 0; i < 10; i++) {
    dt.Rows.Add(false, false, true);
  }
  return dt;
}

Hope this helps.


问:
Installing all the correct versions of packages when handed over a new code base?
So i was handed over someones code base, just a zip file with a visual studio solution but it doesn't build. Just has a few hundred errors 'Type or namespace name x could not be found.' When i look at 'Manage packages for solution...' all of the packages are installed and it says the version of each one. Do I have to restore the packages? Reinstall the correct version of each one independently? How do I go about getting this solution to build on my machine? Thanks.</p>

答: welcome to what's known as "DLL HELL" if you look at the right side of the solution explorer you should see yellow warning icons on each project, dig into those and manually install the missing packages –</p>


问:
How to extract elements in an array with regard to an index?
I have a row A = [0 1 2 3 4] and an index I = [0 0 1 0 1]. I would like to extract the elements in A indexed by I, i.e. [2, 4].

My attempt:

```<code>import numpy as np
A = np.array([0, 1, 2, 3, 4])
index = np.array([0, 0, 1, 0, 1])
print(A[index])
</code>```

The result is not as I expected:

```<code>[0 0 1 0 1]
</code>```

Could you please elaborate on how to achieve my goal?

答:
I think you want boolean indexing:</p>

```<code>A[index.astype(bool)]
# array([2, 4])
</code>```

Body:
I have a row A = [0 1 2 3 4] and an index I = [0 0 1 0 1]. I would like to extract the elements in A indexed by I, i.e. [2, 4].

My attempt:

import numpy as np
A = np.array([0, 1, 2, 3, 4])
index = np.array([0, 0, 1, 0, 1])
print(A[index])

The result is not as I expected:

[0 0 1 0 1]

Could you please elaborate on how to achieve my goal?

Body:
I think you want boolean indexing:

A[index.astype(bool)]
# array([2, 4])


问:
Bringing a MS Graph Search Custom Connector into working mode
Recently Microsoft published the Microsoft Search API (beta) which provides the possibility to index external systems by creating an MS Graph search custom connector.
I created such a connector that was successful so far. I also pushed a few items to the index and in the MS admin center, I created a result type and a vertical. Now I'm able to find the regarded external items in the SharePoint Online modern search center in a dedicated tab belonging to the search vertical created before. So far so good.

But now I wonder:

How can I achieve that the external data is continuously pushed to the MS Search Index? (How can this be implemented? Is there any tutorial or a sample project? What is the underlying architecture?)

Is there a concept of Full / Incremental / Continuous Crawls for a Search Custom Connector at all? If so, how can I "hook" into a crawl in order to update changed data to the index?

Or do I have to implement it all on my own? And if so, what would be a suitable approach?

答:
Thank you for trying out the connector APIs. I am glad to hear that you are able to get items into the index and see the results.

Regarding your questions, the logic for determining when to push items, and your crawl strategy is something that you need to implement on your own. There is no one best strategy per se, and it will depend on your data source and the type of access you have to that data. For example, do you get notifications every time the data changes? If not, how do you determine what data has changed? If none of that is possible, you might need to do a periodic full recrawl, but you will need to consider the size of your data set for ingestion.

We will look into ways to reduce the amount of code you have to write in the future, but right now, this is something you have to implement on your own.

-James


问:
Kentico macro to hide widget zone / web part zone if it contains no web parts
My widget zone (a webpartzone) has before/after HTML to fit it into the layout of the page.  However, if editors choose not to include any web parts, then I would like to set the zone's visible field to false.  Any idea how to access the current zone's child count in a macro?</p>

答: You can hide web parts by checking if the web part has content or not.  But I don't believe you can set the visibility of a zone based on the zone having content or not.  </p>


问:
cmath header confusion
What is the namespace for math functions? Global or std?

Consider cos function. It has 3 overloads. But there is also legacy cos from math.h. C doesn't know anything about function overloading. Therefore cos(x) can't be resolved to cos(float). The solution is to call the single precision version explicitly cosf(x). Did I miss anything?

答:
If you are using C++ you can rely on the function overloading.

There are three version of cos:

```<code>double cos (      double x );
float cos (       float x );
long double cos ( long double x );
</code>```

But if you are using only C or you want portabilty only the double version of this function exists with this name. The float function is cosf.

Title: cmath header confusion

Body:
If you are using C++ you can rely on the function overloading.

There are three version of cos:

double cos (      double x );
float cos (       float x );
long double cos ( long double x );

But if you are using only C or you want portabilty only the double version of this function exists with this name. The float function is cosf.


问:
How do I find highest value using pointer?
I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.

```<code>#include <iostream>
#include <string>
using namespace std;
int main() {
  int a[10], i, index;
  int *p, *max;
  for (i = 0; i < 10; i++) cin >> a[i];
  max = 0;
  p = &a[10];
  for (index = 0; index < 10; index++) {
    if ((p[index]) > *max) {
      *max = (p[index]);
    }
  }
  cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
  return 0;
}
</code>```

答:
There are several problems.

First, p should point to the array's first element, so you should have p = &a[0].

You can also rely on implicit conversion and just write p = a;, which is exactly the same.

&a[10] is the pointer "one-past-the-end" of the array, and dereferencing it is undefined.

Next, you want max to point to the maximum element.

It should also start at the beginning of the array, like p.

Then, when you find a new maximum, you should make max point to that element, not change the value max points to.

Lastly, index will always be 10 after the search loop.

(Take a few moments to think about why.)

You don't need it – the index is the difference between the location of the maximum element and the beginning of the array.

```<code>int main()
{
    int a[10];
    for(int i = 0; i < 10; i++)
        cin >> a[i];
    int* max = &a[0];
    int* p = &a[0];
    for (int index = 0; index < 10; index++){
        if (p[index] > *max){
            max = &p[index];
        }
    }
    cout << "Highest value= " << *max << endl << "is at index= "<< max - a << endl;
}
</code>```

Body:
I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.

#include <iostream>
#include <string>
using namespace std;
int main() {
  int a[10], i, index;
  int *p, *max;
  for (i = 0; i < 10; i++) cin >> a[i];
  max = 0;
  p = &a[10];
  for (index = 0; index < 10; index++) {
    if ((p[index]) > *max) {
      *max = (p[index]);
    }
  }
  cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
  return 0;
}

Body:
There are several problems.

First, p should point to the array's first element, so you should have p = &a[0].

You can also rely on implicit conversion and just write p = a;, which is exactly the same.

&a[10] is the pointer "one-past-the-end" of the array, and dereferencing it is undefined.

Next, you want max to point to the maximum element.

It should also start at the beginning of the array, like p.

Then, when you find a new maximum, you should make max point to that element, not change the value max points to.

Lastly, index will always be 10 after the search loop.

(Take a few moments to think about why.)

You don't need it – the index is the difference between the location of the maximum element and the beginning of the array.

int main()
{
    int a[10];
    for(int i = 0; i < 10; i++)
        cin >> a[i];
    int* max = &a[0];
    int* p = &a[0];
    for (int index = 0; index < 10; index++){
        if (p[index] > *max){
            max = &p[index];
        }
    }
    cout << "Highest value= " << *max << endl << "is at index= "<< max - a << endl;
}


问:
How to use R function properly
I have a dataframe named data and columns comfort, condition and few others.
I do one and the same manipulations with 5 columns and decided to write the following function:

```<code>replacing_na_999<-function(df, variable){
  #variable<-as.name(variable)
  levels <- levels(df$variable)
  levels[length(levels) + 1] <- "999"
  df$variable <- factor(df$variable, levels = levels)
  df$variable[is.na(df$variable)] <- "999"
}

</code>```

When I try:

```<code>replacing_na_999(data, comfort)
</code>```

it returns an error:

```<code> Error in `$<-.data.frame`(`*tmp*`, variable, value = integer(0)) :
  replacement has 0 rows, data has 44070
</code>```

Can someone help me please with syntaxis?

答:
perhaps something on the line of:

```<code>replacing_na_999<-function(df, variable){
  idx <- which(variable == names(df))
  #variable<-as.name(variable)
  levels <- levels(df[idx])
  levels[length(levels) + 1] <- "999"
  df[idx] <- factor(df[idx], levels = levels)
  df[idx][is.na(df[idx])] <- "999"
  return(df)
}
</code>```

will avoid to pass the name as argument to your function

Title: How to use R function properly

Body:
I have a dataframe named data and columns comfort, condition and few others.
I do one and the same manipulations with 5 columns and decided to write the following function:

replacing_na_999<-function(df, variable){
  #variable<-as.name(variable)
  levels <- levels(df$variable)
  levels[length(levels) + 1] <- "999"
  df$variable <- factor(df$variable, levels = levels)
  df$variable[is.na(df$variable)] <- "999"
}

When I try:

replacing_na_999(data, comfort)

it returns an error:

 Error in `$<-.data.frame`(`*tmp*`, variable, value = integer(0)) :
  replacement has 0 rows, data has 44070

Can someone help me please with syntaxis?

Body:
perhaps something on the line of:

replacing_na_999<-function(df, variable){
  idx <- which(variable == names(df))
  #variable<-as.name(variable)
  levels <- levels(df[idx])
  levels[length(levels) + 1] <- "999"
  df[idx] <- factor(df[idx], levels = levels)
  df[idx][is.na(df[idx])] <- "999"
  return(df)
}

will avoid to pass the name as argument to your function


问:
Should I not be subclassing the Cocos2d CCDirector class?
I'm trying to make cocos2d work as an RPG engine. I'm thinking of making a class that will coordinate the movements of the characters, the map loading/unloading etc. Should I make a CCNode for this, or just extend the CCDirector? Is there a reason not to subclass the CCDirector?

答:
I have never seen a subclass of CCDirector except the subclasses in cocos2d (CCDirectorDisplayLink, CCDirectorTimer or so on). Subclasses of CCDirector are allowed to create, but it is not really needed.

If you want a method that is invoked for every frame, you can use CCScheduler -scheduleSelector:forTarget:interval:paused: method. It will invoke the selector for every frame from the main loop.

```<code>[[CCScheduler sharedScheduler]
    scheduleSelector:@selector(tick:) forTarget:self interval:0 paused:NO];
</code>```

And CCScene is able to use for loading/unloading resource data, or etc.

Also, how about these tutorials?

COCOS2D IPHONE TUTORIALS - 12 CREATING RPG WITH TILED MAP

Body:
I have never seen a subclass of CCDirector except the subclasses in cocos2d (CCDirectorDisplayLink, CCDirectorTimer or so on). Subclasses of CCDirector are allowed to create, but it is not really needed.

If you want a method that is invoked for every frame, you can use CCScheduler -scheduleSelector:forTarget:interval:paused: method. It will invoke the selector for every frame from the main loop.

[[CCScheduler sharedScheduler]
    scheduleSelector:@selector(tick:) forTarget:self interval:0 paused:NO];

And CCScene is able to use for loading/unloading resource data, or etc.

Also, how about these tutorials?

COCOS2D IPHONE TUTORIALS - 12 CREATING RPG WITH TILED MAP