问:
Best Method to Turn a Deep Matching Table into a Flat One
I've got a mysql table that's deep, with 4 columns

```<code>source1 | id1 | source2 | id2
red     |   1 | blue    |   1
red     |   1 | green   |   3
red     |   1 | green   |   6
red     |   2 | blue    |   2
red     |   3 | blue    |   2
</code>```

What I'd like is something like....
(source)_ids, (source)_ids, (source)_ids, (source)_ids, etc, with a different column for each distinct source.

so

becomes....

```<code>red_ids | blue_ids | green_ids
1       |   1      | 3, 6
2,3     |   2      | NULL
</code>```

I have tried to accomplish this with case and group_concat but haven't quite gotten my wanted results. Before I try to do this by just writing a python program, anyone know if there's a normal convention for this?

Dynamic would be way preferable, in case new sources are added.

Thanks in advance.

答:
Actually, this problem is trickier than first appears. It seems to me to be next to impossible to think of a way to construct it dynamically in SQL - so I would be sorely to tempted to switch to an application layer solution - but someone might have another idea...</p>

```<code>     SELECT GROUP_CONCAT(DISTINCT r.id1) red
          , GROUP_CONCAT(DISTINCT b.id2) blue
          , GROUP_CONCAT(DISTINCT g.id2) green
       FROM my_table r
       LEFT
       JOIN my_table b
         ON b.id1 = r.id1
        AND b.source2 = 'blue'
       LEFT
       JOIN my_table g
         ON g.id1 = r.id1
        AND g.source2 = 'green'
      WHERE r.source1 = 'red'
      GROUP
         BY r.source1
          , b.source2
          , g.source2;
</code>```

Body:
I've got a mysql table that's deep, with 4 columns

source1 | id1 | source2 | id2
red     |   1 | blue    |   1
red     |   1 | green   |   3
red     |   1 | green   |   6
red     |   2 | blue    |   2
red     |   3 | blue    |   2

What I'd like is something like....
(source)_ids, (source)_ids, (source)_ids, (source)_ids, etc, with a different column for each distinct source.

so

becomes....

red_ids | blue_ids | green_ids
1       |   1      | 3, 6
2,3     |   2      | NULL

I have tried to accomplish this with case and group_concat but haven't quite gotten my wanted results. Before I try to do this by just writing a python program, anyone know if there's a normal convention for this?

Dynamic would be way preferable, in case new sources are added.

Thanks in advance.

Body:
Actually, this problem is trickier than first appears. It seems to me to be next to impossible to think of a way to construct it dynamically in SQL - so I would be sorely to tempted to switch to an application layer solution - but someone might have another idea...

     SELECT GROUP_CONCAT(DISTINCT r.id1) red
          , GROUP_CONCAT(DISTINCT b.id2) blue
          , GROUP_CONCAT(DISTINCT g.id2) green
       FROM my_table r
       LEFT
       JOIN my_table b
         ON b.id1 = r.id1
        AND b.source2 = 'blue'
       LEFT
       JOIN my_table g
         ON g.id1 = r.id1
        AND g.source2 = 'green'
      WHERE r.source1 = 'red'
      GROUP
         BY r.source1
          , b.source2
          , g.source2;


来源: stackexchange

问:
Spark BigQuery Connector: Writing ARRAY type causes exception: ""Invalid value for: ARRAY is not a valid value""
Running a Spark job in Google Cloud Dataproc.  Using the BigQuery Connector to load json data output from the job into a BigQuery table.

BigQuery Standard-SQL data types documentation states the ARRAY type is supported.

My Scala code is:

```<code>val outputDatasetId = "mydataset"
val tableSchema = "["+
    "{'name': '_id', 'type': 'STRING'},"+
    "{'name': 'array1', 'type': 'ARRAY'},"+
    "{'name': 'array2', 'type': 'ARRAY'},"+
    "{'name': 'number1', 'type': 'FLOAT'}"+
    "]"

// Output configuration
BigQueryConfiguration.configureBigQueryOutput(
    conf, projectId, outputDatasetId, "outputTable",
    tableSchema)

//Write visits to BigQuery
jsonData.saveAsNewAPIHadoopDataset(conf)
</code>```

But the job throws this exception:

```<code>{
  "code" : 400,
  "errors" : [ {
  "domain" : "global",
  "message" : "Invalid value for: ARRAY is not a valid value",
  "reason" : "invalid"
   } ],
  "message" : "Invalid value for: ARRAY is not a valid value"
}
    at

com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel.waitForCompletionAnThrowIfUploadFailed(AbstractGoogleAsyncWriteChannel.java:432)
    at com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel.close(AbstractGoogleAsyncWriteChannel.java:287)
    at com.google.cloud.hadoop.io.bigquery.BigQueryRecordWriter.close(BigQueryRecordWriter.java:358)
    at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1$$anonfun$12$$anonfun$apply$5.apply$mcV$sp(PairRDDFunctions.scala:1124)
    at org.apache.spark.util.Utils$.tryWithSafeFinallyAndFailureCallbacks(Utils.scala:1366)
    ... 8 more
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException:
400 Bad Request
</code>```

Is this a Legacy vs. Standard SQL issue?  Or is ARRAY type not supported by the BigQuery Connector for Spark?

答:
Instead of using type=ARRAY, try setting the type as you normally would but also set the key mode=REPEATED.

An array of strings for instance would be defined as:

```<code>{'name': 'field1', 'type': 'STRING', 'mode': 'REPEATED'}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Running a Spark job in Google Cloud Dataproc.  Using the BigQuery Connector to load json data output from the job into a BigQuery table.

BigQuery Standard-SQL data types documentation states the ARRAY type is supported.

My Scala code is:

val outputDatasetId = "mydataset"
val tableSchema = "["+
    "{'name': '_id', 'type': 'STRING'},"+
    "{'name': 'array1', 'type': 'ARRAY'},"+
    "{'name': 'array2', 'type': 'ARRAY'},"+
    "{'name': 'number1', 'type': 'FLOAT'}"+
    "]"

// Output configuration
BigQueryConfiguration.configureBigQueryOutput(
    conf, projectId, outputDatasetId, "outputTable",
    tableSchema)

//Write visits to BigQuery
jsonData.saveAsNewAPIHadoopDataset(conf)

But the job throws this exception:

{
  "code" : 400,
  "errors" : [ {
  "domain" : "global",
  "message" : "Invalid value for: ARRAY is not a valid value",
  "reason" : "invalid"
   } ],
  "message" : "Invalid value for: ARRAY is not a valid value"
}
    at

com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel.waitForCompletionAnThrowIfUploadFailed(AbstractGoogleAsyncWriteChannel.java:432)
    at com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel.close(AbstractGoogleAsyncWriteChannel.java:287)
    at com.google.cloud.hadoop.io.bigquery.BigQueryRecordWriter.close(BigQueryRecordWriter.java:358)
    at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1$$anonfun$12$$anonfun$apply$5.apply$mcV$sp(PairRDDFunctions.scala:1124)
    at org.apache.spark.util.Utils$.tryWithSafeFinallyAndFailureCallbacks(Utils.scala:1366)
    ... 8 more
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException:
400 Bad Request

Is this a Legacy vs. Standard SQL issue?  Or is ARRAY type not supported by the BigQuery Connector for Spark?

Body:
Instead of using type=ARRAY, try setting the type as you normally would but also set the key mode=REPEATED.

An array of strings for instance would be defined as:

{'name': 'field1', 'type': 'STRING', 'mode': 'REPEATED'}


答: Are these arrays of strings? Integers? I believe that using this API, you need to set the type to the element type, e.g. STRING or INT64, but use a mode of REPEATED. The BigQuery APIs have not yet been fully updated to use standard SQL types everywhere, so you need to use the legacy convention of type + mode instead.

Title: Spark BigQuery Connector: Writing ARRAY type causes exception: ""Invalid value for: ARRAY is not a valid value""


问:
Multiple Elements to Flat String Transform
I am looking to transform multiple elements from source xml and combine them in single target string element in comma separated text.

Conditions
Source Inputs are boolean type, only if value true it should be included in target list

E.g. XML

```<code><Root-Element>
<EnggTypes>
<Engg1>true</Engg1>
<Engg2>true</Engg2>
<Engg3>false</Engg3>
<Engg4>false</Engg4>
<Engg5>true</Engg5>
</EnggTypes>
</Root-Element>
</code>```

Expected Transform

```<code><Root-Element>
<RoleTypes>Role1,Role2,Role5</RoleTypes>
</Root-Element>
</code>```

Looking to achieve same in XSL 1.0 or 2.0

I started overthinking and tried to use a variable on a target side to see if I can do some choose/when to construct the string using previous value and concatenate but seems like that will not work as variable value cannot be changed once set!

```<code><xsl:variable name="roleVar">
<xsl:if test="Engg1/text()='true'">Role1</if>
<xsl:if test="Engg2/text()='true'">concat(roleVar,",",Role2)</if>
<xsl:if test="Engg3/text()='true'">concat(roleVar,",",Role3)</if>
<xsl:if test="Engg4/text()='true'">concat(roleVar,",",Role4)</if>
<xsl:if test="Engg5/text()='true'">concat(roleVar,",",Role5)</if>
</xsl:variable>
</code>```

Any inputs appreciated.

Thanks in advance

答:
XSLT 1.0 solution:</p>

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="EnggTypes">
    <xsl:copy>
      <RoleTypes>
        <xsl:apply-templates select="*[starts-with(local-name(), 'Engg')][text() = 'true']"/>
      </RoleTypes>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*[starts-with(local-name(), 'Engg')][text() = 'true']">
    <xsl:value-of select="concat('Role', substring-after(local-name(), 'Engg'))"/>

    <xsl:if test="position() != last()">
      <xsl:text>,</xsl:text>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>
</code>```

Body:
I am looking to transform multiple elements from source xml and combine them in single target string element in comma separated text.

Conditions
Source Inputs are boolean type, only if value true it should be included in target list

E.g. XML

<Root-Element>
<EnggTypes>
<Engg1>true</Engg1>
<Engg2>true</Engg2>
<Engg3>false</Engg3>
<Engg4>false</Engg4>
<Engg5>true</Engg5>
</EnggTypes>
</Root-Element>

Expected Transform

<Root-Element>
<RoleTypes>Role1,Role2,Role5</RoleTypes>
</Root-Element>

Looking to achieve same in XSL 1.0 or 2.0

I started overthinking and tried to use a variable on a target side to see if I can do some choose/when to construct the string using previous value and concatenate but seems like that will not work as variable value cannot be changed once set!

<xsl:variable name="roleVar">
<xsl:if test="Engg1/text()='true'">Role1</if>
<xsl:if test="Engg2/text()='true'">concat(roleVar,",",Role2)</if>
<xsl:if test="Engg3/text()='true'">concat(roleVar,",",Role3)</if>
<xsl:if test="Engg4/text()='true'">concat(roleVar,",",Role4)</if>
<xsl:if test="Engg5/text()='true'">concat(roleVar,",",Role5)</if>
</xsl:variable>

Any inputs appreciated.

Thanks in advance

Body:
XSLT 1.0 solution:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="EnggTypes">
    <xsl:copy>
      <RoleTypes>
        <xsl:apply-templates select="*[starts-with(local-name(), 'Engg')][text() = 'true']"/>
      </RoleTypes>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*[starts-with(local-name(), 'Engg')][text() = 'true']">
    <xsl:value-of select="concat('Role', substring-after(local-name(), 'Engg'))"/>

    <xsl:if test="position() != last()">
      <xsl:text>,</xsl:text>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>


问:
Send HTTP Request and properly ignore the Response in Javascript
Examples abound of methods to initiate a web (HTTP) request in Javascript. But, when I initiate a web request and the server return a blank response, Firefox at least throws an error:

XML Parsing Error: no root element found Location: http://example.com/service Line Number 1, Column 1: 1 service:1:1

I am using a function similar to:

```<code>function RequestGET(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.send();
}
</code>```

In this particular case, the server has nothing to return and I expect that. So, how do I structure my client-side script to handle this response without throwing this error? Or, more generally, how can I handle a non-XML response properly?

答:
responseXML may === null

The XMLHttpRequest.responseXML property is a read-only value which returns a Document containing the HTML or XML retrieved by the request, or null if the request was unsuccessful, has not yet been sent, or if the retrieved data can't be correctly parsed as XML or HTML.

Something like the below will catch and handle the many possible returns we can expect.

var xhr = new XMLHttpRequest(),
    handleResponses = function( x ) {
        var s = x.status;
        if ( s < 400 ) {
            if ( s === 200 ) {
                var rXML = x.responseXML;
                if ( rXML !== null ) {
                    console.log( rXML );
                } else {
                    console.error( "Not XML" );
                    console.log( x.response );
                }
            } else {
                console.warn(
                    { 204: "No Content",
                      304: "Not Modified" // etc.
                    }[ s ] || "Nothingness..."
                );
            }
        } else {
            console.error(
                { 400: "Bad Request",
                  404: "Not Found" // etc.
                }[ s ] || "Oh snap!"
            );
        }
    };
xhr.open( "GET", "https://example.com/service", true );
xhr.addEventListener( "error", function() {
    // If this happens, the request effectively failed.
    console.error( "The internet is empty" );
}, false );
xhr.addEventListener( "readystatechange", function() {
    // Even if the request fails, this will happen.
    if ( xhr.readyState === 4 ) {
        handleResponses( xhr );
    }
}, false );
xhr.send();```

Body:
Examples abound of methods to initiate a web (HTTP) request in Javascript. But, when I initiate a web request and the server return a blank response, Firefox at least throws an error:

XML Parsing Error: no root element found Location: http://example.com/service Line Number 1, Column 1: 1 service:1:1

I am using a function similar to:

function RequestGET(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.send();
}

In this particular case, the server has nothing to return and I expect that. So, how do I structure my client-side script to handle this response without throwing this error? Or, more generally, how can I handle a non-XML response properly?


问:
How to find neighbors within a distance for an unconnected node within a networkx python graph
I would like to simulate a wireless network with time-varying and mobile behaviour of the nodes. Thus, I need every time that the node wakes up or moves to search for its neighbours within a distance. How can I find the nearby nodes? There exist any functions?  Thank you

答:
It's a single function: ego_graph. It lets you specify a distance parameter, called the radius.

```<code>import networkx as nx

# Sample data
G = nx.florentine_families_graph()
nx.draw_networkx(G, with_labels=True)

# Desired graph
H = nx.ego_graph(G, node=4, radius=2)
nx.draw_networkx(H, with_labels=True)
</code>```

The entire Florentine families graph:

And just those within distance 2 of the node 'Acciauoli':

If you're using a distance measure other than simple topological distance (i.e. counting edges), you can provide the distance parameter to the ego_graph function to specify an edge attribute to use for distance.

Body:
It's a single function: ego_graph. It lets you specify a distance parameter, called the radius.

import networkx as nx

# Sample data
G = nx.florentine_families_graph()
nx.draw_networkx(G, with_labels=True)

# Desired graph
H = nx.ego_graph(G, node=4, radius=2)
nx.draw_networkx(H, with_labels=True)

The entire Florentine families graph:

And just those within distance 2 of the node 'Acciauoli':

If you're using a distance measure other than simple topological distance (i.e. counting edges), you can provide the distance parameter to the ego_graph function to specify an edge attribute to use for distance.

ContentLicense: CC BY-SA 4.0


问:
R: evaluating multiple conditionals multiple times
I have data like this:

```<code>df = as.data.frame(cbind(
  event1 = c(88.76,96.04,99.60,88.76,99.60,34.04,96.04,87.03,87.44,87.44),
  time1 = c(0.100,0.033,0.000,0.117,0.000,0.000,0.050,0.500,0.133,0.117),
  event2 = c(NA,99.60,NA,34.04,99.62,88.76,87.44,87.41,88.76,88.76),
  time2 = c(NA,0.050,NA,0.100,0.017,0.083,0.200,0.500,0.133,0.050),
  event100 = c(NA,89.52,NA,34.04,93.93,34.02,88.76,88.01,88.01,87.41),
  time100 = c(NA,0.050,NA,0.100,0.033,0.117,0.300,0.500,0.233,0.300),
  event_88.76_within_0.1 = rep(0,10)
))
</code>```

where event1 is the code for the first event a subject had and time1 is how long it took before event1 happened, and each subject has up to 100 events and times to events.

I am trying to create a variable (event_88.76_within_0.1) that indicates if event 88.76 happened within 0.1 minutes.  So it would equal 1 if any of a subject's events equals 88.76 and the corresponding time to event is less than or equal to 0.1.

Using this nested for loop:

```<code>for(r in 1:nrow(df)){ #for each subject
  for(c in 1:6){ #for each event
    if( !is.na(df[r, c]) & df[r, c] == 88.76 & df[r,(c+1)] <= 0.1){
#if the event code is not missing and if it's the needed event code and
#the next column over (the corresponding time to event) is less than 0.1
      df[r,"event_88.76_within_0.1"] = 1
    }
    i = i + 2  #skip 2 columns to get to next event code
  }
}
</code>```

I can get this, which is what I want:

```<code>      event1 time1 event2 time2 event100 time100 event_88.76_within_0.1
 [1,]  88.76 0.100     NA    NA       NA      NA                      1
 [2,]  96.04 0.033  99.60 0.050    89.52   0.050                      0
 [3,]  99.60 0.000     NA    NA       NA      NA                      0
 [4,]  88.76 0.117  34.04 0.100    34.04   0.100                      0
 [5,]  99.60 0.000  99.62 0.017    93.93   0.033                      0
 [6,]  34.04 0.000  88.76 0.083    34.02   0.117                      1
 [7,]  96.04 0.050  87.44 0.200    88.76   0.300                      0
 [8,]  87.03 0.500  87.41 0.500    88.01   0.500                      0
 [9,]  87.44 0.133  88.76 0.133    88.01   0.233                      0
[10,]  87.44 0.117  88.76 0.050    87.41   0.300                      1
</code>```

But the data set has thousands of subjects (each with 100 possible events), so the nested for loops take a while to run.

I would like to vectorize the above loop to something like this:

```<code>df$event_88.76_within_0.1 = 0
df$event_88.76_within_0.1[df[ "events that equal 88.76 and occurred within 0.1" ]]=1
</code>```

but I haven't had any luck.

Any help would be greatly appreciated.

Body:
I have data like this:

df = as.data.frame(cbind(
  event1 = c(88.76,96.04,99.60,88.76,99.60,34.04,96.04,87.03,87.44,87.44),
  time1 = c(0.100,0.033,0.000,0.117,0.000,0.000,0.050,0.500,0.133,0.117),
  event2 = c(NA,99.60,NA,34.04,99.62,88.76,87.44,87.41,88.76,88.76),
  time2 = c(NA,0.050,NA,0.100,0.017,0.083,0.200,0.500,0.133,0.050),
  event100 = c(NA,89.52,NA,34.04,93.93,34.02,88.76,88.01,88.01,87.41),
  time100 = c(NA,0.050,NA,0.100,0.033,0.117,0.300,0.500,0.233,0.300),
  event_88.76_within_0.1 = rep(0,10)
))

where event1 is the code for the first event a subject had and time1 is how long it took before event1 happened, and each subject has up to 100 events and times to events.

I am trying to create a variable (event_88.76_within_0.1) that indicates if event 88.76 happened within 0.1 minutes.  So it would equal 1 if any of a subject's events equals 88.76 and the corresponding time to event is less than or equal to 0.1.

Using this nested for loop:

for(r in 1:nrow(df)){ #for each subject
  for(c in 1:6){ #for each event
    if( !is.na(df[r, c]) & df[r, c] == 88.76 & df[r,(c+1)] <= 0.1){
#if the event code is not missing and if it's the needed event code and
#the next column over (the corresponding time to event) is less than 0.1
      df[r,"event_88.76_within_0.1"] = 1
    }
    i = i + 2  #skip 2 columns to get to next event code
  }
}

I can get this, which is what I want:

      event1 time1 event2 time2 event100 time100 event_88.76_within_0.1
 [1,]  88.76 0.100     NA    NA       NA      NA                      1
 [2,]  96.04 0.033  99.60 0.050    89.52   0.050                      0
 [3,]  99.60 0.000     NA    NA       NA      NA                      0
 [4,]  88.76 0.117  34.04 0.100    34.04   0.100                      0
 [5,]  99.60 0.000  99.62 0.017    93.93   0.033                      0
 [6,]  34.04 0.000  88.76 0.083    34.02   0.117                      1
 [7,]  96.04 0.050  87.44 0.200    88.76   0.300                      0
 [8,]  87.03 0.500  87.41 0.500    88.01   0.500                      0
 [9,]  87.44 0.133  88.76 0.133    88.01   0.233                      0
[10,]  87.44 0.117  88.76 0.050    87.41   0.300                      1

But the data set has thousands of subjects (each with 100 possible events), so the nested for loops take a while to run.

I would like to vectorize the above loop to something like this:

df$event_88.76_within_0.1 = 0
df$event_88.76_within_0.1[df[ "events that equal 88.76 and occurred within 0.1" ]]=1

but I haven't had any luck.

Any help would be greatly appreciated.

Body:
You could do it this way:

## Define the names of your events and times columns
events = paste0("event",c(1,2,100))
times = paste0("time",c(1,2,100))
## Check if your two conditions are met and multiply the results (multiplying TRUE by TRUE gives 1, multiplying TRUE or FALSE by FALSE returns 0)
df$event_88.76_within_0.1 = pmin(1,rowSums((df[,events]==88.76)*(df[,times]<=0.1),na.rm=T))

   event1 time1 event2 time2 event100 time100 event_88.76_within_0.1
1   88.76 0.100     NA    NA       NA      NA                      1
2   96.04 0.033  99.60 0.050    89.52   0.050                      0
3   99.60 0.000     NA    NA       NA      NA                      0
4   88.76 0.117  34.04 0.100    34.04   0.100                      0
5   99.60 0.000  99.62 0.017    93.93   0.033                      0
6   34.04 0.000  88.76 0.083    34.02   0.117                      1
7   96.04 0.050  87.44 0.200    88.76   0.300                      0
8   87.03 0.500  87.41 0.500    88.01   0.500                      0
9   87.44 0.133  88.76 0.133    88.01   0.233                      0
10  87.44 0.117  88.76 0.050    87.41   0.300                      1


问:
Returning the Default Property
I fill A1 and A2 as follows:

I then run:

```<code>Sub WhatIsGoingOn()
    Dim r As Range, sh As Worksheet

    Set r = Range(Cells(1, 1))
    Set sh = Sheets(Cells(2, 1))
End Sub
</code>```

I expected that in both cases, VBA would use the default property of Cells (the Value) property to Set each variable.  However I get a runtime error 13 on the last line of code!

In order to avoid errors, I must use:

```<code>Sub WhatIsGoingOn2()
    Dim r As Range, sh As Worksheet

    Set r = Range(Cells(1, 1))
    Set sh = Sheets(Cells(2, 1).Value)
End Sub
</code>```

What is going on here ??

答:
Perhaps Leviathan's comment that "Inconsistency is one of the strengths of VBA..." may ring true, but there are some contextual details that his answer neglects (and is technically incorrect on some subtle points).  He is correct that for the given code that all of the parameters are variants, but the statement that "no type coercion will be necessary" can be misleading and perhaps just wrong in many cases.  Even if many objects and methods are programmed to handle multiple types and default values, this very question reveals that it is a mistake to avoid purposely ensuring (or coercing) the correct data type.  Avoiding default properties altogether (by always typing out the full reference) can avoid many headaches.

A significant difference between the lines of code for this particular question is this:  Range is a property that takes parameters, while Sheets is also a property but has no parameters.  Range and Sheets are NOT objects in this context, even though they are properties which do return Range and Sheets objects, respectively.  They are properties of an (automatic global) object defined for the particular module or Excel workbook instance.  This detail is not trivial for understanding what the code is actually doing.

The Obect Browser in the VBA window reveals the following metadata for the two properties:

```<code>Property Range(Cell1, [Cell2]) As Range
Property Sheets As Sheets
</code>```

For Range(Cells(1, 1)), the argument Cells(1,1) is passed to the parameter Cell1.  Cells itself is a property of the Excel.Global hidden object and it returns a Range object, so that Cells(rowindex, colindex) is calling a hidden default property of the Range class equivalent to Cells._Default(rowindex, colindex).  The return type of the property _Default() is not declared, so technically it could return any type in a variant, but inspection shows that it returns a Range object.  Apparently passing a Range object to its default property will attempt to take the default value and if it is a valid range value, like a string with a range expression, then it will execute without error.

The default property for the Sheets class is the parameterized hidden _Default(Index) method.  Thus, Sheets(Cells(2, 1)) is equivalent to Sheets._Default(Cells(2, 1)).  More importantly, it means that Sheets._Default(Cells(2, 1)) is passing a Range object as an index value, but documentation says that it expects an integer or string value.  We already mentioned that the index parameter is variant... and when passing an object to a variant, it always passes the actual object and never its default property.  So we know that Sheets.Item obtains a Range object in that call.  Here is were Levithan was correct in that Sheets.Item can decide what to do with it.  It is likely that it could have been smart enough to get the single string value and continue without error.  Other collection objects (with a default Item(index) property) in MS Office objects do not seem to exhibit this same "pickiness", so it appears that Sheets._Default() (and perhaps Sheets.Item()) is being rather strict on validating its arguments.  But this is just a particular design issue with this method only... not necessarily an overall issue with VBA.

What can be difficult is determining exactly what the source objects of the properties are.  Inside the ThisWorkbook module, Me.Sheets reveals that Sheets is a property of the particular Workbook for the module.  But Me.Range is not valid in the Workbook module, but right-clicking on the Range property (without the Me qualifier) and choosing "Definition" results in the message "Cannot jump to Range because it is hidden".  However, once in the Object Browser, righ-clicking within the browser one can choose "Show Hidden Members" which will then allow navigating to the hidden Global objects and other hidden members.

Why the inconsistency and the hidden properties? In an attempt to make the current instance of Excel and all of its components accessible in a "natural" way, Excel (and all Office applications) implement these various hidden properties to avoid the "complexity" of having to repeatedly discover and type out full references.  For instance, the automatic global Application object also has both Range and Sheets properties.  Actual documentation for Application.Sheets, for example, says "Using this property without an object qualifier is equivalent to using ActiveWorkbook.Sheets".  Even that documentation fails to say is that ActiveWorkbook is in turn a property of the global Excel Application object'.

Title: Returning the Default Property

Body:
I fill A1 and A2 as follows:

I then run:

Sub WhatIsGoingOn()
    Dim r As Range, sh As Worksheet

    Set r = Range(Cells(1, 1))
    Set sh = Sheets(Cells(2, 1))
End Sub

I expected that in both cases, VBA would use the default property of Cells (the Value) property to Set each variable.  However I get a runtime error 13 on the last line of code!

In order to avoid errors, I must use:

Sub WhatIsGoingOn2()
    Dim r As Range, sh As Worksheet

    Set r = Range(Cells(1, 1))
    Set sh = Sheets(Cells(2, 1).Value)
End Sub

What is going on here ??

Body:
Perhaps Leviathan's comment that "Inconsistency is one of the strengths of VBA..." may ring true, but there are some contextual details that his answer neglects (and is technically incorrect on some subtle points).  He is correct that for the given code that all of the parameters are variants, but the statement that "no type coercion will be necessary" can be misleading and perhaps just wrong in many cases.  Even if many objects and methods are programmed to handle multiple types and default values, this very question reveals that it is a mistake to avoid purposely ensuring (or coercing) the correct data type.  Avoiding default properties altogether (by always typing out the full reference) can avoid many headaches.

A significant difference between the lines of code for this particular question is this:  Range is a property that takes parameters, while Sheets is also a property but has no parameters.  Range and Sheets are NOT objects in this context, even though they are properties which do return Range and Sheets objects, respectively.  They are properties of an (automatic global) object defined for the particular module or Excel workbook instance.  This detail is not trivial for understanding what the code is actually doing.

The Obect Browser in the VBA window reveals the following metadata for the two properties:

Property Range(Cell1, [Cell2]) As Range
Property Sheets As Sheets

For Range(Cells(1, 1)), the argument Cells(1,1) is passed to the parameter Cell1.  Cells itself is a property of the Excel.Global hidden object and it returns a Range object, so that Cells(rowindex, colindex) is calling a hidden default property of the Range class equivalent to Cells._Default(rowindex, colindex).  The return type of the property _Default() is not declared, so technically it could return any type in a variant, but inspection shows that it returns a Range object.  Apparently passing a Range object to its default property will attempt to take the default value and if it is a valid range value, like a string with a range expression, then it will execute without error.

The default property for the Sheets class is the parameterized hidden _Default(Index) method.  Thus, Sheets(Cells(2, 1)) is equivalent to Sheets._Default(Cells(2, 1)).  More importantly, it means that Sheets._Default(Cells(2, 1)) is passing a Range object as an index value, but documentation says that it expects an integer or string value.  We already mentioned that the index parameter is variant... and when passing an object to a variant, it always passes the actual object and never its default property.  So we know that Sheets.Item obtains a Range object in that call.  Here is were Levithan was correct in that Sheets.Item can decide what to do with it.  It is likely that it could have been smart enough to get the single string value and continue without error.  Other collection objects (with a default Item(index) property) in MS Office objects do not seem to exhibit this same "pickiness", so it appears that Sheets._Default() (and perhaps Sheets.Item()) is being rather strict on validating its arguments.  But this is just a particular design issue with this method only... not necessarily an overall issue with VBA.

What can be difficult is determining exactly what the source objects of the properties are.  Inside the ThisWorkbook module, Me.Sheets reveals that Sheets is a property of the particular Workbook for the module.  But Me.Range is not valid in the Workbook module, but right-clicking on the Range property (without the Me qualifier) and choosing "Definition" results in the message "Cannot jump to Range because it is hidden".  However, once in the Object Browser, righ-clicking within the browser one can choose "Show Hidden Members" which will then allow navigating to the hidden Global objects and other hidden members.

Why the inconsistency and the hidden properties? In an attempt to make the current instance of Excel and all of its components accessible in a "natural" way, Excel (and all Office applications) implement these various hidden properties to avoid the "complexity" of having to repeatedly discover and type out full references.  For instance, the automatic global Application object also has both Range and Sheets properties.  Actual documentation for Application.Sheets, for example, says "Using this property without an object qualifier is equivalent to using ActiveWorkbook.Sheets".  Even that documentation fails to say is that ActiveWorkbook is in turn a property of the global Excel Application object'.


问:
How to detect top legit search engine bots?
I want to develop a very robust method to detect only a few top search engines spiders such as googlebot and let them access content on my site, otherwise usual user registeration/login required to view that content.

Note that I also make use of cookies to let users access some content without being registered. So if cookies are disabled on client browser, no content except front page is offered. But I heard search engine spiders dont accept cookies so this will also shut out legitimate search engine bots. Is this correct?

One suggestion I heard is to do reverse lookup from ip address and if it resolves to for example googlebot.com, then do a forward dns lookup and if get back the original ip, then its legitimate and not some one impersonating as googlebot. I am using Java on linux server , so java based solution I am looking for.

I am only letting in top good search engine spiders such as google yahoo bing alexa etc and keep the others out to reduce server loads. But its very important top spiders index my site.

答:
I want to develop a very robust method to detect only a few top search engines spiders such as googlebot and let them access content on my site, otherwise usual user registeration/login required to view that content.

The normal approach to this is to configure a robots.txt file to allow the crawlers that you want, and disallow the rest.  Of course, this does depend on crawlers following the rules, but for those that don't you can fall back on things like user-agent strings, ip address checking, etc.

The nice things about "robots.txt" are:

It is simple to set up.

It has minimal impact on your site.  A well behaved crawler would fetch the file, and (assuming you disallowed the crawler) just go away.

You can specify what parts of your site can be crawled.

Note that I also make use of cookies to let users access some content without being registered. So if cookies are disabled on client browser, no content except front page is offered. But I heard search engine spiders dont accept cookies so this will also shut out legitimate search engine bots. Is this correct?

I believe so.  See Google's view on what you are doing.

One suggestion I heard is to do reverse lookup from ip address and if it resolves to for example googlebot.com, then do a forward dns lookup and if get back the original ip, then its legitimate and not some one impersonating as googlebot.

It probably will, but it is rather expensive.  Robots.txt is a simpler approach, and easy to implement in the first instance.

ContentLicense: CC BY-SA 2.5


问:
Any difference between explicit and implicit return in javascript function?
Is there any difference when I explicitly return from a function vs. implicitly return?

Here's the code that puzzles me ATM:

```<code>function ReturnConstructor(arg){
    // Private variable.
    var privateVar = "can't touch this, return ctor.";

    // This is what is being exposed to the outside as the return object
    return {
        print: function() {
            console.log("ReturnConstructor: arg was: %s", arg);
        }
    };
}

function NormalConstructor(arg){
    // Private variable.
    var privateVar = "can't touch this, normal ctor";

    // This is what is being exposed to the outside as "public"
    this.print = function() {
            console.log("NormalConstructor: arg was: %s", arg);
        };
}

var ret = new ReturnConstructor("calling return");
var nor = new NormalConstructor("calling normal");
</code>```

Both objects ('ret' & 'nor') seem the same to me, and I'm wondering if it's only personal preference of whomever wrote whichever article I've read so far, or if there's any hidden traps there.

答:
Implicit return only happens for single statement arrow functions, except When arrow function is declared with {}, even if it’s a single statement, implicit return does not happen:
link</p>

Body:
Is there any difference when I explicitly return from a function vs. implicitly return?

Here's the code that puzzles me ATM:

function ReturnConstructor(arg){
    // Private variable.
    var privateVar = "can't touch this, return ctor.";

    // This is what is being exposed to the outside as the return object
    return {
        print: function() {
            console.log("ReturnConstructor: arg was: %s", arg);
        }
    };
}

function NormalConstructor(arg){
    // Private variable.
    var privateVar = "can't touch this, normal ctor";

    // This is what is being exposed to the outside as "public"
    this.print = function() {
            console.log("NormalConstructor: arg was: %s", arg);
        };
}

var ret = new ReturnConstructor("calling return");
var nor = new NormalConstructor("calling normal");

Both objects ('ret' & 'nor') seem the same to me, and I'm wondering if it's only personal preference of whomever wrote whichever article I've read so far, or if there's any hidden traps there.


问:
Two-way binding Attribute is missing the Android namespace prefix <Data> <Variable>
Trying to implement two way binding
As mentioned:

Data Binding Library

Two-way Android Data Binding - How to use two-way Data Binding to manage a layout

2-way Data Binding on Android!

However on

```<code><variable type="com.example.gideonsassoon.avariel.datamodels.Player" name="name"/>
</code>```

I am getting the following message.:

"Attribute is missing the Android namespace prefix less... (Ctrl+F1)
  Most Android views have attributes in the Android namespace. When
  referencing these attributes you must include the namespace prefix, or
  your attribute will be interpreted by aapt as just a custom attribute.
  Similarly, in manifest files, nearly all attributes should be in the
  android: namespace."

If I try to build it puts all the R. in my file in red and state they don't exist etc.

I have edited my build gradle file to have

```<code>dataBinding.enabled = true
</code>```

Full code up to the point relevant below

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:windowSoftInputMode="adjustPan"
    tools:context="com.example.gideonsassoon.avariel.ui.MainFragmentActivity">
    <data>
        <variable type="com.example.gideonsassoon.avariel.datamodels.Player" name="name"/>
    </data>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <android.support.v4.view.PagerTabStrip
            android:id="@+id/viewpagerStrip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"/>
    </android.support.v4.view.ViewPager>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="34dp">

        <TextView
            android:id="@+id/tv_character_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="@string/name_colon"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"
            android:textIsSelectable="false" />

        <EditText
            android:id="@+id/et_character_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="@={player.name}"

            android:layout_alignBaseline="@+id/tv_character_name"
            android:layout_marginStart="15dp"
            android:layout_toEndOf="@+id/tv_character_name"

            android:ems="12"
            android:hint="@string/character_name"
            android:inputType="textPersonName" />
</code>```

答:
Ahh it appears to be that I have it as relativeLayout. It can't be "binding" so it can only be layout. Not sure how that's gonna affect my files as a whole but I guess we'll just have to see how it plays out. Here's my source. However if anyone wants to answer to that effect it would be most appreciated.

Using data binding in Android - Tutorial

Body:
Trying to implement two way binding
As mentioned:

Data Binding Library

Two-way Android Data Binding - How to use two-way Data Binding to manage a layout

2-way Data Binding on Android!

However on

<variable type="com.example.gideonsassoon.avariel.datamodels.Player" name="name"/>

I am getting the following message.:

"Attribute is missing the Android namespace prefix less... (Ctrl+F1)
  Most Android views have attributes in the Android namespace. When
  referencing these attributes you must include the namespace prefix, or
  your attribute will be interpreted by aapt as just a custom attribute.
  Similarly, in manifest files, nearly all attributes should be in the
  android: namespace."

If I try to build it puts all the R. in my file in red and state they don't exist etc.

I have edited my build gradle file to have

dataBinding.enabled = true

Full code up to the point relevant below

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:windowSoftInputMode="adjustPan"
    tools:context="com.example.gideonsassoon.avariel.ui.MainFragmentActivity">
    <data>
        <variable type="com.example.gideonsassoon.avariel.datamodels.Player" name="name"/>
    </data>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <android.support.v4.view.PagerTabStrip
            android:id="@+id/viewpagerStrip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"/>
    </android.support.v4.view.ViewPager>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="34dp">

        <TextView
            android:id="@+id/tv_character_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="@string/name_colon"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"
            android:textIsSelectable="false" />

        <EditText
            android:id="@+id/et_character_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="@={player.name}"

            android:layout_alignBaseline="@+id/tv_character_name"
            android:layout_marginStart="15dp"
            android:layout_toEndOf="@+id/tv_character_name"

            android:ems="12"
            android:hint="@string/character_name"
            android:inputType="textPersonName" />


问:
Boto3 error: The AWS Access Key Id you provided does not exist in our records
I am currently trying to get access to Amazon S3 inside a virtual machine and download files like so:

```<code>s3 = boto3.resource('s3',
         aws_access_key_id="xxxxxxxxxxx",
         aws_secret_access_key="xxxxxxxxxxxxxxxxx")
s3client = boto3.client('s3')

bucket = s3.Bucket('bucketone')

for obj in bucket.objects.all():
    s3client.download_file(bucket_name, obj.key, filename)
</code>```

But I’m getting the error:

botocore.exceptions.ClientError: An error occurred (InvalidAccessKeyId) when calling the ListObjects operation: The AWS Access Key Id you provided does not exist in our records.

What could I be doing wrong? I checked my aws_access_key_id and aws_secret_access_key multiple times, but still getting the same error. The same code locally, but not on a virtual machine, actually works on a different computer as well.  There is a reason why I’m hardcoding in the keys, as I have to.

答:
You need to set the access for the boto3 session. You don't really want to put your keys in your code. What I would recommend doing first is running 'aws configure' and setting your aws_access_key_id and aws_secret_access_key in your .credentials file.  Then in your code do the following:

```<code>session = boto3.Session(profile_name='name_of_your_profile')
</code>```

If you have just the default profile, you might not need to do that or for good measure, just put:

```<code>session = boto3.Session(profile_name='default')
</code>```

Once you have that in your code you can establish a connection to s3 with:

```<code>s3 = session.resource('s3')
bucket = s3.Bucket('bucketone')
for obj in bucket.objects.all():
   print(obj.key)
</code>```

There is some problem with your code as well.  You are creating an s3 client.  S3 client does not have a Bucket method or property.  To do the same thing with the s3 client you would do:

```<code>s3client = session.client('s3')
response = s3client.get_object(Bucket='bucketone', key='your key')
</code>```

You can then iterate through the response that is returned to see the list of objects in the bucket.

That should take care of your error.

Body:
I am currently trying to get access to Amazon S3 inside a virtual machine and download files like so:

s3 = boto3.resource('s3',
         aws_access_key_id="xxxxxxxxxxx",
         aws_secret_access_key="xxxxxxxxxxxxxxxxx")
s3client = boto3.client('s3')

bucket = s3.Bucket('bucketone')

for obj in bucket.objects.all():
    s3client.download_file(bucket_name, obj.key, filename)

But I’m getting the error:

botocore.exceptions.ClientError: An error occurred (InvalidAccessKeyId) when calling the ListObjects operation: The AWS Access Key Id you provided does not exist in our records.

What could I be doing wrong? I checked my aws_access_key_id and aws_secret_access_key multiple times, but still getting the same error. The same code locally, but not on a virtual machine, actually works on a different computer as well.  There is a reason why I’m hardcoding in the keys, as I have to.

Body:
You need to set the access for the boto3 session. You don't really want to put your keys in your code. What I would recommend doing first is running 'aws configure' and setting your aws_access_key_id and aws_secret_access_key in your .credentials file.  Then in your code do the following:

session = boto3.Session(profile_name='name_of_your_profile')

If you have just the default profile, you might not need to do that or for good measure, just put:

session = boto3.Session(profile_name='default')

Once you have that in your code you can establish a connection to s3 with:

s3 = session.resource('s3')
bucket = s3.Bucket('bucketone')
for obj in bucket.objects.all():
   print(obj.key)

There is some problem with your code as well.  You are creating an s3 client.  S3 client does not have a Bucket method or property.  To do the same thing with the s3 client you would do:

s3client = session.client('s3')
response = s3client.get_object(Bucket='bucketone', key='your key')

You can then iterate through the response that is returned to see the list of objects in the bucket.

That should take care of your error.


问:
why are new controls showing up in my form AND panel
i have a form with a few controls on it, i have a panel with different controls on, That panel is above the form controls.

i have added new controls to the form and when i place the panel back over the form, the new controls are showing through the panel itself, but only the new one controls and not the "old" ones, if i copy and paste a control or add a new one it has the same effect.

i have looked in the designer.cs and the new controls are being added to the form and NOT to the panel itself.

this is weird and iv checked various properties but cannot immediately see the reason for this.

i have made MANY forms before and this is the 1st time this is happening.

one the note of controls, is there a way to change the default value of the labels "AutoSize" property from TRUE to FALSE; i'm using visual studio CE2015

any ideas on what to check? im really stumped by this one.

答:
As mentioned in the comments, you need to check the z-order of your controls.

In the picture below you can see a form I created with two buttons and a panel as you were describing. Neither button is one the panel, however button 3 has a z-order that puts it on top, just as the panel is on top of button 2

If you right click on the controls you want to change the z-order of you see Bring to Front and Send to Back. Choose the appropriate option.


问:
Get the container file for an embedded resource in Qt C++
Here it is shown how to get list of files stored in a .qrc Qt Resorce file?.

This solution works as expected, however the list does not show the .qrc file from which the given entry originates, as in the case where the project contains several sub-projects in the form of libraries, each with its own .qrc file.

So, the question is: Is there a way to know to which .qrc file the given resource in the obtained list belongs?

I need this information to make the library aware of which resources are available from its local .qrc, not to get all the resources, which are available globaly for the application.

Platform info: Qt 5.6.1 with MSVC2013 installed on Windows 7

答:
No, you can't. When the qrc file compiled, the original file name won't be incorporated into compiled binary. If you want the library awares of its local resource, you should add prefix to each resource file with library identifier. For more explanation see Qt Resource System. For example

```<code><!-- resource for mylib01 -->
<!DOCTYPE RCC><RCC version="1.0">
<qresource prefix="mylib01">
    <file>images/copy.png</file>
    <file>images/cut.png</file>
</qresource>
</RCC>

<!-- resource for mylib02 -->
<!DOCTYPE RCC><RCC version="1.0">
<qresource prefix="mylib02">
    <file>images/copy.png</file>
    <file>images/cut.png</file>
    <file>images/new.png</file>
</qresource>
</RCC>
</code>```

Each resource file then will be available as :/mylib01/copy.png, :/mylib02/copy.png, ... When listing files in the resource for a specific library, simply compare the library identifier with resource file name to check whether it is belong to the library or not.

Another option is using separate binary resource, then load it dynamically with QResource. You can access the compiled resource file name by QResource::fileName().

Body:
No, you can't. When the qrc file compiled, the original file name won't be incorporated into compiled binary. If you want the library awares of its local resource, you should add prefix to each resource file with library identifier. For more explanation see Qt Resource System. For example

<!-- resource for mylib01 -->
<!DOCTYPE RCC><RCC version="1.0">
<qresource prefix="mylib01">
    <file>images/copy.png</file>
    <file>images/cut.png</file>
</qresource>
</RCC>

<!-- resource for mylib02 -->
<!DOCTYPE RCC><RCC version="1.0">
<qresource prefix="mylib02">
    <file>images/copy.png</file>
    <file>images/cut.png</file>
    <file>images/new.png</file>
</qresource>
</RCC>

Each resource file then will be available as :/mylib01/copy.png, :/mylib02/copy.png, ... When listing files in the resource for a specific library, simply compare the library identifier with resource file name to check whether it is belong to the library or not.

Another option is using separate binary resource, then load it dynamically with QResource. You can access the compiled resource file name by QResource::fileName().


Title: Converting a text file into a dictionary

Body:
I have the following text file for demand in a network.

Origin  1
    1 :      0.0;     2 :    100.0;     3 :    100.0;     4 :    500.0;     5 :    200.0;
    6 :    300.0;     7 :    500.0;     8 :    800.0;     9 :    500.0;    10 :   1300.0;
   11 :    500.0;    12 :    200.0;    13 :    500.0;    14 :    300.0;    15 :    500.0;
   16 :    500.0;    17 :    400.0;    18 :    100.0;    19 :    300.0;    20 :    300.0;
   21 :    100.0;    22 :    400.0;    23 :    300.0;    24 :    100.0;

Origin  2
    1 :    100.0;     2 :      0.0;     3 :    100.0;     4 :    200.0;     5 :    100.0;
    6 :    400.0;     7 :    200.0;     8 :    400.0;     9 :    200.0;    10 :    600.0;
   11 :    200.0;    12 :    100.0;    13 :    300.0;    14 :    100.0;    15 :    100.0;
   16 :    400.0;    17 :    200.0;    18 :      0.0;    19 :    100.0;    20 :    100.0;
   21 :      0.0;    22 :    100.0;    23 :      0.0;    24 :      0.0;

Origin  3
    1 :    100.0;     2 :    100.0;     3 :      0.0;     4 :    200.0;     5 :    100.0;
    6 :    300.0;     7 :    100.0;     8 :    200.0;     9 :    100.0;    10 :    300.0;
   11 :    300.0;    12 :    200.0;    13 :    100.0;    14 :    100.0;    15 :    100.0;
   16 :    200.0;    17 :    100.0;    18 :      0.0;    19 :      0.0;    20 :      0.0;
   21 :      0.0;    22 :    100.0;    23 :    100.0;    24 :      0.0;

... records 4-23 elided ...

Origin  24
    1 :    100.0;     2 :      0.0;     3 :      0.0;     4 :    200.0;     5 :      0.0;
    6 :    100.0;     7 :    100.0;     8 :    200.0;     9 :    200.0;    10 :    800.0;
   11 :    600.0;    12 :    500.0;    13 :    700.0;    14 :    400.0;    15 :    400.0;
   16 :    300.0;    17 :    300.0;    18 :      0.0;    19 :    100.0;    20 :    400.0;
   21 :    500.0;    22 :   1100.0;    23 :    700.0;    24 :      0.0;

Now I need to create a dictionary, which should look something like:

{(1,1):0.0, (1,2):100.0, (1, 3):100.0, .......
 (2, 1):100.0, (2,2):0, ......}

Where the tuple elements e.g. (1, 2) represent the origin and destination, and the value represents the demand (which is 100.0 for the (1, 2) key).

I tried the following:

with open("trips.txt", "r") as f:
     line = f.readline()
     line = f.readline()
     ind = 0
     while len(line):
         line = line.strip(';')
         l = line.split()
         print l

         ind = ind + 1
         if(ind == 5):
             line = f.readline()
             line = f.readline()
             line = f.readline()
             ind = 0
             node = node + 1
         else:
             line = f.readline()

But I don't think I am going anywhere with this...

Body:
One more way to do this -

nw.usage is a file that has the usage content..

As I commented in the code below.. use collections.OrderedDict() if you want to maintain insertion order.

Hope it helps!

#!/usr/bin/env python

import re
#import collections

with open('nw.usage', 'r') as f:
  usage_dict = {}
  #Use collections.OrderedDict() if you want to maintain insertion order
  origin_val = ''
  for line in f:
    if re.search('Origin', line):
      origin_val = line.rstrip()[-1]
    else:
      hr_demand = line.strip().split(';')
      for hr in hr_demand:
        if not hr:
          continue
        hour = hr.split(':')[0].strip()
        usage = hr.split(':')[1].strip()
        usage_dict[(origin_val, hour)] = usage

  print usage_dict

Output is -

{('1', '17'): '400.0', ('2', '2'): '0.0', ('2', '17'): '200.0', ('1', '20'): '300.0', ('1', '18'): '100.0', ('2', '20'): '100.0', ('1', '13'): '500.0', ('1', '6'): '300.0', ('2', '13'): '300.0', ('1', '24'): '100.0', ('2', '7'): '200.0', ('2', '24'): '0.0', ('1', '2'): '100.0', ('1', '16'): '500.0', ('2', '3'): '100.0', ('2', '18'): '0.0', ('1', '21'): '100.0', ('2', '23'): '0.0', ('1', '12'): '200.0', ('2', '14'): '100.0', ('2', '8'): '400.0', ('1', '5'): '200.0', ('2', '10'): '600.0', ('2', '4'): '200.0', ('2', '19'): '100.0', ('1', '22'): '400.0', ('1', '1'): '0.0', ('2', '22'): '100.0', ('1', '15'): '500.0', ('2', '15'): '100.0', ('2', '9'): '200.0', ('1', '11'): '500.0', ('1', '4'): '500.0', ('2', '11'): '200.0', ('1', '9'): '500.0', ('2', '5'): '100.0', ('1', '23'): '300.0', ('1', '14'): '300.0', ('2', '1'): '100.0', ('2', '16'): '400.0', ('1', '19'): '300.0', ('2', '21'): '0.0', ('1', '10'): '1300.0', ('1', '7'): '500.0', ('2', '12'): '100.0', ('1', '8'): '800.0', ('2', '6'): '400.0', ('1', '3'): '100.0'}


Title: R: evaluating multiple conditionals multiple times

Body:
How about this ball of duct tape...

cond1 <- df[,seq(1,6,by=2)]==88.76
cond2 <- df[,seq(2,6,by=2)]<=0.1
vec <- which(rowSums(cond1 & cond2, na.rm=T)==1)

df[vec,]
##    event1 time1 event2 time2 event100 time100
## 1   88.76 0.100     NA    NA       NA      NA
## 6   34.04 0.000  88.76 0.083    34.02   0.117
## 10  87.44 0.117  88.76 0.050    87.41   0.300


问:
Closing android application from fragment
I have only one activity in my application with multiple fragments. Whenever a user opens the app, it starts with startupFragment. Whenever user navigate through the fragments and presses  back, it takes him back to startupFragment. But when in the startupFragment, I want user, when clicked back, to be able to close the application. Now, here is the code, when the application is started for creating the fragment.:

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

    //Set starting fragment
    StartupFragment startupFragment = new StartupFragment();
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().add(R.id.content_main, startupFragment, "startupFragmentTag").commit();

}
</code>```

As you can see, I have added the tag "startupFragmentTag" to be able to identify it. This is my code onBackPressed:

```<code>@Override
public void onBackPressed()
{

    Fragment startup = getFragmentManager().findFragmentByTag("startupFragmentTag");

    if(startup == null) {

        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        StartupFragment startupFragment = new StartupFragment();
        manager.beginTransaction().replace(R.id.content_main, startupFragment, "startupFragmentTag").commit();

    } else {

        finish();

    }
}
</code>```

So basically what I tried here, is when user is in another fragment, when the user presses back, it will take him/her back to startupFragment. But when in that fragment, when pressing back again, I want the user to be able to exit the application, which won't happen given the code now.

I find the startupFragment by its tag and check if it exists. If not, it will take back the user to it. But if it exists, user should be able to quit, that why finish() is called.

Does the previous fragments not get destroyed? But that shouldn't be the case, because even if I open the app and instantly press back, it won't exit the app.

What am I doing here wrong?

答:
Probably because you've used beginTransaction().add() to add the Fragments including startupFragment and other Fragments on top of it. Then you will always be able to find it using getFragmentManager().findFragmentByTag(), because all Fragments added will be in the Fragment stack (while the find method is actually to find the Fragment with the tag in the stack).

Tips based on what you want to impl:

beginTransaction().replace() will replace instead of adding a Fragment, this way you will only be able to "find" one existing Fragment if you always replace it. i.e. always one Fragment in the stack.

You may want to use getFragmentManager().findFragmentById() to get current showing Fragment (on top of the Fragment stack), instead of findFragmentByTag, if there're several Fragments in the stack which are added not replaced as mentioned above.

When using beginTransaction().add(), you may want to use fragmentManager.addOnBackStackChangedListener() to monitor the Fragment stack changes. Then you probably don't have to handle onBackPressed(). Then in the in the listener you only need to retrieve current Fragment on top stack and see what it is and add your logic there.

Body:
I have only one activity in my application with multiple fragments. Whenever a user opens the app, it starts with startupFragment. Whenever user navigate through the fragments and presses  back, it takes him back to startupFragment. But when in the startupFragment, I want user, when clicked back, to be able to close the application. Now, here is the code, when the application is started for creating the fragment.:

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

    //Set starting fragment
    StartupFragment startupFragment = new StartupFragment();
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().add(R.id.content_main, startupFragment, "startupFragmentTag").commit();

}

As you can see, I have added the tag "startupFragmentTag" to be able to identify it. This is my code onBackPressed:

@Override
public void onBackPressed()
{

    Fragment startup = getFragmentManager().findFragmentByTag("startupFragmentTag");

    if(startup == null) {

        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        StartupFragment startupFragment = new StartupFragment();
        manager.beginTransaction().replace(R.id.content_main, startupFragment, "startupFragmentTag").commit();

    } else {

        finish();

    }
}

So basically what I tried here, is when user is in another fragment, when the user presses back, it will take him/her back to startupFragment. But when in that fragment, when pressing back again, I want the user to be able to exit the application, which won't happen given the code now.

I find the startupFragment by its tag and check if it exists. If not, it will take back the user to it. But if it exists, user should be able to quit, that why finish() is called.

Does the previous fragments not get destroyed? But that shouldn't be the case, because even if I open the app and instantly press back, it won't exit the app.

What am I doing here wrong?


问:
Is it actually possible to store and process individual UTF-8 characters on C ? If so, how?
I've written a program in C that breaks words down into syllables, segments and letters. It's working well with ASCII characters but I want to make versions that work for the IPA and Arabic too.

I'm having massive problems saving and performing functions on individual characters. My editor and console are both set up to UTF-8 and can display Arabic text fine if I save it as a char*, but when I try to print wchars they display random punctuation marks.

My program needs to be able to recognise an individual UTF-8 character in order to work. For example, for the word 'though' it stores 't' as syllable[1]segment[1]letter[1], h as syllable[1]segment[1]letter[2] etc. I want to be able to do the same for non-ASCII characters.

I've spent basically the whole day researching unicode and trying out different methods and I can't get any of them to let me store an Arabic character as a character.

I'm not sure if I've just made some stupid syntax errors along the way, if I've completely misunderstood the whole concept, or if it actually just isn't possible to do what I want in C and I should just give up and try another language...

I would massively, massively, massively appreciate any help you can offer! I'm pretty new to programming, but unicode is completely instrumental to my work so I want to work out how to do it from the beginning.

My understanding of how unicode works (in case that's where I'm going wrong):

I type some text into my editor. My editor encodes it according to the encoding I have set. So if I set it to UFT-8 it will encode the Arabic letter ب with the 2 byte sequence 0xd8 0xab which indicates the code point U+0628.

I compile it, breaking down 0xd8 0xab into the binary 11011000 10101000.

I run it on the command prompt. The command prompt interprets the text according to the encoding I have set, so if I set it to UFT-8 it should interpret 11011000 10101000 as the code point U+0628. Unicode algorithms also tell it which version of U+0628 to display to me, as the character has different shapes depending on where it is in the word. As the character is alone it will show me the standalone version ب

My understanding of the ways I can process unicode in C:

Option A - Use single bytes encoded as UTF-8 (http://www.nubaria.com/en/blog/?p=289)

Use single bytes encoded as UTF-8. Leave all my datatypes as chars and char arrays and only type ASCII characters in my code. If I absolutely have to hard code a unicode character enter it as an array in the format:

```<code>    const char kChineseSampleText[] = "\xe4\xb8\xad\xe6\x96\x87";
</code>```

My problems with this:

I need to manipulate individual characters

Having to type Arabic characters as code points is going to render my code completely unreadable and slow me down immensely.

Option B - Use wchar and friends (http://icu-project.org/docs/papers/unicode_wchar_t.html)

Swap using chars for wchars, which hold 2 to 4 bytes depending on the compiler. String functions like strlen will not work as they are expecting characters to be one byte, but there are w functions like  wprintf I can use instead.

My problem with this:

I can’t get wchars to print Arabic characters at all! I can get them to print English letters fine, but Arabic characters just pull through as random punctuation marks.

I've tried inputing the unicode code point as well as the actual Arabic character and I've tried printing them both to the console and to a UTF-8 encoded text file and I get the same result, even though both the console and the text file display Arabic text if entered as a char*. I've included my code at the end.

(It’s worth saying here that I am aware that a lot of people think wchars are bad because they aren’t very portable and because they take up extra space for ASCII characters. But at this stage, neither of those things are really a worry for me - I’m just writing the program to run on my own computer and the program will only be processing short strings.)

Option C - Use external libraries

I've read in various comments that external libraries are the way to go so I've tried:

C programming library

http://www.cprogramming.com/tutorial/unicode.html suggests replacing all chars with unsigned long integers and using special functions for iterating through strings etc. The site even provides a sample library to download.

My problem:

While I can set the character to be an unsigned long integer I can’t print it out, because the printf and wprintf functions don’t work, and neither does the library provided on the website (I think maybe the library was designed for Linux? Some of the datatypes are invalid and amending them didn't work either)

ICU library

My problem:

I downloaded the ICU library, but when I was looking into how to use it I saw that functionality such as the characterIterator is not available for use in C (http://userguide.icu-project.org/strings). Being able to iterate through characters is completely fundamental to what I need to do, so I don't think the library will work for me.

My code

```<code>#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>
#include <string.h>

int main ()
{
wchar_t unicode = L'\xd8ac';
wchar_t arabic = L'ب';
wchar_t number = 0x062c;

FILE* f;
f = fopen("unitest.txt","w");
char* string = "ايه الاخبار";

//printf - works

printf("printf - literal arabic character is \"م\"\n");
fprintf(f,"printf - literal arabic character is \"م\"\n");

printf("printf - char* string is \"%s\"\n",string);
fprintf(f,"printf - char* string is \"%s\"\n",string);

//wprintf  - english - works

wprintf(L"wprintf - literal english char is \"%C\"\n\n", L't');
fwprintf(f,L"wprintf - literal english char is \"%C\"\n\n", L't');

//wprintf - arabic - doesnt work

wprintf(L"wprintf - unicode wchar_t is \"%C\"\n", unicode);
fwprintf(f,L"wprintf - unicode wchar_t is \"%C\"\n", unicode);

wprintf(L"wprintf - unicode number wchar_t is \"%C\"\n", number);
fwprintf(f,L"wprintf - unicode number wchar_t is \"%C\"\n", number);

wprintf(L"wprintf - arabic wchar_t is \"%C\"\n", arabic);
fwprintf(f,L"wprintf - arabic wchar_t is \"%C\"\n", arabic);

wprintf(L"wprintf - literal arabic character is \"%C\"\n",L'ت');
fwprintf(f,L"wprintf - literal arabic character is \"%C\"\n",L'ت');

wprintf(L"wprintf - literal arabic character in string is \"م\"\n\n");
fwprintf(f,L"wprintf - literal arabic character in string is \"م\"\n\n");

fclose(f);

return 0;
}
</code>```

Output file

```<code>printf - literal arabic character is "م"
printf - char* string is "ايه الاخبار"
wprintf - literal english char is "t"

wprintf - unicode wchar_t is "�"
wprintf - unicode number wchar_t is ","
wprintf - arabic wchar_t is "("
wprintf - literal arabic character is "*"
wprintf - literal arabic character in string is ""
</code>```

I'm using Windows 10, Notepad++ and  MinGW.

Edit
This got marked as a duplicate of Light C Unicode Library but I don't think it really answers my question. I've downloaded the library and had a look at and you can call me stupid if you like, but I'm really new to programming and I don't understand most of the code in the library, so it's hard for me to work out how I can use it achieve what I want. I searched the library for a print function and couldn't find one...

I just want to save a UTF-8 character and then print it out again! Do I really need to install an entire library to do that? I would just really appreciate someone taking pity on me and telling me in baby terms how I can do it... People keep saying I should use uint_32 or something instead of wchar - but how do I then print those datatypes? Can I do it with wprintf?!

答:
An example with utf8proc library to iterate is:

```<code>#include <utf8proc.h>
#include <stdio.h>

int main(void) {
  utf8proc_uint8_t const string[] = u8"ايه الاخبار";
  utf8proc_ssize_t size = sizeof string / sizeof *string - 1;
  utf8proc_int32_t data;
  utf8proc_ssize_t n;

  utf8proc_uint8_t const *pstring = string;
  while ((n = utf8proc_iterate(pstring, size, &data)) > 0) {
    printf("<%.*s>\n", (int)n, pstring);
    pstring += n;
    size -= n;
  }
}
</code>```

This is probably not the best way to use this library but I make an issue an github to have some example. Because, I'm unable to understand how work this library.

Body:
I've written a program in C that breaks words down into syllables, segments and letters. It's working well with ASCII characters but I want to make versions that work for the IPA and Arabic too.

I'm having massive problems saving and performing functions on individual characters. My editor and console are both set up to UTF-8 and can display Arabic text fine if I save it as a char*, but when I try to print wchars they display random punctuation marks.

My program needs to be able to recognise an individual UTF-8 character in order to work. For example, for the word 'though' it stores 't' as syllable[1]segment[1]letter[1], h as syllable[1]segment[1]letter[2] etc. I want to be able to do the same for non-ASCII characters.

I've spent basically the whole day researching unicode and trying out different methods and I can't get any of them to let me store an Arabic character as a character.

I'm not sure if I've just made some stupid syntax errors along the way, if I've completely misunderstood the whole concept, or if it actually just isn't possible to do what I want in C and I should just give up and try another language...

I would massively, massively, massively appreciate any help you can offer! I'm pretty new to programming, but unicode is completely instrumental to my work so I want to work out how to do it from the beginning.

My understanding of how unicode works (in case that's where I'm going wrong):

I type some text into my editor. My editor encodes it according to the encoding I have set. So if I set it to UFT-8 it will encode the Arabic letter ب with the 2 byte sequence 0xd8 0xab which indicates the code point U+0628.

I compile it, breaking down 0xd8 0xab into the binary 11011000 10101000.

I run it on the command prompt. The command prompt interprets the text according to the encoding I have set, so if I set it to UFT-8 it should interpret 11011000 10101000 as the code point U+0628. Unicode algorithms also tell it which version of U+0628 to display to me, as the character has different shapes depending on where it is in the word. As the character is alone it will show me the standalone version ب

My understanding of the ways I can process unicode in C:

Option A - Use single bytes encoded as UTF-8 (http://www.nubaria.com/en/blog/?p=289)

Use single bytes encoded as UTF-8. Leave all my datatypes as chars and char arrays and only type ASCII characters in my code. If I absolutely have to hard code a unicode character enter it as an array in the format:

    const char kChineseSampleText[] = "\xe4\xb8\xad\xe6\x96\x87";

My problems with this:

I need to manipulate individual characters

Having to type Arabic characters as code points is going to render my code completely unreadable and slow me down immensely.

Option B - Use wchar and friends (http://icu-project.org/docs/papers/unicode_wchar_t.html)

Swap using chars for wchars, which hold 2 to 4 bytes depending on the compiler. String functions like strlen will not work as they are expecting characters to be one byte, but there are w functions like  wprintf I can use instead.

My problem with this:

I can’t get wchars to print Arabic characters at all! I can get them to print English letters fine, but Arabic characters just pull through as random punctuation marks.

I've tried inputing the unicode code point as well as the actual Arabic character and I've tried printing them both to the console and to a UTF-8 encoded text file and I get the same result, even though both the console and the text file display Arabic text if entered as a char*. I've included my code at the end.

(It’s worth saying here that I am aware that a lot of people think wchars are bad because they aren’t very portable and because they take up extra space for ASCII characters. But at this stage, neither of those things are really a worry for me - I’m just writing the program to run on my own computer and the program will only be processing short strings.)

Option C - Use external libraries

I've read in various comments that external libraries are the way to go so I've tried:

C programming library

http://www.cprogramming.com/tutorial/unicode.html suggests replacing all chars with unsigned long integers and using special functions for iterating through strings etc. The site even provides a sample library to download.

My problem:

While I can set the character to be an unsigned long integer I can’t print it out, because the printf and wprintf functions don’t work, and neither does the library provided on the website (I think maybe the library was designed for Linux? Some of the datatypes are invalid and amending them didn't work either)

ICU library

My problem:

I downloaded the ICU library, but when I was looking into how to use it I saw that functionality such as the characterIterator is not available for use in C (http://userguide.icu-project.org/strings). Being able to iterate through characters is completely fundamental to what I need to do, so I don't think the library will work for me.

My code

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>
#include <string.h>

int main ()
{
wchar_t unicode = L'\xd8ac';
wchar_t arabic = L'ب';
wchar_t number = 0x062c;

FILE* f;
f = fopen("unitest.txt","w");
char* string = "ايه الاخبار";

//printf - works

printf("printf - literal arabic character is \"م\"\n");
fprintf(f,"printf - literal arabic character is \"م\"\n");

printf("printf - char* string is \"%s\"\n",string);
fprintf(f,"printf - char* string is \"%s\"\n",string);

//wprintf  - english - works

wprintf(L"wprintf - literal english char is \"%C\"\n\n", L't');
fwprintf(f,L"wprintf - literal english char is \"%C\"\n\n", L't');

//wprintf - arabic - doesnt work

wprintf(L"wprintf - unicode wchar_t is \"%C\"\n", unicode);
fwprintf(f,L"wprintf - unicode wchar_t is \"%C\"\n", unicode);

wprintf(L"wprintf - unicode number wchar_t is \"%C\"\n", number);
fwprintf(f,L"wprintf - unicode number wchar_t is \"%C\"\n", number);

wprintf(L"wprintf - arabic wchar_t is \"%C\"\n", arabic);
fwprintf(f,L"wprintf - arabic wchar_t is \"%C\"\n", arabic);

wprintf(L"wprintf - literal arabic character is \"%C\"\n",L'ت');
fwprintf(f,L"wprintf - literal arabic character is \"%C\"\n",L'ت');

wprintf(L"wprintf - literal arabic character in string is \"م\"\n\n");
fwprintf(f,L"wprintf - literal arabic character in string is \"م\"\n\n");

fclose(f);

return 0;
}

Output file

printf - literal arabic character is "م"
printf - char* string is "ايه الاخبار"
wprintf - literal english char is "t"

wprintf - unicode wchar_t is "�"
wprintf - unicode number wchar_t is ","
wprintf - arabic wchar_t is "("
wprintf - literal arabic character is "*"
wprintf - literal arabic character in string is ""

I'm using Windows 10, Notepad++ and  MinGW.

Edit
This got marked as a duplicate of Light C Unicode Library but I don't think it really answers my question. I've downloaded the library and had a look at and you can call me stupid if you like, but I'm really new to programming and I don't understand most of the code in the library, so it's hard for me to work out how I can use it achieve what I want. I searched the library for a print function and couldn't find one...

I just want to save a UTF-8 character and then print it out again! Do I really need to install an entire library to do that? I would just really appreciate someone taking pity on me and telling me in baby terms how I can do it... People keep saying I should use uint_32 or something instead of wchar - but how do I then print those datatypes? Can I do it with wprintf?!

Body:
An example with utf8proc library to iterate is:

#include <utf8proc.h>
#include <stdio.h>

int main(void) {
  utf8proc_uint8_t const string[] = u8"ايه الاخبار";
  utf8proc_ssize_t size = sizeof string / sizeof *string - 1;
  utf8proc_int32_t data;
  utf8proc_ssize_t n;

  utf8proc_uint8_t const *pstring = string;
  while ((n = utf8proc_iterate(pstring, size, &data)) > 0) {
    printf("<%.*s>\n", (int)n, pstring);
    pstring += n;
    size -= n;
  }
}

This is probably not the best way to use this library but I make an issue an github to have some example. Because, I'm unable to understand how work this library.


问:
Error to use deflater on several inputs
 I am trying to use the Deflater class to encode a textfile. The difficulty is I do not want to encode the whole textfile, but just a substring on each line. My textfile looks like this :

 ELEMENT (1): {dataToEncode}

ELEMENT (2): {dataToEncode}

I want to return a HashMap which key is the element ID (Integer) and which value is the compressed bytes corresponding to the part of the line into brackets. I would like to use the same dictionary (not preset) for all the lines since their contents are really close. Furthermore, eventually, the algorithm will have to work on the stream i.e. new lines will be written in the input textfile and should be compressed right after they are added.

I have a version that works if I reset the deflater but I think it resets also the dictionary after every line encoded, which is not as effective as keeping the same dictionary all along since annotations on the elements are quite alike.

```<code>    public static HashMap< Integer, byte[]> encoding(String textfile) throws FileNotFoundException, UnsupportedEncodingException {
    HashMap< Integer, byte[]> elements = new HashMap< Integer, byte[]>();
    Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION);
    File file = new File(textfile + ".txt");
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String toCompress = sc.nextLine();

        if (toCompress.substring(0, 7).equals("ELEMENT")) {
            String infoToCompress = toCompress.substring(toCompress.indexOf('{') + 1, toCompress.indexOf('}'));
            byte [] input = infoToCompress.getBytes("UTF-8");
            byte [] output = new byte[input.length + 100];
            compresser.setInput(input);
            compresser.finish();
            int compressedDataLength = compresser.deflate(output);
            Integer element = Integer.parseInt(toCompress.substring(toCompress.indexOf('(')+1, toCompress.indexOf(")")));
            elements.put(element, output);;
            compresser.reset();
        }
    }
    compresser.end();
    sc.close();
    return elements;
}
</code>```

 If I do not use compresser.reset(), only the first element is compressed and then it compiles but does not have the expected result. Thanks for your help.

答:
```<code>compresser.finish();
</code>```

It's because you're calling finish(). Remove.

Title: Error to use deflater on several inputs

Body:
 I am trying to use the Deflater class to encode a textfile. The difficulty is I do not want to encode the whole textfile, but just a substring on each line. My textfile looks like this :

 ELEMENT (1): {dataToEncode}

ELEMENT (2): {dataToEncode}

I want to return a HashMap which key is the element ID (Integer) and which value is the compressed bytes corresponding to the part of the line into brackets. I would like to use the same dictionary (not preset) for all the lines since their contents are really close. Furthermore, eventually, the algorithm will have to work on the stream i.e. new lines will be written in the input textfile and should be compressed right after they are added.

I have a version that works if I reset the deflater but I think it resets also the dictionary after every line encoded, which is not as effective as keeping the same dictionary all along since annotations on the elements are quite alike.

    public static HashMap< Integer, byte[]> encoding(String textfile) throws FileNotFoundException, UnsupportedEncodingException {
    HashMap< Integer, byte[]> elements = new HashMap< Integer, byte[]>();
    Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION);
    File file = new File(textfile + ".txt");
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String toCompress = sc.nextLine();

        if (toCompress.substring(0, 7).equals("ELEMENT")) {
            String infoToCompress = toCompress.substring(toCompress.indexOf('{') + 1, toCompress.indexOf('}'));
            byte [] input = infoToCompress.getBytes("UTF-8");
            byte [] output = new byte[input.length + 100];
            compresser.setInput(input);
            compresser.finish();
            int compressedDataLength = compresser.deflate(output);
            Integer element = Integer.parseInt(toCompress.substring(toCompress.indexOf('(')+1, toCompress.indexOf(")")));
            elements.put(element, output);;
            compresser.reset();
        }
    }
    compresser.end();
    sc.close();
    return elements;
}

 If I do not use compresser.reset(), only the first element is compressed and then it compiles but does not have the expected result. Thanks for your help.

Body:
compresser.finish();

It's because you're calling finish(). Remove.


问:
Display Browser specific date/time using extjs
I have a database field called CreatedDate which is a timestamp field and holds the date and time. It currently holds the GMT time.

At the moment this field is displayed as it is on the web pages.

We want to amend this to show date/time as per browser local time zone

Can you please let us know how we can do this.

Thanks in advance

答:
If you can represent the universal time as a count of milliseconds since the 1 Jan 1970 epoch at the server then you can have the page code construct Date instances at the client using the client time zone, but starting from that UTC reference.  It's the normal behavior of the Javascript Date() constructor:

```<code>var clientDate = new Date(serverUTC);
</code>```

Now exactly how you get that UTC value depends on your server language. In a JSP page it'd be pretty simple:

```<code>var clientDate = new Date(<%= whatever.getTheDate().getTime() %>);
</code>```

or

```<code>var clientDate = new Date(${something.theDate.time});
</code>```

Once you've got the date value as a client-side Javascript Date instance, you can just update the field(s) with the string. There are no built-in Date formatting tools, but the old standard date.js might help with its ".toString()" formatter.

Body:
If you can represent the universal time as a count of milliseconds since the 1 Jan 1970 epoch at the server then you can have the page code construct Date instances at the client using the client time zone, but starting from that UTC reference.  It's the normal behavior of the Javascript Date() constructor:

var clientDate = new Date(serverUTC);

Now exactly how you get that UTC value depends on your server language. In a JSP page it'd be pretty simple:

var clientDate = new Date(<%= whatever.getTheDate().getTime() %>);

or

var clientDate = new Date(${something.theDate.time});

Once you've got the date value as a client-side Javascript Date instance, you can just update the field(s) with the string. There are no built-in Date formatting tools, but the old standard date.js might help with its ".toString()" formatter.


问:
c# linq listView - selecteditem to object
I need to send some variables for a listView.SelectedindexChanged event to an external object like I can do with a listBox. The following is my listView code. After this I will upload external object code and working listBox code.</p>

```<code>private void listViewProducts_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        ProductList_Variables selected = (ProductList_Variables)listViewProducts.SelectedItems[0];

        textBoxProduct.Text = selected.Product;
        comboBoxCategory.SelectedItem = selected.Category;
        textBoxSize.Text = selected.Size.ToString();
        comboBoxMarket.SelectedItem = selected.Market;
        comboBoxContainer.SelectedItem = comboBoxContainer.Items.OfType<ProductList_Variables>().SingleOrDefault(x => x.Container == selected.Container);
        textBoxPrice1.Text = selected.Price.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

class ProductList_Variables
{
    public int Id { get; set; }
    public string Product { get; set; }
    public string Category { get; set; }
    public string Size { get; set; }
    public string Market { get; set; }
    public string ProductName { get { return Product + " - " + Category + " - Size: " + Size +", Market: "+ Market; } }
    public string Flavour { get; set; }
    public decimal Price { get; set; }
    public string Container { get; set; }
    public int IdContainer { get; set; }
}

    private void listBoxProducts_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            ProductList_Variables selected = (ProductList_Variables)listBoxProducts.SelectedItem;

            //textBoxProduct.Text = selected.Product;
            //comboBoxCategory.SelectedItem = selected.Category;
            //comboBoxMarket.SelectedItem = selected.Market;
            //comboBoxContainer.SelectedValue = selected.IdContainer;
            //textBoxPrice1.Text = selected.Price.ToString();

            textBoxProduct.Text = selected.Product;
            comboBoxCategory.SelectedItem = selected.Category;
            textBoxSize.Text = selected.Size.ToString();
            comboBoxMarket.SelectedItem = selected.Market;
            comboBoxContainer.SelectedItem = comboBoxContainer.Items.OfType<ProductList_Variables>().SingleOrDefault(x => x.Container == selected.Container);
            textBoxPrice1.Text = selected.Price.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
</code>```

答:
If you want to send additional variables for an SelectedIndexChanged event, you may have to consider writing your own event with those requirements.

You can find a good explanation by this user.

Body:
I need to send some variables for a listView.SelectedindexChanged event to an external object like I can do with a listBox. The following is my listView code. After this I will upload external object code and working listBox code.

private void listViewProducts_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        ProductList_Variables selected = (ProductList_Variables)listViewProducts.SelectedItems[0];

        textBoxProduct.Text = selected.Product;
        comboBoxCategory.SelectedItem = selected.Category;
        textBoxSize.Text = selected.Size.ToString();
        comboBoxMarket.SelectedItem = selected.Market;
        comboBoxContainer.SelectedItem = comboBoxContainer.Items.OfType<ProductList_Variables>().SingleOrDefault(x => x.Container == selected.Container);
        textBoxPrice1.Text = selected.Price.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

class ProductList_Variables
{
    public int Id { get; set; }
    public string Product { get; set; }
    public string Category { get; set; }
    public string Size { get; set; }
    public string Market { get; set; }
    public string ProductName { get { return Product + " - " + Category + " - Size: " + Size +", Market: "+ Market; } }
    public string Flavour { get; set; }
    public decimal Price { get; set; }
    public string Container { get; set; }
    public int IdContainer { get; set; }
}

    private void listBoxProducts_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            ProductList_Variables selected = (ProductList_Variables)listBoxProducts.SelectedItem;

            //textBoxProduct.Text = selected.Product;
            //comboBoxCategory.SelectedItem = selected.Category;
            //comboBoxMarket.SelectedItem = selected.Market;
            //comboBoxContainer.SelectedValue = selected.IdContainer;
            //textBoxPrice1.Text = selected.Price.ToString();

            textBoxProduct.Text = selected.Product;
            comboBoxCategory.SelectedItem = selected.Category;
            textBoxSize.Text = selected.Size.ToString();
            comboBoxMarket.SelectedItem = selected.Market;
            comboBoxContainer.SelectedItem = comboBoxContainer.Items.OfType<ProductList_Variables>().SingleOrDefault(x => x.Container == selected.Container);
            textBoxPrice1.Text = selected.Price.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


问:
How do I make my player with a Rigidbody move with isKinematic checked?
My game is a topdown zombie shooter and whenever the zombies get to the player they bunch up underneath them, to the point where the player can just walk over the zombies. I noticed that when I check isKinematic on the Rigidbody the zombies cant push the player up to go underneath him, so they just run into him(which is what I want). Despite this I am then unable to move. How can i fix this?</p>

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

    public class PlayerMoving1 : MonoBehaviour {
    public float moveSpeed;
    private Rigidbody myRigidbody;
    private Vector3 moveInput;
    private Vector3 moveVelocity;
    private Camera mainCamera;
    public GunController theGun;
      void Start () {
         myRigidbody = GetComponent <Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
     }

// Update is called once per frame
void Update () {
    moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    moveVelocity = moveInput * moveSpeed;
    Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
    Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
    float rayLength;
    if(groundPlane.Raycast(cameraRay,out rayLength))
    {
        Vector3 pointToLook = cameraRay.GetPoint(rayLength);
        transform.LookAt(new Vector3(pointToLook.x,transform.position.y,pointToLook.z));
    }
    if (Input.GetMouseButtonDown(0))
        theGun.isFiring = true;
    if (Input.GetMouseButtonUp(0))
        theGun.isFiring = false;
}
void FixedUpdate(){
    myRigidbody.velocity = moveVelocity;
}
}
</code>```

答:
With isKinematic == true You can't change object position through rigidbody, You can only change transform.position.

I think it could be better, if You set isKinematic to false and add stopping distance to enemies, so they can't get too close to player.

Body:
My game is a topdown zombie shooter and whenever the zombies get to the player they bunch up underneath them, to the point where the player can just walk over the zombies. I noticed that when I check isKinematic on the Rigidbody the zombies cant push the player up to go underneath him, so they just run into him(which is what I want). Despite this I am then unable to move. How can i fix this?

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerMoving1 : MonoBehaviour {
    public float moveSpeed;
    private Rigidbody myRigidbody;
    private Vector3 moveInput;
    private Vector3 moveVelocity;
    private Camera mainCamera;
    public GunController theGun;
      void Start () {
         myRigidbody = GetComponent <Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
     }

// Update is called once per frame
void Update () {
    moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    moveVelocity = moveInput * moveSpeed;
    Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
    Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
    float rayLength;
    if(groundPlane.Raycast(cameraRay,out rayLength))
    {
        Vector3 pointToLook = cameraRay.GetPoint(rayLength);
        transform.LookAt(new Vector3(pointToLook.x,transform.position.y,pointToLook.z));
    }
    if (Input.GetMouseButtonDown(0))
        theGun.isFiring = true;
    if (Input.GetMouseButtonUp(0))
        theGun.isFiring = false;
}
void FixedUpdate(){
    myRigidbody.velocity = moveVelocity;
}
}


问:
Difference between synchronized(this) and few synchronized methods of class
In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?

Code in the book:

```<code>public class IntBuffer
{
    private int index;
    private int[] buffer = new int[8];

    // Function called by producer thread
    public synchronized void produce(int num) {
        while(index == buffer.length - 1) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        buffer[index++] = num;
        notifyAll();
    }

    // Function called by consumer thread
    public synchronized int consume() {
        while(index == 0) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        int ret = buffer[--index];
        notifyAll();
        return ret;
    }
}
</code>```

答:
Using synchronized(this) requires the calling thread to take the same lock as when it calls an instance method using the synchronized modifier on the method. There are some differences in what bytecode is generated but that's a pretty low-level distinction.

The purpose of the synchronized keyword is to protect shared state from concurrent access. The produce and consume methods use the same internal state so it's reasonable that they are both protected by the same lock.

The posted code looks well-done, my only nitpick is i would let the methods throw InterruptedException instead of catching it. Both the produce and consume methods require the calling thread to acquire the lock on the instance that the method is being called on.

Body:
In Programming Interviews Exposed book (Wrox publications), code for Producer consumer problem uses 'synchronized' keyword for each of produce() and consume() methods inside a class called IntBuffer. Is this different than using synchronized(this) inside each of those methods ? The book says, "When a thread is busy waiting in produce(), no thread can enter consume() because methods are synchronized." I don't feel that makes sense for the code in the book because, when a thread is busy waiting in produce(), no thread can enter produce(). However other thread can enter consume() which shatters the idea of mutual exclusion. The methods produce and consume should both entirely be synchronized right ?

Code in the book:

public class IntBuffer
{
    private int index;
    private int[] buffer = new int[8];

    // Function called by producer thread
    public synchronized void produce(int num) {
        while(index == buffer.length - 1) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        buffer[index++] = num;
        notifyAll();
    }

    // Function called by consumer thread
    public synchronized int consume() {
        while(index == 0) {
            try { wait();}
            catch(InterruptedException ex) {}
        }
        int ret = buffer[--index];
        notifyAll();
        return ret;
    }
}