问:
Openssl verify with chained CA and chained Cert
I have a certificate chain as:
root CA -> intermediate CA -> org CA -> client Cert

When I verify the client cert with CA as root CA -> intermediate CA -> org CA, it works:

$ cat org_1_ca/ca_crt.pem intermediate_ca/ca_crt.pem root_ca/ca_crt.pem > /tmp/test123.pem
$ openssl verify -CAfile /tmp/test123.pem client/client_crt.pem
client_crt.pem: OK

But when I chained my client cert with org CA (org CA -> client Cert), and have the rest of the chain as CA (root CA -> intermediate CA), it doesn't:

$ cat intermediate_ca/ca_crt.pem root_ca/ca_crt.pem > /tmp/test12.pem
$ openssl verify -CAfile /tmp/test12.pem client/org1_client_crt.pem
client/org1_client_crt.pem: C = US, ST = CA, L = LA, O = PP, OU = TEST, CN = user
error 20 at 0 depth lookup:unable to get local issuer certificate

Is this something that fundamentally wrong or openssl verify doesn't like that? I tried the same thing with nginx and and openssl connect and there was no luck there. Any help is appreciated.

答:
The openssl commandline verify operation reads only one certificate, the first one, from the file given as operand, or from each file if more than one is given. This differs from the files specified with the -CAfile -trusted -untrusted options which can (and typically do) contain multiple certs.

Your file client/org1_client_crt.pem presumably contains the client cert and the 'org CA' cert, in that order. Only the client cert is used, the 'org CA' cert is ignored, and as a result you do not have a valid chain to verify.

If you want to use commandline to mimic/test the validation that a receiver (for a client cert, the server) would do, supply the leaf cert as the operand and all other transmitted (chain) certs with -untrusted, and the anchor(s) plus any 'known' intermediates in the truststore either explicit or defaulted.

There is no openssl connect operation; I assume you mean openssl s_client with options including -connect since that's one place it would make sense to use a client cert chain. The -cert option to s_client similarly uses only the first cert in the file. There is no option on commandline to specify the client chain except in the most recent version, 1.1.0, and even there it isn't documented so you have to read the help message carefully or the code, although the API/library has long supported this for code you write yourself.

Through 1.0.2 if you want to send a client cert with full chain to the server (as you should per the RFCs), assuming the server requests client authentication which is not usual and not the default for nginx (among others), you have to use a trick: supply all the certs needed for the client chain in the truststore, in addition to the anchor(s) needed to verify the server, either using -CAfile and/or -CApath explicitly, or using (modifying if needed) the default truststore unless your openssl is an older non-RedHat version where the default truststore didn't work in s_client s_server s_time only.

And the same is true about the server cert/chain in s_server except that it is used almost always instead of very rarely.


来源: stackexchange

问:
How to invoke a delegate with optional params?
I have the following:

```<code>var availableDelegates = new Dictionary<string, SampleHandler>{
    {"TestWithNoParams", SampleHandlerOne }, // this is what I have now - working
    {"TestWithParamSetA", SampleHandlerTwo } // need this
    {"TestWithNoParams", SampleHandlerTwo } // and this - working
}

public static SampleHandler SampleHandlerOne(){
     // do stuff - working
}

// v1
public static SampleHandler SampleHandlerTwo(){
     // do stuff without parameters - working
}

// v2
public static SampleHandler SampleHandlerTwo(HandlerTwoParams params = null) { // trying to update to support optional params
     // do stuff with parameters - not working
     // params.Foo = bar
}
</code>```

How can I pass optional parameters to a delegate?  The idea would be that I can do:

```<code>if (someCondition)
    availableDelegates[target].Invoke(optionalParams);
else
    availableDelegates[target].Invoke();
</code>```

答: You can achieve exactly what you're looking for with optional parameters on your delegate methods, passing the parameters via the Invoke method. This previous answer shows how this can be done: Can a Delegate have an optional parameter?

ContentLicense: CC BY-SA 3.0

Body:
I have the following:

var availableDelegates = new Dictionary<string, SampleHandler>{
    {"TestWithNoParams", SampleHandlerOne }, // this is what I have now - working
    {"TestWithParamSetA", SampleHandlerTwo } // need this
    {"TestWithNoParams", SampleHandlerTwo } // and this - working
}

public static SampleHandler SampleHandlerOne(){
     // do stuff - working
}

// v1
public static SampleHandler SampleHandlerTwo(){
     // do stuff without parameters - working
}

// v2
public static SampleHandler SampleHandlerTwo(HandlerTwoParams params = null) { // trying to update to support optional params
     // do stuff with parameters - not working
     // params.Foo = bar
}

How can I pass optional parameters to a delegate?  The idea would be that I can do:

if (someCondition)
    availableDelegates[target].Invoke(optionalParams);
else
    availableDelegates[target].Invoke();


问:
Perl: Don't print any lines that are duplicates
What is a Perl one-liner to only print those lines that only ever appear once (that is, do not print if it appears more than once--the truly unique lines)?

For example, if I have a file that contains duplicate lines:

```<code>line1
line2
line2
line3
line1
line4
line5
</code>```

The output should be:

```<code>line3
line4
line5
</code>```

I can do perl -ne 'print if $a{$_}++' file to see only the lines that are duplicates...

```<code>line2
line1
</code>```

I can swap the if for its antonym, unless, and see only one occurrence of each line in the file...

```<code>perl -ne 'print unless $a{$_}++' file
line1
line2
line3
line4
line5
</code>```

I'm assuming I have to slurp the entire file in and process it using single \n delimiters for each line, maybe into a hash?  Just not sure how to do that.

答:
Another way to do it:</p>

```<code>perl -e'@a=<>; $d{$_}++ for @a; print grep {$d{$_}<2} @a' file
</code>```

Body:
What is a Perl one-liner to only print those lines that only ever appear once (that is, do not print if it appears more than once--the truly unique lines)?

For example, if I have a file that contains duplicate lines:

line1
line2
line2
line3
line1
line4
line5

The output should be:

line3
line4
line5

I can do perl -ne 'print if $a{$_}++' file to see only the lines that are duplicates...

line2
line1

I can swap the if for its antonym, unless, and see only one occurrence of each line in the file...

perl -ne 'print unless $a{$_}++' file
line1
line2
line3
line4
line5

I'm assuming I have to slurp the entire file in and process it using single \n delimiters for each line, maybe into a hash?  Just not sure how to do that.

Body:
Another way to do it:

perl -e'@a=<>; $d{$_}++ for @a; print grep {$d{$_}<2} @a' file


问:
ASP.NET 2.5 prefixing ctl00 and ASP.NET 4 not prefixing ctl00
Does anyone know why ASP.NET 4 has dropped the ctl00 prefix on ASP controls?

Is there a setting I have missed?

答:
In ASP.NET 4.0, they've introduced support for cleaner HTML syntax.  You can read about it at Scott Gu's blog. If you want the classic model for Client IDs, you can adjust your web.config:

```<code><configuration>
    <system.web>
        <pages controlRenderingCompatibilityVersion="3.5" />
</code>```

And that'll make upgrading your application easier. You can change this per control (and per page) by using the Control.ClientIDMode property, which can also be set in the web config:

```<code><configuration>
    <system.web>
        <pages clientIDMode="AutoID|Predictable|Static|Inherit" />
</code>```

AutoID renders the controls with the classic ASP.NET 2.0 model.

Body:
In ASP.NET 4.0, they've introduced support for cleaner HTML syntax.  You can read about it at Scott Gu's blog. If you want the classic model for Client IDs, you can adjust your web.config:

<configuration>
    <system.web>
        <pages controlRenderingCompatibilityVersion="3.5" />

And that'll make upgrading your application easier. You can change this per control (and per page) by using the Control.ClientIDMode property, which can also be set in the web config:

<configuration>
    <system.web>
        <pages clientIDMode="AutoID|Predictable|Static|Inherit" />

AutoID renders the controls with the classic ASP.NET 2.0 model.

ContentLicense: CC BY-SA 2.5


问:
Selenium Grid session terminated because SO_Timeout
From C# client, my driver variable returns "Selenium Grid session terminated because SO_Timeout" after 2 seconds. I'm looking for a way to increase that from SE Grid server since it looks like I need to increase the timeout from Selenium Node.

Thanks for helping with this issue.

答:
resolved the problem.

I did not setup timeout properly.
It should be "timeout" parameter instead of "browser_timeout" for this regard.

inside the json, it is in millisecond and from command line, it is in second measurement.

I changed the json timeout so it will cover the 30 seconds timeout parameter I passed from the Selenium client driver.

The json looks like this:

{ "host": null,
"port": 80,
"newSessionWaitTimeout": -1,
"servlets": [],
"prioritizer": null,
"capabilityMatcher":
"org.openqa.grid.internal.utils.DefaultCapabilityMatcher", "throwOnCapabilityNotPresent": true,
"nodePolling": 5000,
"cleanUpCycle": 5000,
"browserTimeout": 60000,
"timeout":50000,
"maxSession": 5,
"jettyMaxThreads": -1 }

Thank you Krishnan for pointing me out the reference page.

Buu


问:
Tensorflow 1.1 MultiRNNCell Shape Errors (Init_State related)
UPDATE:  I believe strongly that the error is related to the init_state as created and fed into the tf.nn.dynamic_rnn(...) as an argument.  So the question becomes, what is the correct shape of, or way to construct, an initial state for a stacked RNN?

I am trying to get a MultiRNNCell definition to work in TensorFlow 1.1.

The graph definition, with helper function to define a GRU cell, is follows below.  The basic idea is to define a placeholder x as a lengthy string of samples of numeric data.  This data will be broken into equal length frames via shaping, and one frame will be presented at each timestep.  I would then like to process this via a stack of two (for now) cells of GRUs.

```<code>def gru_cell(state_size):
     cell = tf.contrib.rnn.GRUCell(state_size)
     return cell

graph = tf.Graph()
with graph.as_default():

     x = tf.placeholder(tf.float32, [batch_size, num_samples], name="Input_Placeholder")
     y = tf.placeholder(tf.int32, [batch_size, num_frames], name="Labels_Placeholder")

     init_state = tf.zeros([batch_size, state_size], name="Initial_State_Placeholder")

     rnn_inputs = tf.reshape(x, (batch_size, num_frames, frame_length))
     cell = tf.contrib.rnn.MultiRNNCell([gru_cell(state_size) for _ in range(2)], state_is_tuple=False)
     rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, rnn_inputs, initial_state=init_state)
</code>```

The graph definition goes on from there with loss functions, optimizers, etc.  But that is the place where it breaks down with the following lengthy error.

It will become relevant at the very last part of the error that batch_size is 10, and frame_length and state_size are both 80.

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-30-4c48b596e055> in <module>()
     14     print(rnn_inputs)
     15     cell = tf.contrib.rnn.MultiRNNCell([gru_cell(state_size) for _ in range(2)], state_is_tuple=False)
---> 16     rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, rnn_inputs, initial_state=init_state)
     17
     18     with tf.variable_scope('softmax'):

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/rnn.pyc in dynamic_rnn(cell, inputs, sequence_length, initial_state, dtype, parallel_iterations, swap_memory, time_major, scope)
    551         swap_memory=swap_memory,
    552         sequence_length=sequence_length,
--> 553         dtype=dtype)
    554
    555     # Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth].

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/rnn.pyc in _dynamic_rnn_loop(cell, inputs, initial_state, parallel_iterations, swap_memory, sequence_length, dtype)
    718       loop_vars=(time, output_ta, state),
    719       parallel_iterations=parallel_iterations,
--> 720       swap_memory=swap_memory)
    721
    722   # Unpack final output if not using output tuples.

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.pyc in while_loop(cond, body, loop_vars, shape_invariants, parallel_iterations, back_prop, swap_memory, name)
   2621     context = WhileContext(parallel_iterations, back_prop, swap_memory, name)
   2622     ops.add_to_collection(ops.GraphKeys.WHILE_CONTEXT, context)
-> 2623     result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
   2624     return result
   2625

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.pyc in BuildLoop(self, pred, body, loop_vars, shape_invariants)
   2454       self.Enter()
   2455       original_body_result, exit_vars = self._BuildLoop(
-> 2456           pred, body, original_loop_vars, loop_vars, shape_invariants)
   2457     finally:
   2458       self.Exit()

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.pyc in _BuildLoop(self, pred, body, original_loop_vars, loop_vars, shape_invariants)
   2435     for m_var, n_var in zip(merge_vars, next_vars):
   2436       if isinstance(m_var, ops.Tensor):
-> 2437         _EnforceShapeInvariant(m_var, n_var)
   2438
   2439     # Exit the loop.

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.pyc in _EnforceShapeInvariant(merge_var, next_var)
    565           "Provide shape invariants using either the `shape_invariants` "
    566           "argument of tf.while_loop or set_shape() on the loop variables."
--> 567           % (merge_var.name, m_shape, n_shape))
    568   else:
    569     if not isinstance(var, (ops.IndexedSlices, sparse_tensor.SparseTensor)):

ValueError: The shape for rnn/while/Merge_2:0 is not an invariant for the loop. It enters the loop with shape (10, 80), but has shape (10, 160) after one iteration. Provide shape invariants using either the `shape_invariants` argument of tf.while_loop or set_shape() on the loop variables.
</code>```

That almost looks like the network starts as a 2-stack of 80s and somehow gets converted a 1-stack of 160.  Any help on fixing this?  Am I misunderstanding the use of the MultiRNNCell?

答:
Based on Allen Lavoie's comment above, the corrected code is:

```<code>def gru_cell(state_size):
     cell = tf.contrib.rnn.GRUCell(state_size)
     return cell

num_layers = 2  # <---------
graph = tf.Graph()
with graph.as_default():

     x = tf.placeholder(tf.float32, [batch_size, num_samples], name="Input_Placeholder")
     y = tf.placeholder(tf.int32, [batch_size, num_frames], name="Labels_Placeholder")

     init_state = tf.zeros([batch_size, num_layer * state_size], name="Initial_State_Placeholder") # <---------

     rnn_inputs = tf.reshape(x, (batch_size, num_frames, frame_length))
     cell = tf.contrib.rnn.MultiRNNCell([gru_cell(state_size) for _ in range(num_layer)], state_is_tuple=False) # <---------
     rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, rnn_inputs, initial_state=init_state)
</code>```

Note three changes above.
Note also that these changes must ripple everywhere that init_state flows, including especially if you are feeding them into a feed_dict.

Body:
UPDATE:  I believe strongly that the error is related to the init_state as created and fed into the tf.nn.dynamic_rnn(...) as an argument.  So the question becomes, what is the correct shape of, or way to construct, an initial state for a stacked RNN?

I am trying to get a MultiRNNCell definition to work in TensorFlow 1.1.

The graph definition, with helper function to define a GRU cell, is follows below.  The basic idea is to define a placeholder x as a lengthy string of samples of numeric data.  This data will be broken into equal length frames via shaping, and one frame will be presented at each timestep.  I would then like to process this via a stack of two (for now) cells of GRUs.

def gru_cell(state_size):
     cell = tf.contrib.rnn.GRUCell(state_size)
     return cell

graph = tf.Graph()
with graph.as_default():

     x = tf.placeholder(tf.float32, [batch_size, num_samples], name="Input_Placeholder")
     y = tf.placeholder(tf.int32, [batch_size, num_frames], name="Labels_Placeholder")

     init_state = tf.zeros([batch_size, state_size], name="Initial_State_Placeholder")

     rnn_inputs = tf.reshape(x, (batch_size, num_frames, frame_length))
     cell = tf.contrib.rnn.MultiRNNCell([gru_cell(state_size) for _ in range(2)], state_is_tuple=False)
     rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, rnn_inputs, initial_state=init_state)

The graph definition goes on from there with loss functions, optimizers, etc.  But that is the place where it breaks down with the following lengthy error.

It will become relevant at the very last part of the error that batch_size is 10, and frame_length and state_size are both 80.

ValueError                                Traceback (most recent call last)
<ipython-input-30-4c48b596e055> in <module>()
     14     print(rnn_inputs)
     15     cell = tf.contrib.rnn.MultiRNNCell([gru_cell(state_size) for _ in range(2)], state_is_tuple=False)
---> 16     rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, rnn_inputs, initial_state=init_state)
     17
     18     with tf.variable_scope('softmax'):

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/rnn.pyc in dynamic_rnn(cell, inputs, sequence_length, initial_state, dtype, parallel_iterations, swap_memory, time_major, scope)
    551         swap_memory=swap_memory,
    552         sequence_length=sequence_length,
--> 553         dtype=dtype)
    554
    555     # Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth].

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/rnn.pyc in _dynamic_rnn_loop(cell, inputs, initial_state, parallel_iterations, swap_memory, sequence_length, dtype)
    718       loop_vars=(time, output_ta, state),
    719       parallel_iterations=parallel_iterations,
--> 720       swap_memory=swap_memory)
    721
    722   # Unpack final output if not using output tuples.

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.pyc in while_loop(cond, body, loop_vars, shape_invariants, parallel_iterations, back_prop, swap_memory, name)
   2621     context = WhileContext(parallel_iterations, back_prop, swap_memory, name)
   2622     ops.add_to_collection(ops.GraphKeys.WHILE_CONTEXT, context)
-> 2623     result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
   2624     return result
   2625

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.pyc in BuildLoop(self, pred, body, loop_vars, shape_invariants)
   2454       self.Enter()
   2455       original_body_result, exit_vars = self._BuildLoop(
-> 2456           pred, body, original_loop_vars, loop_vars, shape_invariants)
   2457     finally:
   2458       self.Exit()

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.pyc in _BuildLoop(self, pred, body, original_loop_vars, loop_vars, shape_invariants)
   2435     for m_var, n_var in zip(merge_vars, next_vars):
   2436       if isinstance(m_var, ops.Tensor):
-> 2437         _EnforceShapeInvariant(m_var, n_var)
   2438
   2439     # Exit the loop.

/home/novak/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.pyc in _EnforceShapeInvariant(merge_var, next_var)
    565           "Provide shape invariants using either the `shape_invariants` "
    566           "argument of tf.while_loop or set_shape() on the loop variables."
--> 567           % (merge_var.name, m_shape, n_shape))
    568   else:
    569     if not isinstance(var, (ops.IndexedSlices, sparse_tensor.SparseTensor)):

ValueError: The shape for rnn/while/Merge_2:0 is not an invariant for the loop. It enters the loop with shape (10, 80), but has shape (10, 160) after one iteration. Provide shape invariants using either the `shape_invariants` argument of tf.while_loop or set_shape() on the loop variables.

That almost looks like the network starts as a 2-stack of 80s and somehow gets converted a 1-stack of 160.  Any help on fixing this?  Am I misunderstanding the use of the MultiRNNCell?

Body:
Based on Allen Lavoie's comment above, the corrected code is:

def gru_cell(state_size):
     cell = tf.contrib.rnn.GRUCell(state_size)
     return cell

num_layers = 2  # <---------
graph = tf.Graph()
with graph.as_default():

     x = tf.placeholder(tf.float32, [batch_size, num_samples], name="Input_Placeholder")
     y = tf.placeholder(tf.int32, [batch_size, num_frames], name="Labels_Placeholder")

     init_state = tf.zeros([batch_size, num_layer * state_size], name="Initial_State_Placeholder") # <---------

     rnn_inputs = tf.reshape(x, (batch_size, num_frames, frame_length))
     cell = tf.contrib.rnn.MultiRNNCell([gru_cell(state_size) for _ in range(num_layer)], state_is_tuple=False) # <---------
     rnn_outputs, final_state = tf.nn.dynamic_rnn(cell, rnn_inputs, initial_state=init_state)

Note three changes above.
Note also that these changes must ripple everywhere that init_state flows, including especially if you are feeding them into a feed_dict.


问:
Dependency Injection with WCF proxy
I have a service (Service1) that uses another serice (Service2). I am using Dependency injection for both services and need to inject the proxy for Service2 into Service1.

I am unsure how to deal with the fact that the proxy is not a simple class of type IService2 but a proxy inheriting from ClientBase as well. Obviously my Service1 implementation needs to open the proxy and should also close it after use or abort it if an exception occurs but if I am just injecting an instance of IService2 then I cannot do this (without casting) because the Open, Close and Abort methods are on the base class whilst my operations are on the interface.

When it comes to testing Service1, I would expect to mock just the interface but if the Service1 implementation expect Open, Close and Abort methods, then this is tricky. In the past, I have done something hacky like this but there must be a better way!

```<code>var proxyBase = _service2 as ClientBase;

if (proxyBase != null)
{
  proxyBase.Open();
}

_service2.DoOperation("blah"); //the actual operation

if (proxyBase != null)
{
  proxyBase.Close();
}

// repeat for Abort in exception handler(s).
</code>```

What are other people doing?

Thanks

答: I ended up using this approach which uses Castle Dynamic Proxy to intercept calls and handle WCF specifics. It works really well and allows the class where the proxy is injected to treat it like a normal class / interface. This class is then totally unit testable by mocking the service contract interface.</p>

Title: Dependency Injection with WCF proxy

Body:
I have a service (Service1) that uses another serice (Service2). I am using Dependency injection for both services and need to inject the proxy for Service2 into Service1.

I am unsure how to deal with the fact that the proxy is not a simple class of type IService2 but a proxy inheriting from ClientBase as well. Obviously my Service1 implementation needs to open the proxy and should also close it after use or abort it if an exception occurs but if I am just injecting an instance of IService2 then I cannot do this (without casting) because the Open, Close and Abort methods are on the base class whilst my operations are on the interface.

When it comes to testing Service1, I would expect to mock just the interface but if the Service1 implementation expect Open, Close and Abort methods, then this is tricky. In the past, I have done something hacky like this but there must be a better way!

var proxyBase = _service2 as ClientBase;

if (proxyBase != null)
{
  proxyBase.Open();
}

_service2.DoOperation("blah"); //the actual operation

if (proxyBase != null)
{
  proxyBase.Close();
}

// repeat for Abort in exception handler(s).

What are other people doing?

Thanks


问:
mongodb collection fetch information with criteria
I'm facing the following issue:

I have this data in a collection in mongoDB

```<code>   { Node: '2', Type: 'temperature', Value: '25.9', _id: 5936f90c81c543363d42f598 },
   { Node: '3', Type: 'temperature', Value: '31.0', _id: 5936f90c81c543363d42f599 },
   { Node: '1', Type: 'humidity', Value: '45.2', _id: 5936f90c81c543363d42f59a },
   { Node: '2', Type: 'humidity', Value: '55.3', _id: 5936f90c81c543363d42f59b }
</code>```

I want to fetch it by type.

Can't find what I'm doing wrong in my code...

```<code>var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  if (err) throw err;
  var collection = db.collection('readings');
  collection.find({}).toArray(function(err, result) {
    if (err) throw err;
    //console.log(result); //mostrar os resultados
    var numTemps = 0;
    result.forEach(function(err,doc){
      if ("temperature" in result) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(err,doc){
      if ("humidity" in result) {
        numHums = numHums + 1;
      };
    });
    console.log("Temps: " + numTemps);
    console.log("Hums: " + numHums);
    db.close();
  });
});
</code>```

答:
You have a few bugs.

```<code>result.forEach(function(err,doc){
      if ("temperature" in result) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(err,doc){
      if ("humidity" in result) {
        numHums = numHums + 1;
      };
    });
</code>```

I believe what you actually meant was:

```<code>result.forEach(function(doc){
      if ("temperature" in doc) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(doc){
      if ("humidity" in doc) {
        numHums = numHums + 1;
      };
    });
</code>```

or, with better formatting and performance (and more DRY):

```<code>result.forEach(function(doc){

  if ("temperature" in doc) {
    numTemps++;
  };

  if ("humidity" in doc) {
    numHums++;
  };

});
</code>```

Body:
I'm facing the following issue:

I have this data in a collection in mongoDB

   { Node: '2', Type: 'temperature', Value: '25.9', _id: 5936f90c81c543363d42f598 },
   { Node: '3', Type: 'temperature', Value: '31.0', _id: 5936f90c81c543363d42f599 },
   { Node: '1', Type: 'humidity', Value: '45.2', _id: 5936f90c81c543363d42f59a },
   { Node: '2', Type: 'humidity', Value: '55.3', _id: 5936f90c81c543363d42f59b }

I want to fetch it by type.

Can't find what I'm doing wrong in my code...

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  if (err) throw err;
  var collection = db.collection('readings');
  collection.find({}).toArray(function(err, result) {
    if (err) throw err;
    //console.log(result); //mostrar os resultados
    var numTemps = 0;
    result.forEach(function(err,doc){
      if ("temperature" in result) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(err,doc){
      if ("humidity" in result) {
        numHums = numHums + 1;
      };
    });
    console.log("Temps: " + numTemps);
    console.log("Hums: " + numHums);
    db.close();
  });
});

Body:
You have a few bugs.

result.forEach(function(err,doc){
      if ("temperature" in result) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(err,doc){
      if ("humidity" in result) {
        numHums = numHums + 1;
      };
    });

I believe what you actually meant was:

result.forEach(function(doc){
      if ("temperature" in doc) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(doc){
      if ("humidity" in doc) {
        numHums = numHums + 1;
      };
    });

or, with better formatting and performance (and more DRY):

result.forEach(function(doc){

  if ("temperature" in doc) {
    numTemps++;
  };

  if ("humidity" in doc) {
    numHums++;
  };

});


问:
gcc linker not automatically including dependency libraries
I am in the process of updating an arm cross compiler from 4.3.3 to 4.9.4.  One issue I am seeing is that the new compiler no longer automatically includes dependent libraries.  For example:

gcc ... -L -l -lssl -lrt

works fine with the previous compiler.  If libssl needed to reference something in libcrypto, then the linker would automatically find and link with libcrypto (no -lcrypto needed).

With the new compiler, this still works, but only if libssl does not reference anything in libcrypto.  If it does, then the -lcyrpto is required.  The same issue applies to -lpthread, -ldl, etc.

Is this a change in the behavior of gcc or is something not configured properly when building gcc?

答: Are you using static or dynamic libraries? For dynamic libraries, if libssl depends on libcrypto, you don't need to explicitly link -lcrypto as long as libssl itself was correctly linked, but if you want to make direct use in your program of symbols from libcrypto, then you have to explicitly link it. This is a change/intentional-regression in newer versions of binutils.


问:
write result of rank loop in r
I've been hitting walls trying to write the results of a loop to a csv.  I'm trying to rank data within each of 20 columns. The loop I'm using is:

```<code>for (i in 1:ncol(testing_file)) {
  print(rank(testing_file[[i]]))
}
</code>```

This works and prints expected results to screen. I've tried a lot of methods suggested in various discussions to write this result to file or data frame, most with no luck.
I'll just include my most promising lead, which returns only one column of correct data, with a column heading of "testing":

```<code>for (i in 1:ncol(testing_file)) {
  testing<- (rank(testing_file[[i]]))
  testingdf <- as.data.frame(testing)
}
</code>```

Any help is greatly appreciated!

答:
I found a solution that works:</p>

```<code>testage<- data.frame(matrix(, nrow=73, ncol=20))  #This creates an empty data
frame that the ranked results will go into
for (i in 1:ncol(testing_file)) {
testage[i] <- rank(testing_file[[i]])
print(testage[i])
} #this is the loop that ranks data within each column
colnames(testage) <- colnames(testing_file) #take the column names from the
original file and apply them to the ranked file.
</code>```

Title: write result of rank loop in r

Body:
I've been hitting walls trying to write the results of a loop to a csv.  I'm trying to rank data within each of 20 columns. The loop I'm using is:

for (i in 1:ncol(testing_file)) {
  print(rank(testing_file[[i]]))
}

This works and prints expected results to screen. I've tried a lot of methods suggested in various discussions to write this result to file or data frame, most with no luck.
I'll just include my most promising lead, which returns only one column of correct data, with a column heading of "testing":

for (i in 1:ncol(testing_file)) {
  testing<- (rank(testing_file[[i]]))
  testingdf <- as.data.frame(testing)
}

Any help is greatly appreciated!

Body:
I found a solution that works:

testage<- data.frame(matrix(, nrow=73, ncol=20))  #This creates an empty data
frame that the ranked results will go into
for (i in 1:ncol(testing_file)) {
testage[i] <- rank(testing_file[[i]])
print(testage[i])
} #this is the loop that ranks data within each column
colnames(testage) <- colnames(testing_file) #take the column names from the
original file and apply them to the ranked file.


问:
Override wordpress login redirect function
I have a login function stored in a custom plugin that over-rides the standard Wordpress login to, once a user logs in, redirect them to a desired page:

```<code>function admin_login_redirect( $redirect_to, $request, $user )
{
global $user;
if( isset( $user->roles ) && is_array( $user->roles ) ) {
if( in_array( "administrator", $user->roles ) ) {
return $redirect_to;
} else {
return home_url();
}
}
else
{
return $redirect_to;
}
}
add_filter("login_redirect", "admin_login_redirect", 10, 3);
</code>```

This works a treat but I now need to build an additional/alternative login page that, if used, redirects the user to a different landing page.

It seems that my only three logical options are to either:

Write code in the new login page to ignore the plugin redirect function (is this even possible!?)

Recognize the login template/form the user is using and build this logic into the above function or

Over ride the redirect function (above) within the new/alternative login page.

Does anyone know if either of these are possible and if so how would i action it?

答:
I think the best option is to create a new login page and define the redirect after login action on that page.

The page template for the custom login page will look something like this:

```<code><?php
    // Define custom redirect
    $custom_redirect = "REDIRECT_URL";

    // If user is logged out
    if ( !is_user_logged_in() ) {
        $args = array(
            'redirect' => $custom_redirect
        );

        // Output the login form with arguments
        wp_login_form( $args );
    }
    // Display below if user is logged in
    else {
        wp_loginout( home_url() ); // Display "Log Out" link.
        echo " | ";
        wp_register('', ''); // Display "Site Admin" link.
    }
?>
</code>```

You can either wrap this inside a custom_login_form() function inside functions.php and then call that function inside your custom login page template or place it directly in the custom login page template. You can name the custom page template page-login.php, which will automatically apply to a WP page named "login".

Full guide on creating a custom page template for the login page.

Full guide on customizing the login form.

Body:
I have a login function stored in a custom plugin that over-rides the standard Wordpress login to, once a user logs in, redirect them to a desired page:

function admin_login_redirect( $redirect_to, $request, $user )
{
global $user;
if( isset( $user->roles ) && is_array( $user->roles ) ) {
if( in_array( "administrator", $user->roles ) ) {
return $redirect_to;
} else {
return home_url();
}
}
else
{
return $redirect_to;
}
}
add_filter("login_redirect", "admin_login_redirect", 10, 3);

This works a treat but I now need to build an additional/alternative login page that, if used, redirects the user to a different landing page.

It seems that my only three logical options are to either:

Write code in the new login page to ignore the plugin redirect function (is this even possible!?)

Recognize the login template/form the user is using and build this logic into the above function or

Over ride the redirect function (above) within the new/alternative login page.

Does anyone know if either of these are possible and if so how would i action it?

Body:
I think the best option is to create a new login page and define the redirect after login action on that page.

The page template for the custom login page will look something like this:

<?php
    // Define custom redirect
    $custom_redirect = "REDIRECT_URL";

    // If user is logged out
    if ( !is_user_logged_in() ) {
        $args = array(
            'redirect' => $custom_redirect
        );

        // Output the login form with arguments
        wp_login_form( $args );
    }
    // Display below if user is logged in
    else {
        wp_loginout( home_url() ); // Display "Log Out" link.
        echo " | ";
        wp_register('', ''); // Display "Site Admin" link.
    }
?>

You can either wrap this inside a custom_login_form() function inside functions.php and then call that function inside your custom login page template or place it directly in the custom login page template. You can name the custom page template page-login.php, which will automatically apply to a WP page named "login".

Full guide on creating a custom page template for the login page.

Full guide on customizing the login form.


问:
How to Depict Either/Or Inheritance in a UML diagram?
So lets say I have a class CelebrityDog. CelebrityDog can either be a BigDog or a SmallDog depending on what the user wants.

It will inherit the properties of one of them, but not of both. How would I depict this in a UML diagram?

答:
Dog is the top level class.  It does not contain a size attribute.
CelebrityDog derives from Dog (as do normal, EverydayDogs).
BigDog and SmallDog derive from CelebrityDog.  Perhaps change their class names to BigCelebrityDog and SmallCelebrityDog.

It is possible to use multiple inheritance to solve this, but that can be confusing.


答:
As far as i remember its up to ASP.NET to decide which prefix to use.
Its a bad practice to reference on the controls with hardcoded id value.

You should use ClientId property that will always generate you proper Id:

```<code><td class="tmarg10" style="width: 150px">
    <label for="<%=txtName.ClientID %>">
        Name of the mall group :</label>
</td>
<td class="tmarg10">
    <asp:TextBox ID="txtName" runat="server" Columns="90" /> <br />
</td>
</code>```

In the example above, its calculating proper ID of the textbox and putting it into label attribute. In this way you will no more worry about keeping the same id of the control.

Title: ASP.NET 2.5 prefixing ctl00 and ASP.NET 4 not prefixing ctl00

Body:
Does anyone know why ASP.NET 4 has dropped the ctl00 prefix on ASP controls?

Is there a setting I have missed?

Body:
As far as i remember its up to ASP.NET to decide which prefix to use.
Its a bad practice to reference on the controls with hardcoded id value.

You should use ClientId property that will always generate you proper Id:

<td class="tmarg10" style="width: 150px">
    <label for="<%=txtName.ClientID %>">
        Name of the mall group :</label>
</td>
<td class="tmarg10">
    <asp:TextBox ID="txtName" runat="server" Columns="90" /> <br />
</td>

In the example above, its calculating proper ID of the textbox and putting it into label attribute. In this way you will no more worry about keeping the same id of the control.


问:
Where in sub-query or in main query, what is preferable?
Simplified example 1:

```<code>SELECT * FROM (
    SELECT x, y, z FROM table1
    WHERE x = 'test'
    -- union, etc, etc, complicated stuff...
) AS t
-- union, etc, etc, complicated stuff...
</code>```

Simplified example 2:

```<code>SELECT * FROM (
    SELECT x, y, z FROM table1
    -- union, etc, etc, complicated stuff...
) AS t
-- union, etc, etc, complicated stuff...
WHERE x = 'test'
</code>```

Which of the above is more popular? Is more performant? Is recommended for other reasons? Does it help to filter the results "early", before doing union and similar operations? Thanks.

答:
In MySQL you definitely want the filtering condition in the subquery.  MySQL materializes subqueries.  The smaller the subquery the faster the query.

In addition, MySQL may be able to use an index for the condition.

Body:
Simplified example 1:

SELECT * FROM (
    SELECT x, y, z FROM table1
    WHERE x = 'test'
    -- union, etc, etc, complicated stuff...
) AS t
-- union, etc, etc, complicated stuff...

Simplified example 2:

SELECT * FROM (
    SELECT x, y, z FROM table1
    -- union, etc, etc, complicated stuff...
) AS t
-- union, etc, etc, complicated stuff...
WHERE x = 'test'

Which of the above is more popular? Is more performant? Is recommended for other reasons? Does it help to filter the results "early", before doing union and similar operations? Thanks.


问:
Using Picasso Images not showing in Recycler view
I am trying to show images from a Firebase database in recycler view in android studio but the images are not displaying. I am not sure where I have gone wrong or what the problem is.

Main Activity.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.test.test.AddBrandPage"
        android:weightSum="1">

    <TextView
        android:id="@+id/editText"
        android:layout_width="383dp"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="17dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Select your favourite stores..."
        android:textAlignment="center"
        android:textSize="22sp" />

    <LinearLayout
        android:id="@+id/alphaindex"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal"></LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recylView"
        android:layout_width="337dp"
        android:layout_height="370dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/editText2"
        android:layout_marginLeft="14dp"
        android:layout_marginRight="14dp"
        android:layout_marginStart="14dp"
        android:layout_marginTop="24dp"
        android:layout_weight="0.23"
        android:scrollbars="vertical">
        </android.support.v7.widget.RecyclerView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.11"
        android:layout_marginTop="20dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_skip"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="15dp"
            android:layout_marginRight="15dp"
            android:background="@color/colorPrimary"
            android:text="Skip"
            android:textAllCaps="true"
            android:textColor="@android:color/background_light"
            android:textSize="20sp"
            android:textStyle="normal|bold" />

        <Button
            android:id="@+id/btn_submit"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="15dp"
            android:layout_marginRight="20dp"
            android:background="@color/colorPrimary"
            android:text="Submit"
            android:textAllCaps="true"
            android:textColor="@android:color/background_light"
            android:textSize="20sp"
            android:textStyle="normal|bold" />

      </LinearLayout>

    </LinearLayout>
</code>```

Logo_items.xml

```<code>      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:cardView="http://schemas.android.com/apk/res-auto"
          android:id="@+id/logo_container"
          android:layout_width="match_parent"
          android:layout_height="100dp"
          android:background="@android:color/darker_gray"
          android:gravity="center_vertical|center_horizontal"
          android:orientation="vertical"
          android:paddingBottom="10dp"
          android:paddingLeft="10dp"
          android:paddingRight="10dp"
          android:paddingTop="10dp"
          android:visibility="visible"
          cardView:layout_collapseParallaxMultiplier="1.0">

    <android.support.v7.widget.CardView
        android:layout_width="155dp"
        android:layout_height="100dp"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        cardView:cardBackgroundColor="@android:color/white">

        <GridLayout
            android:id="@+id/cardView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal|center_vertical"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/img_logo"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_column="1"
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_row="0"
                android:paddingBottom="5dp"
                android:paddingLeft="2.5dp"
                android:paddingRight="2.5dp"
                android:paddingTop="5dp">

            </ImageView>

        </GridLayout>

        <CheckBox
            android:id="@+id/checkbox"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="130dp"
            android:layout_marginTop="66dp"
             />

    </android.support.v7.widget.CardView>

    </LinearLayout>
</code>```

LogoItems.java

```<code>    public class LogoItems {

        //declare variables(the items displayed in the layout)
        private String logo;//, name;

        public String getLogo() {
            return logo;
        }

        public void setLogo(String logo) {
            this.logo = logo;
        }

     }
</code>```

Main Activity.java

```<code>package com.test.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddBrandPage extends AppCompatActivity implements OnClickListener {

    //declare variables
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;
    private DatabaseReference myRef;
    private Button btn_skip;
    private Button btn_submit;
    //private String name;
    //private String url;

    List<LogoItems> brandLogo = new ArrayList<>();
    //HashMap<String, String> dataSet = new HashMap<>();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_brand_page);

        //initialize variables
        btn_skip = (Button) findViewById(R.id.btn_skip);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        myRef = FirebaseDatabase.getInstance().getReference().child("/brands");

        // set the main recyclerview view in the layout
        recyclerView = (RecyclerView) findViewById(R.id.recylView);
        recyclerView.setHasFixedSize(true);

        // set the main layoutManager of the recyclerview
        layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);

        loadLogoImgData();

        // set the recycler view adapter
        adapter =  new LogoAdapter(brandLogo, getBaseContext());
        recyclerView.setAdapter(adapter);

        //set the listener for the buttons click event
        btn_skip.setOnClickListener(this);
        btn_submit.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        if (view == btn_skip) {
            //if skip button clicked close current window and go to user main page
            finish();
            startActivity(new Intent(getApplicationContext(), UserMainPage.class));

        }

    }

    public void loadLogoImgData(){

        brandLogo.clear();
        myRef.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
                    LogoItems value = brandSnapshot.getValue(LogoItems.class);
                    LogoItems brandDetails = new LogoItems();
                   // String name = value.getName();
                    String logos = value.getLogo();
                    //brandDetails.setName(name);
                    brandDetails.setLogo(logos);
                    brandLogo.add(brandDetails);

            }
        }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

      }
    }
</code>```

LogoItemsAdapter.java

```<code>package com.test.test;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

public class LogoAdapter extends RecyclerView.Adapter<LogoAdapter.LogoViewHolder> {

    List<LogoItems> brandLogo = new ArrayList<>();
   // private AddBrandPage addBrandPage;
    private Context context;

    public LogoAdapter(List <LogoItems> brandLogo, Context context){
        this.brandLogo = brandLogo;
        this.context = context;
        //addBrandPage = (AddBrandPage)context;
    }

    @Override
    public LogoAdapter.LogoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.logo_items,parent,false);
        LogoViewHolder logoViewHolder = new LogoViewHolder(view);
        return logoViewHolder;
    }

    @Override
    public void onBindViewHolder(LogoAdapter.LogoViewHolder holder, int position) {

        //holder.logo.setImageURI(Uri.parse(brandLogo.get(position).getLogo()));
        Picasso.with(context).load(brandLogo.get(position).getLogo()).into(holder.logo);

    }

    @Override
    public int getItemCount() {

        return brandLogo.size();
    }

    public static class LogoViewHolder extends RecyclerView.ViewHolder{

        //declare variables
        public ImageView logo;
        CheckBox checkbox;
        //private View itemView;

        public LogoViewHolder(View itemView){
            super(itemView);

            //initialize variables inside the constructor
            logo = (ImageView)itemView.findViewById(R.id.img_logo);
            checkbox = (CheckBox)itemView.findViewById(R.id.checkbox);
           // this.itemView = itemView;

        }

    }

}
</code>```

答:
your code seems a bit vague like here :

```<code>myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value =
brandSnapshot.getValue(LogoItems.class);
LogoItems brandDetails =
 new LogoItems();
 // String name = value.getName();
 String logos = value.getLogo();
  //brandDetails.setName(name);
  brandDetails.setLogo(logos);
  brandLogo.add(brandDetails); } }
</code>```

Change this code to :

```<code> myRef.addValueEventListener(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
 for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
 LogoItems value =
 brandSnapshot.getValue(LogoItems.class);
 brandLogo.add(value); }

  startRecyclerView();

  }
</code>```

Firebase methods are asynchronous, your present code inflates the recylcerview synchronously which means it is loaded before the data has been set and received.

The changed code starts recyclerview asynchronously after the data has been loaded from the database. You can add a progress bar to know the status. You can set it like this (Initialize it before this method and it will be visible by default) :

```<code>  mProgressBar.setVisibility(View.INVISIBLE);
  startRecyclerView();
</code>```

This way the code looks organised.

Body:
I am trying to show images from a Firebase database in recycler view in android studio but the images are not displaying. I am not sure where I have gone wrong or what the problem is.

Main Activity.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.test.test.AddBrandPage"
        android:weightSum="1">

    <TextView
        android:id="@+id/editText"
        android:layout_width="383dp"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="17dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Select your favourite stores..."
        android:textAlignment="center"
        android:textSize="22sp" />

    <LinearLayout
        android:id="@+id/alphaindex"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal"></LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recylView"
        android:layout_width="337dp"
        android:layout_height="370dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/editText2"
        android:layout_marginLeft="14dp"
        android:layout_marginRight="14dp"
        android:layout_marginStart="14dp"
        android:layout_marginTop="24dp"
        android:layout_weight="0.23"
        android:scrollbars="vertical">
        </android.support.v7.widget.RecyclerView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.11"
        android:layout_marginTop="20dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_skip"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="15dp"
            android:layout_marginRight="15dp"
            android:background="@color/colorPrimary"
            android:text="Skip"
            android:textAllCaps="true"
            android:textColor="@android:color/background_light"
            android:textSize="20sp"
            android:textStyle="normal|bold" />

        <Button
            android:id="@+id/btn_submit"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="15dp"
            android:layout_marginRight="20dp"
            android:background="@color/colorPrimary"
            android:text="Submit"
            android:textAllCaps="true"
            android:textColor="@android:color/background_light"
            android:textSize="20sp"
            android:textStyle="normal|bold" />

      </LinearLayout>

    </LinearLayout>

Logo_items.xml

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:cardView="http://schemas.android.com/apk/res-auto"
          android:id="@+id/logo_container"
          android:layout_width="match_parent"
          android:layout_height="100dp"
          android:background="@android:color/darker_gray"
          android:gravity="center_vertical|center_horizontal"
          android:orientation="vertical"
          android:paddingBottom="10dp"
          android:paddingLeft="10dp"
          android:paddingRight="10dp"
          android:paddingTop="10dp"
          android:visibility="visible"
          cardView:layout_collapseParallaxMultiplier="1.0">

    <android.support.v7.widget.CardView
        android:layout_width="155dp"
        android:layout_height="100dp"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        cardView:cardBackgroundColor="@android:color/white">

        <GridLayout
            android:id="@+id/cardView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal|center_vertical"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/img_logo"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_column="1"
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_row="0"
                android:paddingBottom="5dp"
                android:paddingLeft="2.5dp"
                android:paddingRight="2.5dp"
                android:paddingTop="5dp">

            </ImageView>

        </GridLayout>

        <CheckBox
            android:id="@+id/checkbox"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="130dp"
            android:layout_marginTop="66dp"
             />

    </android.support.v7.widget.CardView>

    </LinearLayout>

LogoItems.java

    public class LogoItems {

        //declare variables(the items displayed in the layout)
        private String logo;//, name;

        public String getLogo() {
            return logo;
        }

        public void setLogo(String logo) {
            this.logo = logo;
        }

     }

Main Activity.java

package com.test.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddBrandPage extends AppCompatActivity implements OnClickListener {

    //declare variables
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;
    private DatabaseReference myRef;
    private Button btn_skip;
    private Button btn_submit;
    //private String name;
    //private String url;

    List<LogoItems> brandLogo = new ArrayList<>();
    //HashMap<String, String> dataSet = new HashMap<>();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_brand_page);

        //initialize variables
        btn_skip = (Button) findViewById(R.id.btn_skip);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        myRef = FirebaseDatabase.getInstance().getReference().child("/brands");

        // set the main recyclerview view in the layout
        recyclerView = (RecyclerView) findViewById(R.id.recylView);
        recyclerView.setHasFixedSize(true);

        // set the main layoutManager of the recyclerview
        layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);

        loadLogoImgData();

        // set the recycler view adapter
        adapter =  new LogoAdapter(brandLogo, getBaseContext());
        recyclerView.setAdapter(adapter);

        //set the listener for the buttons click event
        btn_skip.setOnClickListener(this);
        btn_submit.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        if (view == btn_skip) {
            //if skip button clicked close current window and go to user main page
            finish();
            startActivity(new Intent(getApplicationContext(), UserMainPage.class));

        }

    }

    public void loadLogoImgData(){

        brandLogo.clear();
        myRef.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
                    LogoItems value = brandSnapshot.getValue(LogoItems.class);
                    LogoItems brandDetails = new LogoItems();
                   // String name = value.getName();
                    String logos = value.getLogo();
                    //brandDetails.setName(name);
                    brandDetails.setLogo(logos);
                    brandLogo.add(brandDetails);

            }
        }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

      }
    }

LogoItemsAdapter.java

package com.test.test;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

public class LogoAdapter extends RecyclerView.Adapter<LogoAdapter.LogoViewHolder> {

    List<LogoItems> brandLogo = new ArrayList<>();
   // private AddBrandPage addBrandPage;
    private Context context;

    public LogoAdapter(List <LogoItems> brandLogo, Context context){
        this.brandLogo = brandLogo;
        this.context = context;
        //addBrandPage = (AddBrandPage)context;
    }

    @Override
    public LogoAdapter.LogoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.logo_items,parent,false);
        LogoViewHolder logoViewHolder = new LogoViewHolder(view);
        return logoViewHolder;
    }

    @Override
    public void onBindViewHolder(LogoAdapter.LogoViewHolder holder, int position) {

        //holder.logo.setImageURI(Uri.parse(brandLogo.get(position).getLogo()));
        Picasso.with(context).load(brandLogo.get(position).getLogo()).into(holder.logo);

    }

    @Override
    public int getItemCount() {

        return brandLogo.size();
    }

    public static class LogoViewHolder extends RecyclerView.ViewHolder{

        //declare variables
        public ImageView logo;
        CheckBox checkbox;
        //private View itemView;

        public LogoViewHolder(View itemView){
            super(itemView);

            //initialize variables inside the constructor
            logo = (ImageView)itemView.findViewById(R.id.img_logo);
            checkbox = (CheckBox)itemView.findViewById(R.id.checkbox);
           // this.itemView = itemView;

        }

    }

}

Body:
your code seems a bit vague like here :

myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value =
brandSnapshot.getValue(LogoItems.class);
LogoItems brandDetails =
 new LogoItems();
 // String name = value.getName();
 String logos = value.getLogo();
  //brandDetails.setName(name);
  brandDetails.setLogo(logos);
  brandLogo.add(brandDetails); } }

Change this code to :

 myRef.addValueEventListener(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
 for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
 LogoItems value =
 brandSnapshot.getValue(LogoItems.class);
 brandLogo.add(value); }

  startRecyclerView();

  }

Firebase methods are asynchronous, your present code inflates the recylcerview synchronously which means it is loaded before the data has been set and received.

The changed code starts recyclerview asynchronously after the data has been loaded from the database. You can add a progress bar to know the status. You can set it like this (Initialize it before this method and it will be visible by default) :

  mProgressBar.setVisibility(View.INVISIBLE);
  startRecyclerView();

This way the code looks organised.


问:
How can a list's lists be modified efficiently to have equal length to the list's longest list?
I have a 2-D list of shape (300,000, X), where each of the sublists has a different size. In order to convert the data to a Tensor, all of the sublists need to have equal length, but I don't want to lose any data from my sublists in the conversion.

That means that I need to fill all sublists smaller than the longest sublist with filler (-1) in order to create a rectangular array. For my current dataset, the longest sublist is of length 5037.

My conversion code is below:

```<code>for seq in new_format:
    for i in range(0, length-len(seq)):
        seq.append(-1)
</code>```

However, when there are 300,000 sequences in new_format, and length-len(seq) is generally >4000, the process is extraordinarily slow. How can I speed this process up or get around the issue efficiently?

答:
Individual append calls can be rather slow, so use list multiplication to create the whole filler value at once, then concatenate it all at once, e.g.:

```<code>for seq in new_format:
    seq += [-1] * (length-len(seq))
</code>```

seq.extend([-1] * (length-len(seq))) would be equivalent (trivially slower due to generalized method call approach, but likely unnoticeable given size of real work).

In theory, seq.extend(itertools.repeat(-1, length-len(seq))) would avoid the potentially large temporaries, but IIRC, the actual CPython implementation of list.__iadd__/list.extend forces the creation of a temporary list anyway (to handle the case where the generator is defined in terms of the list being extended), so it wouldn't actually avoid the temporary.

Body:
I have a 2-D list of shape (300,000, X), where each of the sublists has a different size. In order to convert the data to a Tensor, all of the sublists need to have equal length, but I don't want to lose any data from my sublists in the conversion.

That means that I need to fill all sublists smaller than the longest sublist with filler (-1) in order to create a rectangular array. For my current dataset, the longest sublist is of length 5037.

My conversion code is below:

for seq in new_format:
    for i in range(0, length-len(seq)):
        seq.append(-1)

However, when there are 300,000 sequences in new_format, and length-len(seq) is generally >4000, the process is extraordinarily slow. How can I speed this process up or get around the issue efficiently?

Body:
Individual append calls can be rather slow, so use list multiplication to create the whole filler value at once, then concatenate it all at once, e.g.:

for seq in new_format:
    seq += [-1] * (length-len(seq))

seq.extend([-1] * (length-len(seq))) would be equivalent (trivially slower due to generalized method call approach, but likely unnoticeable given size of real work).

In theory, seq.extend(itertools.repeat(-1, length-len(seq))) would avoid the potentially large temporaries, but IIRC, the actual CPython implementation of list.__iadd__/list.extend forces the creation of a temporary list anyway (to handle the case where the generator is defined in terms of the list being extended), so it wouldn't actually avoid the temporary.


问:
How to convert CSS to SCSS every time?
I'm a full stack developer that uses sass (.scss) for styling. However, my backend crew, when they have to make front end changes, use css because they are comfortable with it.

I have to convert the css to scss every time manually or else I will overwrite their changes. Is there a way to update my scss file to pull in css changes automatically?

My IDE is PhpStorm (if that helps anybody)
SASS version 3.4.24

答:
I don't see a plugin for PHPStorm to do that; you might have to make one yourself. But even if you do, the SCSS it'd produce probably wouldn't be much better than the CSS you already have. It's silly to convert to SCSS only to compile back to CSS. The whole point of SCSS is so that you don't have to write CSS.

You could convert the CSS to SCSS with sites like this one. Again, results will probably not be much better than if you just kept it CSS.

My solution would be to split the CSS file. One part would be for the stubborn devs, while the other one is the CSS compiled from the SCSS you like to use. So, they can work in CSS, and you can work in SCSS.

You probably need a workplace solution before a technical one.

Title: How to convert CSS to SCSS every time?

ContentLicense: CC BY-SA 4.0


问:
Scraping table within iframe using R rvest library
I am decent with R's rvest library for scraping websites, but am struggling with something new. From this webpage - http://www.naia.org/ViewArticle.dbml?ATCLID=205323044 - I am trying to scrape the main table of colleges.

Here is what my code looks like currently:

```<code>NAIA_url = "http://www.naia.org/ViewArticle.dbml?ATCLID=205323044"
NAIA_page = read_html(NAIA_url)

tables = html_table(html_nodes(NAIA_page, 'table'))
# tables returns a length-2 list, however neither of these tables are the table I desire.

# grab the correct iframe node
iframe = html_nodes(NAIA_page, "iframe")[3]
</code>```

However I'm struggling past this. (1) for some reason calling html_nodes isn't grabbing the table I want. (2) and I'm not sure if I should instead grab the iframe and then try to grab the table from within it.

Any help appreciated!

答:
If the embedded iframe is html, you can grab the iframe source and get your desired table from there.

library(rvest)
#> Loading required package: xml2
library(magrittr)
"http://www.naia.org/ViewArticle.dbml?ATCLID=205323044" %>%
  read_html() %>%
  html_nodes("iframe") %>%
  extract(3) %>%
  html_attr("src") %>%
  read_html() %>%
  html_node("#searchResultsTable") %>%
  html_table() %>%
  head()
#>                                   College or University       City, State
#> 1                   Central Christian College ATHLETICS     McPherson, KS
#> 2 +                   Crowley's Ridge College ATHLETICS     Paragould, AR
#> 3                       Edward Waters College ATHLETICS  Jacksonville, Fl
#> 4                 Fisher College ADMISSIONS | ATHLETICS        Boston, MA
#> 5       Georgia Gwinnett College ADMISSIONS | ATHLETICS Lawrenceville, GA
#> 6   Lincoln Christian University ADMISSIONS | ATHLETICS       Lincoln, IL
#>   Conference Enrollment
#> 1     A.I.I.        259
#> 2     A.I.I.          0
#> 3     A.I.I.        805
#> 4     A.I.I.        600
#> 5     A.I.I.      9,720
#> 6     A.I.I.      1,060
```

Body:
I am decent with R's rvest library for scraping websites, but am struggling with something new. From this webpage - http://www.naia.org/ViewArticle.dbml?ATCLID=205323044 - I am trying to scrape the main table of colleges.

Here is what my code looks like currently:

NAIA_url = "http://www.naia.org/ViewArticle.dbml?ATCLID=205323044"
NAIA_page = read_html(NAIA_url)

tables = html_table(html_nodes(NAIA_page, 'table'))
# tables returns a length-2 list, however neither of these tables are the table I desire.

# grab the correct iframe node
iframe = html_nodes(NAIA_page, "iframe")[3]

However I'm struggling past this. (1) for some reason calling html_nodes isn't grabbing the table I want. (2) and I'm not sure if I should instead grab the iframe and then try to grab the table from within it.

Any help appreciated!


问:
How to open view controller when popup is open - swift 3
I'm using the PopupDialog library and have a button that when tapped loads a popup as shown in the code below:

```<code>// Create the dialog
let popup_around_me = AroundMePopUpViewController(nibName: "popup_around_me", bundle: nil)
popup_around_me.gh = self.getJobByLatitude(latitude: marker.position.latitude)
let popup = PopupDialog(viewController: popup_around_me, buttonAlignment: .horizontal, transitionStyle: .bounceDown, gestureDismissal: true)

present(popup, animated: true, completion: nil)
//print("marker.position.latitude: \(marker.position.latitude)")
</code>```

Within my popup there are two buttons that open controllers.

Because I'm using a navigation bar, I think I should first close the popup and then open my controller. Without doing so my navigation bar is not loaded.

But I don't know whether this is the correct way to do it.
If it's ok, how can I do(close popup and open controller)?

my button function:

```<code> func cliclOnContent(tapGestureRecognizer: UITapGestureRecognizer)
    {
        print("job id: \(self.gh.id)")

//below codes not load my navigation.
//        let vc = self.storyboard!.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
//        vc.job_id = self.gh.id
//        self.navigationController?.pushViewController(vc, animated: true)

       // let storyboard = UIStoryboard(name: "Main", bundle: nil)
//        let controller = storyboard?.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
//        controller.job_id = self.gh.id
//        self.present(controller, animated: true, completion: nil)

    }
</code>```

答:
I'm not familiar with the lifecycle of the above mentioned PopupDialog, but if it works like the UIAlertController it will dismiss automatically when one of the button actions are completed.

It looks like you are using the custom PopupDialog version. You should implement your buttons and button actions similar to this:

```<code>    func showCustomDialog(animated: Bool = true) {

        // Create a custom view controller
        let popup_around_me = AroundMePopUpViewController(nibName: "popup_around_me", bundle: nil)

        let popup_around_me = AroundMePopUpViewController(nibName: "popup_around_me", bundle: nil)
        popup_around_me.gh = self.getJobByLatitude(latitude: marker.position.latitude)
        // Create the dialog
        let popup = PopupDialog(viewController: popup_around_me, buttonAlignment: .horizontal, transitionStyle: .bounceDown, gestureDismissal: true)

        // Create first button
        let buttonOne = CancelButton(title: "CANCEL", height: 60) {
            // Do what you want when you cancel
        }

        // Create second button
        let buttonTwo = DefaultButton(title: "Open VC", height: 60) {
            self.gotoMyOtherViewController()
        }

        // Add buttons to dialog
        popup.addButtons([buttonOne, buttonTwo])

        // Present dialog
        present(popup, animated: true, completion: nil)
    }
}
</code>```

Notice the call to self.gotoMyOtherViewController() within the "Open VC" button action this is where you would open the other VC since you are using navigation bar in stead of segue

```<code>func gotoMyOtherViewController(){
    let vc = self.storyboard!.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
    vc.job_id = self.gh.id
    navigationController?.pushViewController(vc, animated: true)
}
</code>```

Body:
I'm using the PopupDialog library and have a button that when tapped loads a popup as shown in the code below:

// Create the dialog
let popup_around_me = AroundMePopUpViewController(nibName: "popup_around_me", bundle: nil)
popup_around_me.gh = self.getJobByLatitude(latitude: marker.position.latitude)
let popup = PopupDialog(viewController: popup_around_me, buttonAlignment: .horizontal, transitionStyle: .bounceDown, gestureDismissal: true)

present(popup, animated: true, completion: nil)
//print("marker.position.latitude: \(marker.position.latitude)")

Within my popup there are two buttons that open controllers.

Because I'm using a navigation bar, I think I should first close the popup and then open my controller. Without doing so my navigation bar is not loaded.

But I don't know whether this is the correct way to do it.
If it's ok, how can I do(close popup and open controller)?

my button function:

 func cliclOnContent(tapGestureRecognizer: UITapGestureRecognizer)
    {
        print("job id: \(self.gh.id)")

//below codes not load my navigation.
//        let vc = self.storyboard!.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
//        vc.job_id = self.gh.id
//        self.navigationController?.pushViewController(vc, animated: true)

       // let storyboard = UIStoryboard(name: "Main", bundle: nil)
//        let controller = storyboard?.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
//        controller.job_id = self.gh.id
//        self.present(controller, animated: true, completion: nil)

    }

Body:
I'm not familiar with the lifecycle of the above mentioned PopupDialog, but if it works like the UIAlertController it will dismiss automatically when one of the button actions are completed.

It looks like you are using the custom PopupDialog version. You should implement your buttons and button actions similar to this:

    func showCustomDialog(animated: Bool = true) {

        // Create a custom view controller
        let popup_around_me = AroundMePopUpViewController(nibName: "popup_around_me", bundle: nil)

        let popup_around_me = AroundMePopUpViewController(nibName: "popup_around_me", bundle: nil)
        popup_around_me.gh = self.getJobByLatitude(latitude: marker.position.latitude)
        // Create the dialog
        let popup = PopupDialog(viewController: popup_around_me, buttonAlignment: .horizontal, transitionStyle: .bounceDown, gestureDismissal: true)

        // Create first button
        let buttonOne = CancelButton(title: "CANCEL", height: 60) {
            // Do what you want when you cancel
        }

        // Create second button
        let buttonTwo = DefaultButton(title: "Open VC", height: 60) {
            self.gotoMyOtherViewController()
        }

        // Add buttons to dialog
        popup.addButtons([buttonOne, buttonTwo])

        // Present dialog
        present(popup, animated: true, completion: nil)
    }
}

Notice the call to self.gotoMyOtherViewController() within the "Open VC" button action this is where you would open the other VC since you are using navigation bar in stead of segue

func gotoMyOtherViewController(){
    let vc = self.storyboard!.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
    vc.job_id = self.gh.id
    navigationController?.pushViewController(vc, animated: true)
}


问:
Difference between InputStream and InputStreamReader in java
I read that InputStream is used for byte based reading it reads 1 byte at a time.
And InputStreamReader is used for character based reading so it reads one character at a time so no need to convert this first to int then read it.

Here is reading using InputStream.

```<code> InputStream input=new FileInputStream("D:/input.txt");

 int c;

 while((c=input.read())!=-1)
 {
    System.out.print((char)c);
 }
</code>```

here is reading using InputStreamReader

```<code>InputStream input=new FileInputStream("D:/input.txt");

reader=new InputStreamReader(input,"UTF-8");

int c;

while((c=reader.read())!=-1)
{
    System.out.print((char)c);
}
</code>```

What is difference between InputStream and InputStreamReader? In both case I have to use a int and then read it and at the end if I want to print that data I have to cast that with "(char)c".

So what is advantage of using InputStreamReader?

答:
In the case of InputStreamReader you can use 'char c' in place of 'int c' and instead of '-1' value, you can use 'null'. Like this :

```<code>InputStream input=new FileInputStream("D:/input.txt");

reader=new InputStreamReader(input,"UTF-8");

char c;

while((c=reader.read())!=null)
{
System.out.print(c);
}
</code>```

Because you are using InputStreamReader which do character based reading.
 So, there is no need to set datatype 'int' and then to cast it using 'char', it is unnecessary.
We need to do this in the case of InputStream as it does byte based reading.

Body:
I read that InputStream is used for byte based reading it reads 1 byte at a time.
And InputStreamReader is used for character based reading so it reads one character at a time so no need to convert this first to int then read it.

Here is reading using InputStream.

 InputStream input=new FileInputStream("D:/input.txt");

 int c;

 while((c=input.read())!=-1)
 {
    System.out.print((char)c);
 }

here is reading using InputStreamReader

InputStream input=new FileInputStream("D:/input.txt");

reader=new InputStreamReader(input,"UTF-8");

int c;

while((c=reader.read())!=-1)
{
    System.out.print((char)c);
}

What is difference between InputStream and InputStreamReader? In both case I have to use a int and then read it and at the end if I want to print that data I have to cast that with "(char)c".

So what is advantage of using InputStreamReader?

Body:
In the case of InputStreamReader you can use 'char c' in place of 'int c' and instead of '-1' value, you can use 'null'. Like this :

InputStream input=new FileInputStream("D:/input.txt");

reader=new InputStreamReader(input,"UTF-8");

char c;

while((c=reader.read())!=null)
{
System.out.print(c);
}

Because you are using InputStreamReader which do character based reading.
 So, there is no need to set datatype 'int' and then to cast it using 'char', it is unnecessary.
We need to do this in the case of InputStream as it does byte based reading.


问:
Null in a strongly typed collection?
I have a strongly typed collection:

```<code>NSMutableArray<SupportClass *> *_items;
</code>```

I need to put a null-like object into it. When you need it with a non-typed collection in ObjC - you use [NSNull null] object:

```<code>[_items replaceObjectAtIndex:index withObject:[NSNull null]];
</code>```

But with the typed one, I'm getting the following warning on that line:

Incompatible pointer types sending 'NSNull * _Nonnull' to parameter of
  type 'SupportClass * _Nonnull'

I understand why the warning arises in this sample with the mix of the typed collection and the [NSNull null] object.

What is the proper way to have a strongly typed collection with complile time type checks and, at the same time, be able to put null-like objects into it?

答:
I have a strongly typed collection:

```<code>NSMutableArray<SupportClass *> *_items;
</code>```

Combining two of your comments:

But [the majority of] programming languages known to me allows to have a typed collection with compile time type checks and at the same time being able to put null objects into it. So I'm just looking for a way to do the same with ObjC.

The trouble you are facing is because you are using a recent addition to Objective-C designed to improve inter-working with Swift, and Swift does not allow you to mix in nulls in this way into your "strongly typed collection".

The Swift model is generally to replace the "reference or null" model you are used to with the "non-null reference and optional" model. In Swift a reference to SomeClassType is non-null, while the type SomeClassType? is shorthand for Optional<SomeClassType>. The Optional type has two cases: .none and .some(v), and Swift allows you to test for .none by comparing to nil.

Swift did not invent this model, (like most parts of the language) it is inherited from others, like the many functional languages which are strong users of such tagged unions.

My question is: Which one is the preferred to deal with the issue from the experienced ObjC developer point of view?

Using NSNull, as you tried. This was the Apple recommended way, the very raison d'être for NSNull, but dates from before Apple introduced the lightweight generics to help bridge between Obj-C and Swift.

How do you use the "reference or null" model in the post lightweight generics world? You I think know most of the alternatives, they include:

Don't. Either don't use the strongly typed collections in Obj-C, or use them following the Swift model.

Use Swift. If you want static strong typing over runtime typing use a language based on it.

Use a subclass. Override every method/property to throw an illegal use of null exception. Add an isNull predicate. Etc.

Use a distinguished object. Don't like inheritance, then just create a unique instance of your class to act as the null case. Add appropriate methods/properties to support it.

Build your own Optional in Obj-C.

Break through the paper wall. Lightweight generics really are a paper-thin layer over the standard collections, just break through it if you must.

Etc.

There is no single "right way" to address your issue. Look at your design, decide whether the "reference of null" model is key, pick a solution that suits your circumstances.

HTH

Title: Null in a strongly typed collection?

Body:
I have a strongly typed collection:

NSMutableArray<SupportClass *> *_items;

I need to put a null-like object into it. When you need it with a non-typed collection in ObjC - you use [NSNull null] object:

[_items replaceObjectAtIndex:index withObject:[NSNull null]];

But with the typed one, I'm getting the following warning on that line:

Incompatible pointer types sending 'NSNull * _Nonnull' to parameter of
  type 'SupportClass * _Nonnull'

I understand why the warning arises in this sample with the mix of the typed collection and the [NSNull null] object.

What is the proper way to have a strongly typed collection with complile time type checks and, at the same time, be able to put null-like objects into it?

Body:
I have a strongly typed collection:

NSMutableArray<SupportClass *> *_items;

Combining two of your comments:

But [the majority of] programming languages known to me allows to have a typed collection with compile time type checks and at the same time being able to put null objects into it. So I'm just looking for a way to do the same with ObjC.

The trouble you are facing is because you are using a recent addition to Objective-C designed to improve inter-working with Swift, and Swift does not allow you to mix in nulls in this way into your "strongly typed collection".

The Swift model is generally to replace the "reference or null" model you are used to with the "non-null reference and optional" model. In Swift a reference to SomeClassType is non-null, while the type SomeClassType? is shorthand for Optional<SomeClassType>. The Optional type has two cases: .none and .some(v), and Swift allows you to test for .none by comparing to nil.

Swift did not invent this model, (like most parts of the language) it is inherited from others, like the many functional languages which are strong users of such tagged unions.

My question is: Which one is the preferred to deal with the issue from the experienced ObjC developer point of view?

Using NSNull, as you tried. This was the Apple recommended way, the very raison d'être for NSNull, but dates from before Apple introduced the lightweight generics to help bridge between Obj-C and Swift.

How do you use the "reference or null" model in the post lightweight generics world? You I think know most of the alternatives, they include:

Don't. Either don't use the strongly typed collections in Obj-C, or use them following the Swift model.

Use Swift. If you want static strong typing over runtime typing use a language based on it.

Use a subclass. Override every method/property to throw an illegal use of null exception. Add an isNull predicate. Etc.

Use a distinguished object. Don't like inheritance, then just create a unique instance of your class to act as the null case. Add appropriate methods/properties to support it.

Build your own Optional in Obj-C.

Break through the paper wall. Lightweight generics really are a paper-thin layer over the standard collections, just break through it if you must.

Etc.

There is no single "right way" to address your issue. Look at your design, decide whether the "reference of null" model is key, pick a solution that suits your circumstances.

HTH


问:
Store more data in iov in C++
I am writing a C++ program (see below). My goal is to store data in iov struct. I have allocated buffer of fixed length in constructor. Every time that buffer gets filled, I want to transfer data in iov and allocated new buffer of fixed length. Finally when done with data processing, I want to return iov struct. My intension here is to store all these data into iov so that if it's required in future, I can send data easily. I have written sample code. But it seems it's not working. I got an "Bus error: 10". Can someone help me? </p>

<p>Sample code: </p>

```<code>#include <iostream>
#include <string>
#include <sys/uio.h>
#include <cstdlib>

using namespace std;
#define MAX_LEN 1000
#define MIN_LEN    20

class MyClass
{
    public:
        MyClass();
       ~MyClass();
        void fillData(std::string &data);

    private:
       struct iovec     *iov;
       unsigned int     count;
      unsigned int  len;
      char *buf;
      unsigned int total_len;
      unsigned int tmp_len;
};

MyClass::MyClass()
{
  cout << "Inside constructor" << endl;
   total_len = MIN_LEN;
   buf = (char *)malloc(MAX_LEN);
   if (buf == NULL) {
        cout << "Error: can’t allocate buf" << endl;
        exit(EXIT_FAILURE);
     }
}

MyClass::~MyClass()
{
    free(buf);
}

void MyClass::fillData(std::string &data)
{
    unsigned int d_len, tmp_len, offset;
    d_len = data.size();
    const char* t = data.c_str();
    total_len += d_len;
    tmp_len += d_len;
    if (total_len > MAX_LEN) {

        /* Allocate memory and assign to iov */
        tmp_len = d_len;

     }

    memcpy(buf + offset, t,  d_len);
    /* Adjust offset */
}

int main()
{

  MyClass my_obj;
  int i;
  std::string str = "Hey, welcome to my first class!";
  for (i = 0; i < 10; i++) {
    my_obj.fillData(str);
  }
  return 0;
}
</code>```

答:
Without understanding the intent of your program in detail, it is very clear that you forgot to reserve memory for the iov-objects themselfes.
For example, in your constructor you write iov[0].iov_base = buf, yet iov has not been allocated before.

To overcome this, somewhere in your code, before the first access to iov, you should write something like iov = calloc(100,sizeof(struct iovev)) or a c++ equivalent using new[].

Consider the following program:

```<code>struct myStruct {
  char *buf;
  int len;
};

int main() {

  struct myStruct *myStructPtr;

  myStructPtr->buf = "Herbert";  // Illegal, since myStructPtr is not initialized; So even if "Herbert" is valid, there is no place to store the pointer to literal "Herbert".
  myStructPtr[0].buf = "Herbert"; // Illegal, since myStructPtr is not initialized

  // but:
  struct myStruct *myStructObj = new (struct myStruct);
   myStructObj->buf = "Herbert"; // OK, because myStructObj can store the pointer to literal "Herbert"
   myStructObj->buf = "Something else"; // OK; myStructObj can hold a pointer, so just let it point to a different portion of memory. No need for an extra "new (struct myStruct)" here
}
</code>```

Title: Store more data in iov in C++

Body:
I am writing a C++ program (see below). My goal is to store data in iov struct. I have allocated buffer of fixed length in constructor. Every time that buffer gets filled, I want to transfer data in iov and allocated new buffer of fixed length. Finally when done with data processing, I want to return iov struct. My intension here is to store all these data into iov so that if it's required in future, I can send data easily. I have written sample code. But it seems it's not working. I got an "Bus error: 10". Can someone help me?

Sample code:

#include <iostream>
#include <string>
#include <sys/uio.h>
#include <cstdlib>

using namespace std;
#define MAX_LEN 1000
#define MIN_LEN    20

class MyClass
{
    public:
        MyClass();
       ~MyClass();
        void fillData(std::string &data);

    private:
       struct iovec     *iov;
       unsigned int     count;
      unsigned int  len;
      char *buf;
      unsigned int total_len;
      unsigned int tmp_len;
};

MyClass::MyClass()
{
  cout << "Inside constructor" << endl;
   total_len = MIN_LEN;
   buf = (char *)malloc(MAX_LEN);
   if (buf == NULL) {
        cout << "Error: can’t allocate buf" << endl;
        exit(EXIT_FAILURE);
     }
}

MyClass::~MyClass()
{
    free(buf);
}

void MyClass::fillData(std::string &data)
{
    unsigned int d_len, tmp_len, offset;
    d_len = data.size();
    const char* t = data.c_str();
    total_len += d_len;
    tmp_len += d_len;
    if (total_len > MAX_LEN) {

        /* Allocate memory and assign to iov */
        tmp_len = d_len;

     }

    memcpy(buf + offset, t,  d_len);
    /* Adjust offset */
}

int main()
{

  MyClass my_obj;
  int i;
  std::string str = "Hey, welcome to my first class!";
  for (i = 0; i < 10; i++) {
    my_obj.fillData(str);
  }
  return 0;
}

Body:
Without understanding the intent of your program in detail, it is very clear that you forgot to reserve memory for the iov-objects themselfes.
For example, in your constructor you write iov[0].iov_base = buf, yet iov has not been allocated before.

To overcome this, somewhere in your code, before the first access to iov, you should write something like iov = calloc(100,sizeof(struct iovev)) or a c++ equivalent using new[].

Consider the following program:

struct myStruct {
  char *buf;
  int len;
};

int main() {

  struct myStruct *myStructPtr;

  myStructPtr->buf = "Herbert";  // Illegal, since myStructPtr is not initialized; So even if "Herbert" is valid, there is no place to store the pointer to literal "Herbert".
  myStructPtr[0].buf = "Herbert"; // Illegal, since myStructPtr is not initialized

  // but:
  struct myStruct *myStructObj = new (struct myStruct);
   myStructObj->buf = "Herbert"; // OK, because myStructObj can store the pointer to literal "Herbert"
   myStructObj->buf = "Something else"; // OK; myStructObj can hold a pointer, so just let it point to a different portion of memory. No need for an extra "new (struct myStruct)" here
}


问:
Git adding file having space in name
I am trying to update my file, but I was unable to do so because of file name contains two words

```<code>$ git add 00162808_LirajMaharjan_CP_Design/Class diagram.mdj
</code>```

Error:

```<code>fatal: pathspec '00162808_LirajMaharjan_CP_Design/Class' did not match any files
</code>```

Can I add a file like 'Class diagram/mdj' with spaces in the name?

答:
Try
git add 00162808_LirajMaharjan_CP_Design/Class\ diagram.mdj

Title: Git adding file having space in name

Body:
I am trying to update my file, but I was unable to do so because of file name contains two words

$ git add 00162808_LirajMaharjan_CP_Design/Class diagram.mdj

Error:

fatal: pathspec '00162808_LirajMaharjan_CP_Design/Class' did not match any files

Can I add a file like 'Class diagram/mdj' with spaces in the name?