问:
Keras 2 Deconv2D layer
Trying to follow this implementation of a fully-convolutional densenet in Keras 2.  I updated the function calls for some layers and updated the concatenate layer from

```<code>def transition_up(added, wd=0):
    x = concat(added)
    _, r, c, ch = x.get_shape().as_list()
    return Deconvolution2D(ch, 3, 3, (None,r*2,c*2,ch), init='he_uniform',
                           border_mode='same', subsample=(2,2), W_regularizer=l2(wd))(x)
</code>```

to

```<code>def transition_up(added, wd=0):
    x = concat(added)
    _, r, c, ch = x.get_shape().as_list()
    return Deconv2D(ch, (3, 3), input_shape=(r*2, c*2, ch), padding='same',
                    kernel_initializer='he_uniform', kernel_regularizer=l2(wd)) (x)
</code>```

but an input doesn't double like it should after the down path. Here's the full code to create the model with Keras 2.

```<code>def conv(x, nf, sz, wd, p, stride=1):
    x = Conv2D(nf, (sz, sz), strides=(stride, stride), padding='same',
               kernel_initializer='he_uniform', kernel_regularizer=l2(wd)) (x)
    return dropout(x, p)

def conv_relu_bn(x, nf, sz=3, wd=0, p=0, stride=1):
    return conv(relu_bn(x), nf, sz, wd=wd, p=p, stride=stride)

def dense_block(n, x, growth_rate, p, wd):
    added = []
    for i in range(n):
        b = conv_relu_bn(x, growth_rate, p=p, wd=wd)
        print('x:', x, 'b:', b)
        x = concat([x, b])
        added.append(b)
    return x, added

def transition_dn(x, p, wd):
    return conv_relu_bn(x, x.get_shape().as_list()[-1], sz=1, p=p, wd=wd, stride=2)

def down_path(x, nb_layers, growth_rate, p, wd):
    skips = []
    for i, n in enumerate(nb_layers):
        x, added = dense_block(n, x, growth_rate, p, wd)
        skips.append(x)
        x = transition_dn(x, p=p, wd=wd)
    return skips, added

def transition_up(added, wd=0):
    x = concat(added)
    _, r, c, ch = x.get_shape().as_list()
    return Deconv2D(ch, (3, 3), input_shape=(r*2, c*2, ch), padding='same',
                    kernel_initializer='he_uniform', kernel_regularizer=l2(wd)) (x)

def up_path(added, skips, nb_layers, growth_rate, p, wd):
    for i, n in enumerate(nb_layers):

        x = transition_up(added, wd)
        x = concat([x, skips[i]])
        x, added = dense_block(n, x, growth_rate, p, wd)
    return x

def reverse(x):
    return list(reversed(x))

def create_tiramisu(nb_classes, img_input, nb_dense_block=6, growth_rate=16, nb_filter=48,
                    nb_layers_per_block=5, p=None, wd=0):
    if type(nb_layers_per_block) is list or type(nb_layers_per_block) is tuple:
        nb_layers = list(nb_layers_per_block)
    else:
        nb_layers = [nb_layers_per_block] * nb_dense_block

    x = conv(img_input, nb_filter, 3, wd, 0)
    skips, added = down_path(x, nb_layers, growth_rate, p, wd)
    x = up_path(added, reverse(skips[:-1]), reverse(nb_layers[:-1]), growth_rate, p, wd)
    x = conv(x, nb_classes, 1, wd, 0)
    _, r, c, f = x.get_shape().as_list()
    x = Reshape((-1, nb_classes)) (x)
    return Activation('softmax') (x)

input_shape = (224, 224, 3)
img_input = Input(shape=input_shape)
x = create_tiramisu(12, img_input, nb_layers_per_block=[4, 5, 7, 10, 12, 15], p=0.2, wd=1e-4)
</code>```

This is the stacktrace when the it tries to create the model with Keras 2 syntax. One of the inputs to the concatenate layer doesn't get doubled from (None, 7, 7, 656) when it should be like (None, 14, 14, 656) at the beginning of the upsampling path. This doesn't happen with Keras 1 syntax, which I can also post.

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-133-fb96a61666a1> in <module>()
----> 1 x = create_tiramisu(12, img_input, nb_layers_per_block=[4, 5, 7, 10, 12, 15], p=0.2, wd=1e-4)

<ipython-input-131-f58faf58b799> in create_tiramisu(nb_classes, img_input, nb_dense_block, growth_rate, nb_filter, nb_layers_per_block, p, wd)
     62     print('p', p)
     63     print('wd', wd)
---> 64     x = up_path(added, reverse(skips[:-1]), reverse(nb_layers[:-1]), growth_rate, p, wd)
     65     x = conv(x, nb_classes, 1, wd, 0)
     66     _, r, c, f = x.get_shape().as_list()

<ipython-input-131-f58faf58b799> in up_path(added, skips, nb_layers, growth_rate, p, wd)
     38         print('up path', 'i:', i, 'n:', n)
     39         x = transition_up(added, wd)
---> 40         x = concat([x, skips[i]])
     41         x, added = dense_block(n, x, growth_rate, p, wd)
     42     return x

<ipython-input-130-c6d2942be960> in concat(xs)
      5 def bn(x): return BatchNormalization(axis=-1)(x)
      6 def relu_bn(x): return relu(bn(x))
----> 7 def concat(xs): return concatenate(xs, axis=-1)

/home/clu/anaconda3/lib/python3.6/site-packages/keras/layers/merge.py in concatenate(inputs, axis, **kwargs)
    389         A tensor, the concatenation of the inputs alongside axis `axis`.
    390     """
--> 391     return Concatenate(axis=axis, **kwargs)(inputs)
    392
    393

/home/clu/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py in __call__(self, inputs, **kwargs)
    528                     self.build(input_shapes[0])
    529                 else:
--> 530                     self.build(input_shapes)
    531                 self.built = True
    532

/home/clu/anaconda3/lib/python3.6/site-packages/keras/layers/merge.py in build(self, input_shape)
    158                              'inputs with matching shapes '
    159                              'except for the concat axis. '
--> 160                              'Got inputs shapes: %s' % (input_shape))
    161
    162     def call(self, inputs):

ValueError: `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 7, 7, 240), (None, 14, 14, 656)]
</code>```

答: Use a stride of 2 in the deconvolutional layer.</p>

Title: Keras 2 Deconv2D layer

Body:
Trying to follow this implementation of a fully-convolutional densenet in Keras 2.  I updated the function calls for some layers and updated the concatenate layer from

def transition_up(added, wd=0):
    x = concat(added)
    _, r, c, ch = x.get_shape().as_list()
    return Deconvolution2D(ch, 3, 3, (None,r*2,c*2,ch), init='he_uniform',
                           border_mode='same', subsample=(2,2), W_regularizer=l2(wd))(x)

to

def transition_up(added, wd=0):
    x = concat(added)
    _, r, c, ch = x.get_shape().as_list()
    return Deconv2D(ch, (3, 3), input_shape=(r*2, c*2, ch), padding='same',
                    kernel_initializer='he_uniform', kernel_regularizer=l2(wd)) (x)

but an input doesn't double like it should after the down path. Here's the full code to create the model with Keras 2.

def conv(x, nf, sz, wd, p, stride=1):
    x = Conv2D(nf, (sz, sz), strides=(stride, stride), padding='same',
               kernel_initializer='he_uniform', kernel_regularizer=l2(wd)) (x)
    return dropout(x, p)

def conv_relu_bn(x, nf, sz=3, wd=0, p=0, stride=1):
    return conv(relu_bn(x), nf, sz, wd=wd, p=p, stride=stride)

def dense_block(n, x, growth_rate, p, wd):
    added = []
    for i in range(n):
        b = conv_relu_bn(x, growth_rate, p=p, wd=wd)
        print('x:', x, 'b:', b)
        x = concat([x, b])
        added.append(b)
    return x, added

def transition_dn(x, p, wd):
    return conv_relu_bn(x, x.get_shape().as_list()[-1], sz=1, p=p, wd=wd, stride=2)

def down_path(x, nb_layers, growth_rate, p, wd):
    skips = []
    for i, n in enumerate(nb_layers):
        x, added = dense_block(n, x, growth_rate, p, wd)
        skips.append(x)
        x = transition_dn(x, p=p, wd=wd)
    return skips, added

def transition_up(added, wd=0):
    x = concat(added)
    _, r, c, ch = x.get_shape().as_list()
    return Deconv2D(ch, (3, 3), input_shape=(r*2, c*2, ch), padding='same',
                    kernel_initializer='he_uniform', kernel_regularizer=l2(wd)) (x)

def up_path(added, skips, nb_layers, growth_rate, p, wd):
    for i, n in enumerate(nb_layers):

        x = transition_up(added, wd)
        x = concat([x, skips[i]])
        x, added = dense_block(n, x, growth_rate, p, wd)
    return x

def reverse(x):
    return list(reversed(x))

def create_tiramisu(nb_classes, img_input, nb_dense_block=6, growth_rate=16, nb_filter=48,
                    nb_layers_per_block=5, p=None, wd=0):
    if type(nb_layers_per_block) is list or type(nb_layers_per_block) is tuple:
        nb_layers = list(nb_layers_per_block)
    else:
        nb_layers = [nb_layers_per_block] * nb_dense_block

    x = conv(img_input, nb_filter, 3, wd, 0)
    skips, added = down_path(x, nb_layers, growth_rate, p, wd)
    x = up_path(added, reverse(skips[:-1]), reverse(nb_layers[:-1]), growth_rate, p, wd)
    x = conv(x, nb_classes, 1, wd, 0)
    _, r, c, f = x.get_shape().as_list()
    x = Reshape((-1, nb_classes)) (x)
    return Activation('softmax') (x)

input_shape = (224, 224, 3)
img_input = Input(shape=input_shape)
x = create_tiramisu(12, img_input, nb_layers_per_block=[4, 5, 7, 10, 12, 15], p=0.2, wd=1e-4)

This is the stacktrace when the it tries to create the model with Keras 2 syntax. One of the inputs to the concatenate layer doesn't get doubled from (None, 7, 7, 656) when it should be like (None, 14, 14, 656) at the beginning of the upsampling path. This doesn't happen with Keras 1 syntax, which I can also post.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-133-fb96a61666a1> in <module>()
----> 1 x = create_tiramisu(12, img_input, nb_layers_per_block=[4, 5, 7, 10, 12, 15], p=0.2, wd=1e-4)

<ipython-input-131-f58faf58b799> in create_tiramisu(nb_classes, img_input, nb_dense_block, growth_rate, nb_filter, nb_layers_per_block, p, wd)
     62     print('p', p)
     63     print('wd', wd)
---> 64     x = up_path(added, reverse(skips[:-1]), reverse(nb_layers[:-1]), growth_rate, p, wd)
     65     x = conv(x, nb_classes, 1, wd, 0)
     66     _, r, c, f = x.get_shape().as_list()

<ipython-input-131-f58faf58b799> in up_path(added, skips, nb_layers, growth_rate, p, wd)
     38         print('up path', 'i:', i, 'n:', n)
     39         x = transition_up(added, wd)
---> 40         x = concat([x, skips[i]])
     41         x, added = dense_block(n, x, growth_rate, p, wd)
     42     return x

<ipython-input-130-c6d2942be960> in concat(xs)
      5 def bn(x): return BatchNormalization(axis=-1)(x)
      6 def relu_bn(x): return relu(bn(x))
----> 7 def concat(xs): return concatenate(xs, axis=-1)

/home/clu/anaconda3/lib/python3.6/site-packages/keras/layers/merge.py in concatenate(inputs, axis, **kwargs)
    389         A tensor, the concatenation of the inputs alongside axis `axis`.
    390     """
--> 391     return Concatenate(axis=axis, **kwargs)(inputs)
    392
    393

/home/clu/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py in __call__(self, inputs, **kwargs)
    528                     self.build(input_shapes[0])
    529                 else:
--> 530                     self.build(input_shapes)
    531                 self.built = True
    532

/home/clu/anaconda3/lib/python3.6/site-packages/keras/layers/merge.py in build(self, input_shape)
    158                              'inputs with matching shapes '
    159                              'except for the concat axis. '
--> 160                              'Got inputs shapes: %s' % (input_shape))
    161
    162     def call(self, inputs):

ValueError: `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 7, 7, 240), (None, 14, 14, 656)]


来源: stackexchange

问:
order a facet_grid or facet_wrap grid by modality in ggplot2
I would like to order my facet_plot plot on two parameters at the same time. I have taken a look here and here but I don't understand how to deal with my two axes use and es.type at the same time.

```<code>library(ggplot2)

my.df <- data.frame(site = sample(c("place1","place2"), 20, replace = T), value = sample(1:10,20,replace = T),
                    use = sample(c("medic","pharma","foodS","forage"), 5, replace = T), es.type = sample(c("plante","cereal","sol","sun"), 5, replace = T))
</code>```

so my.df can be like :

```<code>     site value    use es.type
1  place2     5  medic     sol
2  place2     2 forage     sun
3  place2     2  medic  plante
4  place2     8 pharma  plante
5  place2     8  foodS  cereal
6  place1     9  medic     sol
7  place1     6 forage     sun
8  place2    10  medic  plante
9  place1     8 pharma  plante
10 place1    10  foodS  cereal
11 place1     7  medic     sol
12 place1     3 forage     sun
13 place1     5  medic  plante
14 place2     7 pharma  plante
15 place1     2  foodS  cereal
16 place1     9  medic     sol
17 place2     1 forage     sun
18 place1     2  medic  plante
19 place1     8 pharma  plante
20 place2     8  foodS  cereal
</code>```

my plot is

```<code>ggplot(data = my.df)+
  geom_bar(aes(x = site, y = value, fill = site), stat="identity")+
  facet_wrap(use~es.type)+
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())
</code>```

I would like to reorder facet and have the max combination first.

答:
You can try using an interaction eg pasting both variables together.

```<code>library(tidyverse)
# Calculate the maximum on both values
gr <- my.df %>%
  mutate(group=paste(use, es.type, sep="\n")) %>%
  group_by(group) %>%
  summarise(Max=sum(value)) %>%
  arrange(-Max)

# Plot the data, but specifiying the order of the facets via
# the factor levels with respect to the order in `gr`.
my.df %>%
  mutate(group=factor(paste(use, es.type, sep="\n"), levels=gr$group)) %>%
  ggplot()+
  geom_bar(aes(x = site, y = value, fill = site), stat="identity")+
  facet_wrap(~group)+
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())
</code>```

--

In base R you can do before plotting:

```<code>my.df$group <- paste(my.df$use, my.df$es.type, sep="\n")
gr <- aggregate(value ~ group, my.df, sum)
gr <- gr[order(gr$value, decreasing = T), ]
my.df$group <- factor(my.df$group, levels = gr$group)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to order my facet_plot plot on two parameters at the same time. I have taken a look here and here but I don't understand how to deal with my two axes use and es.type at the same time.

library(ggplot2)

my.df <- data.frame(site = sample(c("place1","place2"), 20, replace = T), value = sample(1:10,20,replace = T),
                    use = sample(c("medic","pharma","foodS","forage"), 5, replace = T), es.type = sample(c("plante","cereal","sol","sun"), 5, replace = T))

so my.df can be like :

     site value    use es.type
1  place2     5  medic     sol
2  place2     2 forage     sun
3  place2     2  medic  plante
4  place2     8 pharma  plante
5  place2     8  foodS  cereal
6  place1     9  medic     sol
7  place1     6 forage     sun
8  place2    10  medic  plante
9  place1     8 pharma  plante
10 place1    10  foodS  cereal
11 place1     7  medic     sol
12 place1     3 forage     sun
13 place1     5  medic  plante
14 place2     7 pharma  plante
15 place1     2  foodS  cereal
16 place1     9  medic     sol
17 place2     1 forage     sun
18 place1     2  medic  plante
19 place1     8 pharma  plante
20 place2     8  foodS  cereal

my plot is

ggplot(data = my.df)+
  geom_bar(aes(x = site, y = value, fill = site), stat="identity")+
  facet_wrap(use~es.type)+
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

I would like to reorder facet and have the max combination first.

Body:
You can try using an interaction eg pasting both variables together.

library(tidyverse)
# Calculate the maximum on both values
gr <- my.df %>%
  mutate(group=paste(use, es.type, sep="\n")) %>%
  group_by(group) %>%
  summarise(Max=sum(value)) %>%
  arrange(-Max)

# Plot the data, but specifiying the order of the facets via
# the factor levels with respect to the order in `gr`.
my.df %>%
  mutate(group=factor(paste(use, es.type, sep="\n"), levels=gr$group)) %>%
  ggplot()+
  geom_bar(aes(x = site, y = value, fill = site), stat="identity")+
  facet_wrap(~group)+
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

--

In base R you can do before plotting:

my.df$group <- paste(my.df$use, my.df$es.type, sep="\n")
gr <- aggregate(value ~ group, my.df, sum)
gr <- gr[order(gr$value, decreasing = T), ]
my.df$group <- factor(my.df$group, levels = gr$group)


问:
More efficient Javascript
Looking for another eye on making the following Javascript more efficient.

The following JSON is produced from a Resteasy service:

```<code>var testing = {
   "com:klistret:cmdb:ci:pojo:successful":true,
   "com:klistret:cmdb:ci:pojo:count":1,
   "com:klistret:cmdb:ci:pojo:elements":{
      "com:klistret:cmdb:ci:pojo:id":123,
      "com:klistret:cmdb:ci:pojo:name":"Mars",
      "com:klistret:cmdb:ci:pojo:type":{
        "com:klistret:cmdb:ci:pojo:id":1,
        "com:klistret:cmdb:ci:pojo:name":"Environment"
      },
      "com:klistret:cmdb:ci:pojo:configuration":{
        "@www:w3:org:2001:XMLSchemainstance:type":"Environment",
        "@Watermark":"past",
        "com:klistret:cmdb:ci:commons:Name":"Mars"
      }
    }
 };
</code>```

Extended the Extjs JSONReader to handle key depths higher than 2 in the createAccessor method.  Wondering if there is a way to make the code more efficient?  The function below will be called like function(testing, "com:klistret:cmdb:ci:pojo:configuration.@Watermark") where the com:klistret:cmdb:ci:pojo:elements property is the root.

```<code>createAccessor : function(){
    var re = /[\[\.]/;

    return function(expr) {
        if(Ext.isEmpty(expr)){
            return Ext.emptyFn;
        }

        if(Ext.isFunction(expr)){
            return expr;
        }

        # THIS FUNCTION I WANT TO BE EFFICIENT
        return function(obj){
         while (String(expr).search(re) !== -1) {
 var i = String(expr).search(re);
 var key = expr.substring(0, i);

 if (obj.hasOwnProperty(key)) {
  obj = obj[key];
 }

 expr = expr.substring(i+1, expr.length);
}

            return obj[expr];
        };
    };
}()
</code>```

答:
A basic optimization would be to avoid scanning the string twice with search, which is pretty slow.

The best you could do is replace all the string scanning and substring extraction with a single call to expr.split('.'), which would support accessors of the form aaa.bbb.ccc.ddd and turn them into an array like ['aaa','bbb','ccc','ddd']. The other two characters you seem to support ([ and ]) wouldn't work.

Alternately, you could do an initial match for /[^\].[]+/g over your entire string and keep the matches to obtain a similar array, but this would possibly be slower than the previous solution.

ContentLicense: CC BY-SA 2.5

Title: More efficient Javascript

Body:
Looking for another eye on making the following Javascript more efficient.

The following JSON is produced from a Resteasy service:

var testing = {
   "com:klistret:cmdb:ci:pojo:successful":true,
   "com:klistret:cmdb:ci:pojo:count":1,
   "com:klistret:cmdb:ci:pojo:elements":{
      "com:klistret:cmdb:ci:pojo:id":123,
      "com:klistret:cmdb:ci:pojo:name":"Mars",
      "com:klistret:cmdb:ci:pojo:type":{
        "com:klistret:cmdb:ci:pojo:id":1,
        "com:klistret:cmdb:ci:pojo:name":"Environment"
      },
      "com:klistret:cmdb:ci:pojo:configuration":{
        "@www:w3:org:2001:XMLSchemainstance:type":"Environment",
        "@Watermark":"past",
        "com:klistret:cmdb:ci:commons:Name":"Mars"
      }
    }
 };

Extended the Extjs JSONReader to handle key depths higher than 2 in the createAccessor method.  Wondering if there is a way to make the code more efficient?  The function below will be called like function(testing, "com:klistret:cmdb:ci:pojo:configuration.@Watermark") where the com:klistret:cmdb:ci:pojo:elements property is the root.

createAccessor : function(){
    var re = /[\[\.]/;

    return function(expr) {
        if(Ext.isEmpty(expr)){
            return Ext.emptyFn;
        }

        if(Ext.isFunction(expr)){
            return expr;
        }

        # THIS FUNCTION I WANT TO BE EFFICIENT
        return function(obj){
         while (String(expr).search(re) !== -1) {
 var i = String(expr).search(re);
 var key = expr.substring(0, i);

 if (obj.hasOwnProperty(key)) {
  obj = obj[key];
 }

 expr = expr.substring(i+1, expr.length);
}

            return obj[expr];
        };
    };
}()


问:
How do you access Devise controllers?
Are controllers in devise automatically generated? How do you access them?

I know for views you do
rails generate devise_views.

答:
To define custom controller behavior,

see @ErikTrautman's answer.

But if you're trying to understand what Devise is doing under the hood,

you must inspect the source (specifically, in the project root's app/ directory). @MatheusMoreira provides a link to the source on GitHub, but if you'd rather browse it locally in your own text editor, you can find the install location of the Devise gem with gem which devise.

For instance, to see Devise::SessionsController:

```<code>$ vim $(gem which devise | sed 's|\(.*\)\(/.*\)\{2\}|\1|')/app/controllers/devise/sessions_controller.rb
</code>```

(Or, you could just clone the git repo and poke around that way.)

```<code>$ git clone https://github.com/plataformatec/devise
$ cd devise
$ vim app/controllers/devise/sessions_controller.rb
</code>```

Title: How do you access Devise controllers?

Body:
To define custom controller behavior,

see @ErikTrautman's answer.

But if you're trying to understand what Devise is doing under the hood,

you must inspect the source (specifically, in the project root's app/ directory). @MatheusMoreira provides a link to the source on GitHub, but if you'd rather browse it locally in your own text editor, you can find the install location of the Devise gem with gem which devise.

For instance, to see Devise::SessionsController:

$ vim $(gem which devise | sed 's|\(.*\)\(/.*\)\{2\}|\1|')/app/controllers/devise/sessions_controller.rb

(Or, you could just clone the git repo and poke around that way.)

$ git clone https://github.com/plataformatec/devise
$ cd devise
$ vim app/controllers/devise/sessions_controller.rb


问:
css first child not wokring
I have the following html

.resources .resource:first-child {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="resources">
  <h2 class="text-center">Ресурси</h1>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h3>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h3>
    </div>
</div></code>```

the selector without the first-child works fine. But the first-child selector it's not wrking in my case. Can someone tell me why ?

答:
.resources .resource:first-of-type {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="resources">
  <h2 class="text-center">Ресурси</h2>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h4>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h4>
    </div>
</div></code>```

Title: css first child not wokring

Body:
I have the following html

.resources .resource:first-child {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}

Ресурси

Минерали 3700

Газ 500

the selector without the first-child works fine. But the first-child selector it's not wrking in my case. Can someone tell me why ?

Body:
.resources .resource:first-of-type {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}

<div class="resources">
  <h2 class="text-center">Ресурси</h2>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h4>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h4>
    </div>
</div>


问:
Angular 2 (or 4) object serialization
Recently come across the following conundrum:

Standards

The Typescript documentation suggests creating object definitions with private members having an underscore prefix, allowing getters/setters to utilize the original 'name' of said members, providing indirect public access (as they should).

The Angular documentation recommends otherwise, however does not provide an example of using getters & setters for the private variable in their object definition example.

The Issue

I've been following the Typescript coding standard to the most extent. Take the following class for example:

```<code>public class Foo{
    private _bar:string;

    constructor(){ this._bar='Baz'; }

    get bar():string{return this._bar}
}
</code>```

Using the following code to serialize it into JSON:

```<code>console.log(JSON.stringify(new Foo()));
</code>```

...will produce:

```<code>{
    '_bar': 'Baz'
}
</code>```

Questions

Taking into account these are 'guidelines' and simply recommendations, what would be the Angular-way of handling an object definition, allowing for direct serialization?

In my example, surely the private access modifier shouldn't allow direct access to the value of it? What have I missed in my understanding of using the private access modifier here?

I've done a fair share of reading to other articles and StackOverflow posts regarding different ways of handling serialization, want to deter from the 'how', and rather ask 'why' with regards to the behavior mentioned.

Any feedback would be greatly appreciated! :)

Kind regards

答:
You can customize serialization by implementing toJSON()

```<code>public class Foo{
    private _bar:string;

    constructor(){ this._bar='Baz'; }

    get bar():string{return this._bar}

    toJSON() {
      return {bar: _bar};
    }

    static fromJSON(json) {
      ...
    }
}
</code>```

See also http://choly.ca/post/typescript-json/

Getters and setters are pure TypeScript language feature and entirely unrelated to Angular.

private is only for static analysis in TypeScript. When it's transpiled to JS private won't exist anymore. It becomes a plain old JS object and JSON.stringify treats it like that.

Title: Angular 2 (or 4) object serialization

Body:
Recently come across the following conundrum:

Standards

The Typescript documentation suggests creating object definitions with private members having an underscore prefix, allowing getters/setters to utilize the original 'name' of said members, providing indirect public access (as they should).

The Angular documentation recommends otherwise, however does not provide an example of using getters & setters for the private variable in their object definition example.

The Issue

I've been following the Typescript coding standard to the most extent. Take the following class for example:

public class Foo{
    private _bar:string;

    constructor(){ this._bar='Baz'; }

    get bar():string{return this._bar}
}

Using the following code to serialize it into JSON:

console.log(JSON.stringify(new Foo()));

...will produce:

{
    '_bar': 'Baz'
}

Questions

Taking into account these are 'guidelines' and simply recommendations, what would be the Angular-way of handling an object definition, allowing for direct serialization?

In my example, surely the private access modifier shouldn't allow direct access to the value of it? What have I missed in my understanding of using the private access modifier here?

I've done a fair share of reading to other articles and StackOverflow posts regarding different ways of handling serialization, want to deter from the 'how', and rather ask 'why' with regards to the behavior mentioned.

Any feedback would be greatly appreciated! :)

Kind regards

Body:
You can customize serialization by implementing toJSON()

public class Foo{
    private _bar:string;

    constructor(){ this._bar='Baz'; }

    get bar():string{return this._bar}

    toJSON() {
      return {bar: _bar};
    }

    static fromJSON(json) {
      ...
    }
}

See also http://choly.ca/post/typescript-json/

Getters and setters are pure TypeScript language feature and entirely unrelated to Angular.

private is only for static analysis in TypeScript. When it's transpiled to JS private won't exist anymore. It becomes a plain old JS object and JSON.stringify treats it like that.


问:
Compiling JD2XX for Raspberry Pi
For Openhab2 there is a binding add-on called RFXCOM. The problem however is that this add-on uses JD2XX which is not compatible with the ARM architecture of the Raspberry Pi.

I have found a Github repository with the source that you can use to compile a *.so file: https://github.com/0x6a77/JD2XX

A little change to the Makefile to use the correct Java path (zulu-8-armhf-embedded instead of (oracle-7).

Running sudo make jni creates a *.so file which I copied to /usr/lib (inside the java library path). However I still get the error that the Raspberry Pi can't open the shared library due to it being 32-bit. How can you compile a shared library that works for ARM with the source provided by the Github repository.

Error message:

```<code>java.lang.UnsatisfiedLinkError:
/var/lib/openhab2/tmp/libjd2xx5892592723514582617.so:
/var/lib/openhab2/tmp/libjd2xx5892592723514582617.so: cannot open shared object file:
No such file or directory (Possible cause: can't load IA 32-bit .so on a ARM-bit platform)
</code>```

The Raspberry Pi has a fresh installation of Openhabian.

Link to the issue on Github: https://github.com/openhab/openhab2-addons/issues/2316#issuecomment-304795652

EDIT:

```<code>11:00:52.291 [ERROR] [rnal.discovery.RFXComBridgeDiscovery] - Error occurred during discovery
java.io.IOException: device not found (2)
    at jd2xx.JD2XX.listDevices(Native Method)
    at jd2xx.JD2XX.listDevicesByDescription(JD2XX.java:785)
    at org.openhab.binding.rfxcom.internal.discovery.RFXComBridgeDiscovery.discoverRfxcom(RFXComBridgeDiscovery.java:89)
    at org.openhab.binding.rfxcom.internal.discovery.RFXComBridgeDiscovery.startScan(RFXComBridgeDiscovery.java:66)
    at org.eclipse.smarthome.config.discovery.AbstractDiscoveryService.startScan(AbstractDiscoveryService.java:199)
    at org.eclipse.smarthome.config.discovery.internal.DiscoveryServiceRegistryImpl.startScan(DiscoveryServiceRegistryImpl.java:382)
    at org.eclipse.smarthome.config.discovery.internal.DiscoveryServiceRegistryImpl.startScans(DiscoveryServiceRegistryImpl.java:358)
    at org.eclipse.smarthome.config.discovery.internal.DiscoveryServiceRegistryImpl.startScan(DiscoveryServiceRegistryImpl.java:216)
    at org.eclipse.smarthome.io.rest.core.discovery.DiscoveryResource.scan(DiscoveryResource.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)[:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)[:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498)[:1.8.0_121]
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at com.eclipsesource.jaxrs.publisher.internal.ServletContainerBridge.service(ServletContainerBridge.java:76)[10:com.eclipsesource.jaxrs.publisher:5.3.1.201602281253]
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)[81:org.eclipse.jetty.servlet:9.2.19.v20160908]
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)[81:org.eclipse.jetty.servlet:9.2.19.v20160908]
    at org.ops4j.pax.web.service.jetty.internal.HttpServiceServletHandler.doHandle(HttpServiceServletHandler.java:71)[172:org.ops4j.pax.web.pax-web-jetty:4.3.0]
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)[79:org.eclipse.jetty.security:9.2.19.v20160908]
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.ops4j.pax.web.service.jetty.internal.HttpServiceContext.doHandle(HttpServiceContext.java:287)[172:org.ops4j.pax.web.pax-web-jetty:4.3.0]
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)[81:org.eclipse.jetty.servlet:9.2.19.v20160908]
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.ops4j.pax.web.service.jetty.internal.JettyServerHandlerCollection.handle(JettyServerHandlerCollection.java:80)[172:org.ops4j.pax.web.pax-web-jetty:4.3.0]
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.Server.handle(Server.java:499)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)[72:org.eclipse.jetty.io:9.2.19.v20160908]
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)[83:org.eclipse.jetty.util:9.2.19.v20160908]
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)[83:org.eclipse.jetty.util:9.2.19.v20160908]
    at java.lang.Thread.run(Thread.java:745)[:1.8.0_121]
11:01:02.868 [WARN ] [e.sshd.server.channel.ChannelSession] - Unknown pty opcode value: 42
</code>```

答:
In the JD2XX.java file, you can see the mechanism how to load a dll, so or some other type of library depending on OS.

```<code>static {
    String dataModel = System.getProperty("sun.arch.data.model");
    String osName = System.getProperty("os.name").toLowerCase();;

    StringBuilder lib = new StringBuilder("/jni/");

    if (osName.contains("win"))
        lib.append("win/");
    else if (osName.contains("linux"))
        lib.append("linux/");
    else if (osName.contains("mac"))
        lib.append("mac/");
    else
        throw new UnsatisfiedLinkError("Loading JD2XX JNI: Unsupported operating system ("+osName+")");

    if (dataModel.equals("32"))
        lib.append("x86_32/");
    else if (dataModel.equals("64"))
        lib.append("x86_64/");
    else
        throw new UnsatisfiedLinkError("Loading JD2XX JNI: Unknown runtime data model ("+dataModel+")");

    if (osName.contains("win"))
        lib.append("jd2xx.dll");
    else if (osName.contains("linux"))
        lib.append("libjd2xx.so");
    else if (osName.contains("mac"))
        lib.append("libjd2xx.jnilib");

    try {
        NativeUtils.loadLibraryFromJar(lib.toString());
    } catch (IOException e) {
        throw new UnsatisfiedLinkError(e.getMessage());
    }
}
</code>```

The loadLibraryFromJar method from NativeUtils creates temp directory and copy the right library for OS to temp directory then call the System.load method eventually.
So, I think you should modify this part of source code like the code as follows, if possible.

```<code>static
{
   System.load("/var/lib/openhab2/tmp/libjd2xx5892592723514582617.so");
}
</code>```

or

```<code>static
{
   System.load("/usr/lib/libjd2xx5892592723514582617.so");
}
</code>```

There are several ways to make this job work re-setting the 'java.library.path' order to indicate the /usr/lib directory first then use the code below.

Or you can rename the library name, libjd2xx5892592723514582617.so to libjd2xx.so in the /usr/lib which is usually in the 'LD_LIBRARY_PATH' variable.

then, our code in the JD2XX.java can be used instead,

```<code>static
{
   System.loadLibrary("jd2xx");
}
</code>```

I think it works..

Title: Compiling JD2XX for Raspberry Pi

Body:
For Openhab2 there is a binding add-on called RFXCOM. The problem however is that this add-on uses JD2XX which is not compatible with the ARM architecture of the Raspberry Pi.

I have found a Github repository with the source that you can use to compile a *.so file: https://github.com/0x6a77/JD2XX

A little change to the Makefile to use the correct Java path (zulu-8-armhf-embedded instead of (oracle-7).

Running sudo make jni creates a *.so file which I copied to /usr/lib (inside the java library path). However I still get the error that the Raspberry Pi can't open the shared library due to it being 32-bit. How can you compile a shared library that works for ARM with the source provided by the Github repository.

Error message:

java.lang.UnsatisfiedLinkError:
/var/lib/openhab2/tmp/libjd2xx5892592723514582617.so:
/var/lib/openhab2/tmp/libjd2xx5892592723514582617.so: cannot open shared object file:
No such file or directory (Possible cause: can't load IA 32-bit .so on a ARM-bit platform)

The Raspberry Pi has a fresh installation of Openhabian.

Link to the issue on Github: https://github.com/openhab/openhab2-addons/issues/2316#issuecomment-304795652

EDIT:

11:00:52.291 [ERROR] [rnal.discovery.RFXComBridgeDiscovery] - Error occurred during discovery
java.io.IOException: device not found (2)
    at jd2xx.JD2XX.listDevices(Native Method)
    at jd2xx.JD2XX.listDevicesByDescription(JD2XX.java:785)
    at org.openhab.binding.rfxcom.internal.discovery.RFXComBridgeDiscovery.discoverRfxcom(RFXComBridgeDiscovery.java:89)
    at org.openhab.binding.rfxcom.internal.discovery.RFXComBridgeDiscovery.startScan(RFXComBridgeDiscovery.java:66)
    at org.eclipse.smarthome.config.discovery.AbstractDiscoveryService.startScan(AbstractDiscoveryService.java:199)
    at org.eclipse.smarthome.config.discovery.internal.DiscoveryServiceRegistryImpl.startScan(DiscoveryServiceRegistryImpl.java:382)
    at org.eclipse.smarthome.config.discovery.internal.DiscoveryServiceRegistryImpl.startScans(DiscoveryServiceRegistryImpl.java:358)
    at org.eclipse.smarthome.config.discovery.internal.DiscoveryServiceRegistryImpl.startScan(DiscoveryServiceRegistryImpl.java:216)
    at org.eclipse.smarthome.io.rest.core.discovery.DiscoveryResource.scan(DiscoveryResource.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)[:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)[:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498)[:1.8.0_121]
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
    at com.eclipsesource.jaxrs.publisher.internal.ServletContainerBridge.service(ServletContainerBridge.java:76)[10:com.eclipsesource.jaxrs.publisher:5.3.1.201602281253]
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)[81:org.eclipse.jetty.servlet:9.2.19.v20160908]
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)[81:org.eclipse.jetty.servlet:9.2.19.v20160908]
    at org.ops4j.pax.web.service.jetty.internal.HttpServiceServletHandler.doHandle(HttpServiceServletHandler.java:71)[172:org.ops4j.pax.web.pax-web-jetty:4.3.0]
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)[79:org.eclipse.jetty.security:9.2.19.v20160908]
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.ops4j.pax.web.service.jetty.internal.HttpServiceContext.doHandle(HttpServiceContext.java:287)[172:org.ops4j.pax.web.pax-web-jetty:4.3.0]
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)[81:org.eclipse.jetty.servlet:9.2.19.v20160908]
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.ops4j.pax.web.service.jetty.internal.JettyServerHandlerCollection.handle(JettyServerHandlerCollection.java:80)[172:org.ops4j.pax.web.pax-web-jetty:4.3.0]
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.Server.handle(Server.java:499)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)[80:org.eclipse.jetty.server:9.2.19.v20160908]
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)[72:org.eclipse.jetty.io:9.2.19.v20160908]
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)[83:org.eclipse.jetty.util:9.2.19.v20160908]
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)[83:org.eclipse.jetty.util:9.2.19.v20160908]
    at java.lang.Thread.run(Thread.java:745)[:1.8.0_121]
11:01:02.868 [WARN ] [e.sshd.server.channel.ChannelSession] - Unknown pty opcode value: 42

Body:
In the JD2XX.java file, you can see the mechanism how to load a dll, so or some other type of library depending on OS.

static {
    String dataModel = System.getProperty("sun.arch.data.model");
    String osName = System.getProperty("os.name").toLowerCase();;

    StringBuilder lib = new StringBuilder("/jni/");

    if (osName.contains("win"))
        lib.append("win/");
    else if (osName.contains("linux"))
        lib.append("linux/");
    else if (osName.contains("mac"))
        lib.append("mac/");
    else
        throw new UnsatisfiedLinkError("Loading JD2XX JNI: Unsupported operating system ("+osName+")");

    if (dataModel.equals("32"))
        lib.append("x86_32/");
    else if (dataModel.equals("64"))
        lib.append("x86_64/");
    else
        throw new UnsatisfiedLinkError("Loading JD2XX JNI: Unknown runtime data model ("+dataModel+")");

    if (osName.contains("win"))
        lib.append("jd2xx.dll");
    else if (osName.contains("linux"))
        lib.append("libjd2xx.so");
    else if (osName.contains("mac"))
        lib.append("libjd2xx.jnilib");

    try {
        NativeUtils.loadLibraryFromJar(lib.toString());
    } catch (IOException e) {
        throw new UnsatisfiedLinkError(e.getMessage());
    }
}

The loadLibraryFromJar method from NativeUtils creates temp directory and copy the right library for OS to temp directory then call the System.load method eventually.
So, I think you should modify this part of source code like the code as follows, if possible.

static
{
   System.load("/var/lib/openhab2/tmp/libjd2xx5892592723514582617.so");
}

or

static
{
   System.load("/usr/lib/libjd2xx5892592723514582617.so");
}

There are several ways to make this job work re-setting the 'java.library.path' order to indicate the /usr/lib directory first then use the code below.

Or you can rename the library name, libjd2xx5892592723514582617.so to libjd2xx.so in the /usr/lib which is usually in the 'LD_LIBRARY_PATH' variable.

then, our code in the JD2XX.java can be used instead,

static
{
   System.loadLibrary("jd2xx");
}

I think it works..


问:
How to use recursively to query get node after root one level (details see in the photo attach)?
Category is organized by Tree in the following: When I know (Target1),How do I find (Source3) not root (after root one level
)?
Details see here</p>

答:
Oracle Setup:

```<code>CREATE your_table ( source, target ) AS
  SELECT '0',     '1' FROM DUAL UNION ALL
  SELECT '0',     '2' FROM DUAL UNION ALL
  SELECT '0',     '3' FROM DUAL UNION ALL
  SELECT '1',     '1.1' FROM DUAL UNION ALL
  SELECT '1',     '1.2' FROM DUAL UNION ALL
  SELECT '1',     '1.3' FROM DUAL UNION ALL
  SELECT '2',     '2.1' FROM DUAL UNION ALL
  SELECT '2',     '2.2' FROM DUAL UNION ALL
  SELECT '3',     '3.1' FROM DUAL UNION ALL
  SELECT '1.1',   '1.1.1' FROM DUAL UNION ALL
  SELECT '1.1',   '1.1.2' FROM DUAL UNION ALL
  SELECT '1.1',   '1.1.3' FROM DUAL UNION ALL
  SELECT '1.1.2', '1.1.2.1' FROM DUAL UNION ALL
  SELECT '1.1.2', '1.1.2.2' FROM DUAL UNION ALL
  SELECT '1.1.2', '1.1.2.3' FROM DUAL;
</code>```

Query:

```<code>SELECT CONNECT_BY_ROOT( target ) AS first_child
FROM   your_table
WHERE  target = '1.1.2.2'
START WITH source = '0'
CONNECT BY PRIOR target = source;
</code>```

Output:

```<code>FIRST_CHILD
-----------
1
</code>```

Body:
Oracle Setup:

CREATE your_table ( source, target ) AS
  SELECT '0',     '1' FROM DUAL UNION ALL
  SELECT '0',     '2' FROM DUAL UNION ALL
  SELECT '0',     '3' FROM DUAL UNION ALL
  SELECT '1',     '1.1' FROM DUAL UNION ALL
  SELECT '1',     '1.2' FROM DUAL UNION ALL
  SELECT '1',     '1.3' FROM DUAL UNION ALL
  SELECT '2',     '2.1' FROM DUAL UNION ALL
  SELECT '2',     '2.2' FROM DUAL UNION ALL
  SELECT '3',     '3.1' FROM DUAL UNION ALL
  SELECT '1.1',   '1.1.1' FROM DUAL UNION ALL
  SELECT '1.1',   '1.1.2' FROM DUAL UNION ALL
  SELECT '1.1',   '1.1.3' FROM DUAL UNION ALL
  SELECT '1.1.2', '1.1.2.1' FROM DUAL UNION ALL
  SELECT '1.1.2', '1.1.2.2' FROM DUAL UNION ALL
  SELECT '1.1.2', '1.1.2.3' FROM DUAL;

Query:

SELECT CONNECT_BY_ROOT( target ) AS first_child
FROM   your_table
WHERE  target = '1.1.2.2'
START WITH source = '0'
CONNECT BY PRIOR target = source;

Output:

FIRST_CHILD
-----------
1


问:
Clear Input Field on Invalid Input Entered in Jquery Autocomplete
I am Using devbridge/jQuery-Autocomplete

What am I Doing?

I have Appended This Autocomplete to the Input Field.
As Autocomplete Behaviour It's Allow You to type and Show Some Suggestion according to the Lookup data.

So, User can simply type some letter and they get suggested data according to it.

When User Select anything from that suggested data I save its id for further operations. I save that id in hidden input field.

It Works Fine.

The Problem:

Case 1: 1st Time When user select anything from the list and it's id
  get to the hidden input. That's Work Ok.

But When User Decided To Change it and the New value is not in the
  list then Obyesly I have to clear the hidden input Which I am not Able
  to clear.(this is the problem1)

Case 2: Autocomplete has the option - onInvalidateSelection But
  it's not working for me.

This is the Code:

```<code>$('body').on('focus',".qualification_major_data", function(){

  var qualifications_major_string = [{data: "1", value: "Tom Smith"},
                        {data: "2", value: "Tommy Smith"},
                        {data: "3", value: "add Smith"}];

 $(this).autocomplete({

                lookup: qualifications_major_string,
                appendTo: '.qualification_major_div',
                minChars: 2,
                onSelect: function (suggestion) {

                // On select I am Saving the Id of the Selected Value to the Hidden Input
                     alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                    var selectedValueID = suggestion.data;
                    $(this).closest('.qualification_major_div').find('input[name="qualification_major_id_hidden[]"]').val(selectedValueID);
                },
                onInvalidateSelection: function() {

                    // On Invalid Select or Enter I want to Clear the Hidden Input Value. Which I am not Able to do.
                    // This Part is the Problem
                    $('.qualification_major_div input[name="qualification_major_id_hidden[]"]').val('');
                },
                showNoSuggestionNotice: true,
                noSuggestionNotice: 'Sorry, no matching results'

            });

});
</code>```

This is the HTML Part of It:

```<code> <div class="col-md-4">
    <div class="form-group qualification_major_div">
          <label for="qualification_major" class="control-label">Qualification Major *</label>
          <input type="text" name="qualification_major_id[]" id="qualification_major_id" required class="form-control require qualification_major_data" />
          <input type="hidden" id="qualification_major_id_hidden" name="qualification_major_id_hidden[]">
    </div>
</div>
</code>```

答:
I have tested your code and it works good. The only thing I have changed is $('body').on('focus',".qualification_major_data", function(){

I don't find it useful that you instantiate all array of objects every time you click on the input field. If there's a reason behind it, feel free to leave it like that. If not, then delete that function and replace  $(this).autocomplete({

with

 $('#qualification_major_id').autocomplete({

What's causing your errors (Case1 and Case2)? I know it may sound strange, but it's the actual alert() I would suggest you to use console.log() in future.

I've made you a JSFiddle and left some comments also.

JSFiddle

Body:
I am Using devbridge/jQuery-Autocomplete

What am I Doing?

I have Appended This Autocomplete to the Input Field.
As Autocomplete Behaviour It's Allow You to type and Show Some Suggestion according to the Lookup data.

So, User can simply type some letter and they get suggested data according to it.

When User Select anything from that suggested data I save its id for further operations. I save that id in hidden input field.

It Works Fine.

The Problem:

Case 1: 1st Time When user select anything from the list and it's id
  get to the hidden input. That's Work Ok.

But When User Decided To Change it and the New value is not in the
  list then Obyesly I have to clear the hidden input Which I am not Able
  to clear.(this is the problem1)

Case 2: Autocomplete has the option - onInvalidateSelection But
  it's not working for me.

This is the Code:

$('body').on('focus',".qualification_major_data", function(){

  var qualifications_major_string = [{data: "1", value: "Tom Smith"},
                        {data: "2", value: "Tommy Smith"},
                        {data: "3", value: "add Smith"}];

 $(this).autocomplete({

                lookup: qualifications_major_string,
                appendTo: '.qualification_major_div',
                minChars: 2,
                onSelect: function (suggestion) {

                // On select I am Saving the Id of the Selected Value to the Hidden Input
                     alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                    var selectedValueID = suggestion.data;
                    $(this).closest('.qualification_major_div').find('input[name="qualification_major_id_hidden[]"]').val(selectedValueID);
                },
                onInvalidateSelection: function() {

                    // On Invalid Select or Enter I want to Clear the Hidden Input Value. Which I am not Able to do.
                    // This Part is the Problem
                    $('.qualification_major_div input[name="qualification_major_id_hidden[]"]').val('');
                },
                showNoSuggestionNotice: true,
                noSuggestionNotice: 'Sorry, no matching results'

            });

});

This is the HTML Part of It:

          Qualification Major *
          <input type="text" name="qualification_major_id[]" id="qualification_major_id" required class="form-control require qualification_major_data" />
          <input type="hidden" id="qualification_major_id_hidden" name="qualification_major_id_hidden[]">


问:
VBA Replace Code in Another Module Using VBA Code
I have a line of code in one module:

```<code>City = "Paris"
</code>```

Within a separate module I need to change the name of the city based on what a user selects from a dropdown. I have code that will change the entire line as follows:

```<code>Sub ChangeUserCity()
Call Dictionary.CityLocation
Dim UserChosenCity As String
Dim SL As Long, EL As Long, SC As Long, EC As Long
Dim S As String
Dim Found As Boolean

ComboBoxList = Array(CStr(CityName)) 'This is the name of the combodropdown box with the list of city names.

For Each Ky In ComboBoxList
'On Error Resume Next

UserChosenCity = dict4.Item(Ky)(0) 'This refers to the dictionary that has the list of city names. It grabs the string (the name of the city).

With ActivePresentation.VBProject.VBComponents("Dictionary").CodeModule
SL = 1
SC = 1
EL = -1
EC = -1
Found = .Find("City = " & """" & "Paris" & """", SL, SC, EL, EC, True, False, False)
If Found = True Then
S = .Lines(SL, 1)
S = Replace(S, "City = " & """" & "Paris" & """", "City= " & """" & UserChosenCity & """")
.ReplaceLine SL, S
End If
End With
Next Ky
End Sub
</code>```

The problem with the way this code works is that the city name will not always be "Paris". It could be any string (i.e. any city name). So what I really need the code to do is just replace the city name between the quotes with the UserChosenCity. Any idea on how to accomplish this? Thank you!

答:
Add a combo box and a text box to your slide.

With ComboBox1 and TextBox1 on Slide 1 this code moves the value from the combobox to the the textbox:

```<code>Private Sub ComboBox1_Change()
    Dim oComboBox As ComboBox
    Dim oTextBox As TextBox

    Set oComboBox = ActivePresentation.Slides("Slide1").Shapes("ComboBox1").OLEFormat.Object
    Set oTextBox = ActivePresentation.Slides("Slide1").Shapes("TextBox1").OLEFormat.Object

    oTextBox.Value = oComboBox.Value

    'or

    Slide1.TextBox1.Value = Slide1.ComboBox1.Value

End Sub
</code>```

Note: Powerpoint isn't my forte so there may be a "proper" way to store values in PPT.

You can now retrieve the value from the textbox after the presentation has been saved, closed and re-opened (saying that - the combobox also retained the value when I re-opened it) and use that value in elsewhere in your code.

Body:
I have a line of code in one module:

City = "Paris"

Within a separate module I need to change the name of the city based on what a user selects from a dropdown. I have code that will change the entire line as follows:

Sub ChangeUserCity()
Call Dictionary.CityLocation
Dim UserChosenCity As String
Dim SL As Long, EL As Long, SC As Long, EC As Long
Dim S As String
Dim Found As Boolean

ComboBoxList = Array(CStr(CityName)) 'This is the name of the combodropdown box with the list of city names.

For Each Ky In ComboBoxList
'On Error Resume Next

UserChosenCity = dict4.Item(Ky)(0) 'This refers to the dictionary that has the list of city names. It grabs the string (the name of the city).

With ActivePresentation.VBProject.VBComponents("Dictionary").CodeModule
SL = 1
SC = 1
EL = -1
EC = -1
Found = .Find("City = " & """" & "Paris" & """", SL, SC, EL, EC, True, False, False)
If Found = True Then
S = .Lines(SL, 1)
S = Replace(S, "City = " & """" & "Paris" & """", "City= " & """" & UserChosenCity & """")
.ReplaceLine SL, S
End If
End With
Next Ky
End Sub

The problem with the way this code works is that the city name will not always be "Paris". It could be any string (i.e. any city name). So what I really need the code to do is just replace the city name between the quotes with the UserChosenCity. Any idea on how to accomplish this? Thank you!

Body:
Add a combo box and a text box to your slide.

With ComboBox1 and TextBox1 on Slide 1 this code moves the value from the combobox to the the textbox:

Private Sub ComboBox1_Change()
    Dim oComboBox As ComboBox
    Dim oTextBox As TextBox

    Set oComboBox = ActivePresentation.Slides("Slide1").Shapes("ComboBox1").OLEFormat.Object
    Set oTextBox = ActivePresentation.Slides("Slide1").Shapes("TextBox1").OLEFormat.Object

    oTextBox.Value = oComboBox.Value

    'or

    Slide1.TextBox1.Value = Slide1.ComboBox1.Value

End Sub

Note: Powerpoint isn't my forte so there may be a "proper" way to store values in PPT.

You can now retrieve the value from the textbox after the presentation has been saved, closed and re-opened (saying that - the combobox also retained the value when I re-opened it) and use that value in elsewhere in your code.


问:
Disable a button when the input fields are empty in reactjs
Im new to reactJS. Im wondering why my code below doesnt work. Everything works except disabling my NEXT button when text fields are empty. My expectation is that after i fill out ALL the textboxes, the NEXT button will be enabled.

```<code>class Registration extends React.Component {
constructor (props) {
    super (props);
    this.state = {
        selectedGender: null,
        errors: [],
        initComplete: false
    }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    //this.setState({value: e.target.value})
}

change(e){
    if("" != e.target.value){
        this.button.disabled = false;
    }
    else{
        this.button.disabled = true;
    }
}
render() {
    return (
            <div className="container-fluid">
                <form onSubmit={this._handleSubmit}>
                    <div className="form-group has-danger">
                        <label htmlFor="input-MobileNum">number *</label>
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={()=>{ this._handleInputMobileOnChange; this.change.bind(this)}} defaultValue=""/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Email">Email address *</label>
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Invitation">Invitation code</label>
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>
                    </div>
                    <div className="form-group cta">
       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" ref={(button) => this.button=button}>Next</button>
                    </div>
                </form>
            </div>

    )
}
</code>```

THANKS!!!

I updated my code to this. And i tested it case by case. Only mobile works, the email and invitation code dont work for some reason.

```<code>class Registration extends React.Component {
    constructor (props) {
        super (props);
        this.state = {
            selectedGender: null,
            errors: [],
            initComplete: false
        }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this._handleInputEmailOnChange =
    this._handleInputEmailOnChange.bind(this);
    this._handleInputInvitationOnChange =
    this._handleInputInvitationOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

disable(){
    let disable = true;
    if (this.state.inputMobile || this.state.inputEmail || this.state.inputInvitation) {     //I tried && operator, still only mobile works
        disable = false;
    }
    return disable;
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputMobile: e.target.value})
}

_handleInputEmailOnChange(e){
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputEmail: e.target.value})
}

_handleInputInvitationOnChange(e){
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputInvitation: e.target.value})
}

change(e){
    if("" != e.target.value){
        this.button.disabled = false;
    }
    else{
        this.button.disabled = true;
    }
}
render() {
    return (
            <div className="container-fluid">
                <form onSubmit={this._handleSubmit}>
                    <div className="form-group has-danger">
                        <label htmlFor="input-MobileNum">number *</label>
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={this._handleInputMobileOnChange}} defaultValue=""/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Email">Email address *</label>
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={this._handleInputEmailOnChange}/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Invitation">Invitation code</label>
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={this._handleInputInvitationOnChange}/>
                    </div>
                    <div className="form-group cta">
       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" disabled={this.disable()}>Next</button>
                    </div>
                </form>
            </div>

    )
}
</code>```

Nvm. I was being stupid. The code above works! :)))

答:
You should consider using controlled input elements rather than uncontrolled. This lets react manage the values of your input elements which makes things a bit easier.

First of all start by adding the initial values of each input element to to your constructor. You probably just want empty strings here ("").

Then, add a change event listener for each input element and create a function for each. Each such function should then check what the value for the other elements are, as well as its own, and then enable or disable the button.

Demo:

class Registration extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
        selectedGender: null,
        errors: [],
        initComplete: false,
        buttonIsDisabled: true,
        numberValue: "",
        emailValue: "",
        codeValue: "",
    }
    this.changeNumber = this.changeNumber.bind(this);
    this.changeEmail = this.changeEmail.bind(this)
    this.changeCode = this.changeCode.bind(this);
  }

  changeNumber = (e) => {
    let s = true;
    if(this.state.emailValue.length && this.state.codeValue.length && e.target.value.length) {
      s = false;
    }
    let val = e.target.value;
    //let val = utils.removeNonNumbers(e.target.value);
    this.setState({numberValue: val, buttonIsDisabled: s, errors: []});
  }

  changeEmail = (e) => {
    let s = true;
    if(this.state.numberValue.length && this.state.codeValue.length && e.target.value.length) {
      s = false;
    }
    this.setState({emailValue: e.target.value, buttonIsDisabled: s, errors: []});
  }

  changeCode = (e) => {
    let s = true;
    if(this.state.numberValue.length && this.state.emailValue.length && e.target.value.length) {
      s = false;
    }
    this.setState({codeValue: e.target.value, buttonIsDisabled: s, errors: []});
  }

  render() {
    return (

                <form onSubmit={this._handleSubmit}>

                        number *
                        <input type="tel" className={'form-control ' } id="input-MobileNum" onChange={this.changeNumber} />

                        Email address *
                        <input type="email" className={'form-control '} id="input-Email" onChange={this.changeEmail} />

                        Invitation code
                        <input type="text" className={'form-control '} id="input-Invitation" onChange={this.changeCode} />

                        <button type="submit" className="btn btn-primary" disabled={this.state.buttonIsDisabled} ref={(button) => this.button=button}>Next</button>

                </form>

    )
}}

ReactDOM.render(<Registration />, document.getElementById("myApp"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="myApp"></div></code>```

Body:
Im new to reactJS. Im wondering why my code below doesnt work. Everything works except disabling my NEXT button when text fields are empty. My expectation is that after i fill out ALL the textboxes, the NEXT button will be enabled.

class Registration extends React.Component {
constructor (props) {
    super (props);
    this.state = {
        selectedGender: null,
        errors: [],
        initComplete: false
    }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    //this.setState({value: e.target.value})
}

change(e){
    if("" != e.target.value){
        this.button.disabled = false;
    }
    else{
        this.button.disabled = true;
    }
}
render() {
    return (

                <form onSubmit={this._handleSubmit}>

                        number *
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={()=>{ this._handleInputMobileOnChange; this.change.bind(this)}} defaultValue=""/>

                        Email address *
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>

                        Invitation code
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>

       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" ref={(button) => this.button=button}>Next</button>

                </form>

    )
}

THANKS!!!

I updated my code to this. And i tested it case by case. Only mobile works, the email and invitation code dont work for some reason.

class Registration extends React.Component {
    constructor (props) {
        super (props);
        this.state = {
            selectedGender: null,
            errors: [],
            initComplete: false
        }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this._handleInputEmailOnChange =
    this._handleInputEmailOnChange.bind(this);
    this._handleInputInvitationOnChange =
    this._handleInputInvitationOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

disable(){
    let disable = true;
    if (this.state.inputMobile || this.state.inputEmail || this.state.inputInvitation) {     //I tried && operator, still only mobile works
        disable = false;
    }
    return disable;
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputMobile: e.target.value})
}

_handleInputEmailOnChange(e){
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputEmail: e.target.value})
}

_handleInputInvitationOnChange(e){
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputInvitation: e.target.value})
}

change(e){
    if("" != e.target.value){
        this.button.disabled = false;
    }
    else{
        this.button.disabled = true;
    }
}
render() {
    return (

                <form onSubmit={this._handleSubmit}>

                        number *
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={this._handleInputMobileOnChange}} defaultValue=""/>

                        Email address *
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={this._handleInputEmailOnChange}/>

                        Invitation code
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={this._handleInputInvitationOnChange}/>

       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" disabled={this.disable()}>Next</button>

                </form>

    )
}

Nvm. I was being stupid. The code above works! :)))

Body:
You should consider using controlled input elements rather than uncontrolled. This lets react manage the values of your input elements which makes things a bit easier.

First of all start by adding the initial values of each input element to to your constructor. You probably just want empty strings here ("").

Then, add a change event listener for each input element and create a function for each. Each such function should then check what the value for the other elements are, as well as its own, and then enable or disable the button.

Demo:

class Registration extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
        selectedGender: null,
        errors: [],
        initComplete: false,
        buttonIsDisabled: true,
        numberValue: "",
        emailValue: "",
        codeValue: "",
    }
    this.changeNumber = this.changeNumber.bind(this);
    this.changeEmail = this.changeEmail.bind(this)
    this.changeCode = this.changeCode.bind(this);
  }

  changeNumber = (e) => {
    let s = true;
    if(this.state.emailValue.length && this.state.codeValue.length && e.target.value.length) {
      s = false;
    }
    let val = e.target.value;
    //let val = utils.removeNonNumbers(e.target.value);
    this.setState({numberValue: val, buttonIsDisabled: s, errors: []});
  }

  changeEmail = (e) => {
    let s = true;
    if(this.state.numberValue.length && this.state.codeValue.length && e.target.value.length) {
      s = false;
    }
    this.setState({emailValue: e.target.value, buttonIsDisabled: s, errors: []});
  }

  changeCode = (e) => {
    let s = true;
    if(this.state.numberValue.length && this.state.emailValue.length && e.target.value.length) {
      s = false;
    }
    this.setState({codeValue: e.target.value, buttonIsDisabled: s, errors: []});
  }

  render() {
    return (
            <div className="container-fluid">
                <form onSubmit={this._handleSubmit}>
                    <div className="form-group has-danger">
                        <label htmlFor="input-MobileNum">number *</label>
                        <input type="tel" className={'form-control ' } id="input-MobileNum" onChange={this.changeNumber} />
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Email">Email address *</label>
                        <input type="email" className={'form-control '} id="input-Email" onChange={this.changeEmail} />
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Invitation">Invitation code</label>
                        <input type="text" className={'form-control '} id="input-Invitation" onChange={this.changeCode} />
                    </div>
                    <div className="form-group cta">
                        <button type="submit" className="btn btn-primary" disabled={this.state.buttonIsDisabled} ref={(button) => this.button=button}>Next</button>
                    </div>
                </form>
            </div>

    )
}}

ReactDOM.render(<Registration />, document.getElementById("myApp"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="myApp"></div>


问:
Entrust package and displaying roles expecting array but receives object
Recently I've started to learn Larave but from version 4.2. I've followed other users from SO advice to dump v4.2 and start with 5.4. So I did this.

I've installed laravel 5.4.* and Entrust package and trying to build simple ACL cms.

Everything is fine so far but when I try to Edit some role I've got error

in_array() expects parameter 2 to be array, object given

The problem is in the blade here:

```<code>@foreach($permission as $value)
    <label>{{ Form::checkbox('permission[]', $value->id, in_array($value->id, $rolePermissions) ? true : false, array('class' => 'name')) }}
    {{ $value->display_name }}</label>
    <br/>
@endforeach
</code>```

This is the Controller function

```<code> public function edit($id)
 {
     $role = Role::find($id);
     $permission = Permission::get();
     $rolePermissions = DB::table("permission_role")
                          ->where("permission_role.role_id",$id)
                          ->pluck('permission_role.permission_id','permission_role.permission_id');

     return view('roles.edit',compact('role','permission','rolePermissions'));
 }
</code>```

Generally I know what the error means. It means that the query return collection- object but I can't understand how to fix this.

答:
I guess you want to use ->toArray() on collection object.

Text below is out of the scope of this question.

You can trim your controller a bit.

```<code> public function edit(Role $role) // in route file you want to do Get::route('roles/{role}/edit'...)
 {
     //role should have relation M-M so you can access "permissions" like $role->permissions

     return view('roles.edit')->withRole($role);
 }
</code>```

If you follow all the conventions you should define M-M relationships as follows:

```<code>public function permissions()
{
    return $this->belongsToMany(Permission::class, 'your pivot table', 'role_id', 'permission_id');
}
</code>```

Body:
Recently I've started to learn Larave but from version 4.2. I've followed other users from SO advice to dump v4.2 and start with 5.4. So I did this.

I've installed laravel 5.4.* and Entrust package and trying to build simple ACL cms.

Everything is fine so far but when I try to Edit some role I've got error

in_array() expects parameter 2 to be array, object given

The problem is in the blade here:

@foreach($permission as $value)
    {{ Form::checkbox('permission[]', $value->id, in_array($value->id, $rolePermissions) ? true : false, array('class' => 'name')) }}
    {{ $value->display_name }}

@endforeach

This is the Controller function

 public function edit($id)
 {
     $role = Role::find($id);
     $permission = Permission::get();
     $rolePermissions = DB::table("permission_role")
                          ->where("permission_role.role_id",$id)
                          ->pluck('permission_role.permission_id','permission_role.permission_id');

     return view('roles.edit',compact('role','permission','rolePermissions'));
 }

Generally I know what the error means. It means that the query return collection- object but I can't understand how to fix this.

Body:
I guess you want to use ->toArray() on collection object.

Text below is out of the scope of this question.

You can trim your controller a bit.

 public function edit(Role $role) // in route file you want to do Get::route('roles/{role}/edit'...)
 {
     //role should have relation M-M so you can access "permissions" like $role->permissions

     return view('roles.edit')->withRole($role);
 }

If you follow all the conventions you should define M-M relationships as follows:

public function permissions()
{
    return $this->belongsToMany(Permission::class, 'your pivot table', 'role_id', 'permission_id');
}


问:
bind ng-click to a css class
Can we bind ng-click to a CSS class?

I have loads of s to bind and check if they are clicked then fire the click of the label in it, in order to give a maximum clickable area for touch devices.

I have done something like below.

var myApp = angular.module("myApp", [])
  .controller("myController", ["$scope", "$timeout", function myController($scope, $timeout) {
    $scope.checkRadio = function checkRadio($event) {
      $timeout(function() {
        angular.element($event.target).find("label").trigger('click');
      }, 100);
    };
  }]);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invisible-radio {
  position: absolute;
  display: inline;
  opacity: 0;
  width: 0;
  margin: 0;
  -webkit-appearance: none;
  overflow: hidden;
}

.custom-radio-label {
  display: inline-block;
  position: relative;
  padding-left: 20px;
  vertical-align: text-top;
  line-height: 20px;
  cursor: pointer;
  border-style: solid;
  border-width: 0;
}

.custom-radio-label::before {
  border-color: #7f7f7f;
  border-radius: 50%;
  background-color: #fff;
  border-width: 2px;
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 18px;
  height: 18px;
  border-style: solid;
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
}

.invisible-radio:checked+.custom-radio-label::after {
  background-color: #337ab7;
  border-radius: 50%;
  top: 5px;
  left: 5px;
  content: "";
  width: 12px;
  height: 12px;
  position: absolute;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

      Option 1
      Option 2

        <input id="option1" type="radio" class="invisible-radio" name="option" value="0" ng-model="model.Option" required />

        <input id="option2" type="radio" class="invisible-radio" name="option" value="1" ng-model="model.Option" required />

```
</div>
</div>
</p>

<p>But it seems overkill to go and decorate 100s of <code><td></code>s with <code>ng-click</code> attribute.</p>

<p>I am thinking if it is possible to bind <code>ng-click</code> to a common class that all my <code><td></code>s share.</p>

<p>It is certainly possible to do it with <code>jQuery</code> as below.</p>

```$(".someclassOnMyTD").click($event) {
   $event.target.find("label").click();
}
```

But I am looking for an Angular way here. A directive possibly.

答:
You can do it by using angular.element</p>

```<code>  var cells = angular.element(document.querySelectorAll(".someclassOnMyTD"));
  cells.on('click', function(event){
        // write your code here
        // var labels = angular.element(event.currentTarget).find('label');
  })
</code>```

Title: bind ng-click to a css class

Body:
Can we bind ng-click to a CSS class?

I have loads of s to bind and check if they are clicked then fire the click of the label in it, in order to give a maximum clickable area for touch devices.

I have done something like below.

var myApp = angular.module("myApp", [])
  .controller("myController", ["$scope", "$timeout", function myController($scope, $timeout) {
    $scope.checkRadio = function checkRadio($event) {
      $timeout(function() {
        angular.element($event.target).find("label").trigger('click');
      }, 100);
    };
  }]);

.invisible-radio {
  position: absolute;
  display: inline;
  opacity: 0;
  width: 0;
  margin: 0;
  -webkit-appearance: none;
  overflow: hidden;
}

.custom-radio-label {
  display: inline-block;
  position: relative;
  padding-left: 20px;
  vertical-align: text-top;
  line-height: 20px;
  cursor: pointer;
  border-style: solid;
  border-width: 0;
}

.custom-radio-label::before {
  border-color: #7f7f7f;
  border-radius: 50%;
  background-color: #fff;
  border-width: 2px;
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 18px;
  height: 18px;
  border-style: solid;
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
}

.invisible-radio:checked+.custom-radio-label::after {
  background-color: #337ab7;
  border-radius: 50%;
  top: 5px;
  left: 5px;
  content: "";
  width: 12px;
  height: 12px;
  position: absolute;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

      Option 1
      Option 2

        <input id="option1" type="radio" class="invisible-radio" name="option" value="0" ng-model="model.Option" required />

        <input id="option2" type="radio" class="invisible-radio" name="option" value="1" ng-model="model.Option" required />

But it seems overkill to go and decorate 100s of s with ng-click attribute.

I am thinking if it is possible to bind ng-click to a common class that all my s share.

It is certainly possible to do it with jQuery as below.

$(".someclassOnMyTD").click($event) {
   $event.target.find("label").click();
}

But I am looking for an Angular way here. A directive possibly.

Body:
You can do it by using angular.element

  var cells = angular.element(document.querySelectorAll(".someclassOnMyTD"));
  cells.on('click', function(event){
        // write your code here
        // var labels = angular.element(event.currentTarget).find('label');
  })


问:
VBA: convert xls to csv and save it in a certain path
Please help me.
I'm trying to convert a .xls/.xlsx placed on a certain path on a server (let's say one\test\1.xls) file to .csv (without damageing the date format or any other info) and save it in a fixed path (let's say one\result\1.csv). This process must repeat itself automatically every 24 hours.

Thank you!

答:
So far I only got the code below that only converts to csv and saves it in the same location as the original file.

Also for some unknown reason it converts HALF of the dates to 05/31/2017 for exemple (and the original format is 31.05.2017).

```<code>Sub ConvertXLSToCSV()

    Dim InputPath As String

    Dim PowershellCommand As String

    ' To suppress excel prompts and alert messages while the macro is running.

    Application.DisplayAlerts = False

    Do

        ' Taking the input excel file path which needs to be converted to .csv format.

        InputPath = InputBox("Enter the full path of the input excel file.", "Convert XLS to CSV")

        If Trim(InputPath) <> "" Then

            If Dir(InputPath) = vbNullString Then

                MsgBox "File: '" & InputPath & "' doesn't exists.", vbOKOnly + vbCritical, "Convert XLS to CSV"

            ElseIf Split(Dir(InputPath), ".")(1) = "xlsx" Or Split(Dir(InputPath), ".")(1) = "xls" Then

                InputPath = Trim(InputPath)

                ' Opening the input excel file and saving it in .csv using powershell.

                PowershellCommand = "$ExcelWB = new-object -comobject excel.application" & vbNewLine

                PowershellCommand = PowershellCommand & "$ExcelWB = new-object -comobject excel.application" & vbNewLine

                PowershellCommand = PowershellCommand & "$ExcelWB.Visible = $false" & vbNewLine & "$ExcelWB.DisplayAlerts = $false" & vbNewLine

                PowershellCommand = PowershellCommand & "$Workbook = $ExcelWB.Workbooks.Open('" & InputPath & "')" & vbNewLine

                PowershellCommand = PowershellCommand & "$Workbook.SaveAs('" & Left(InputPath, (InStrRev(InputPath, ".", -1, vbTextCompare) - 1)) & ".csv',6)" & vbNewLine

                PowershellCommand = PowershellCommand & "$Workbook.Close($false)" & vbNewLine

                PowershellCommand = PowershellCommand & "$ExcelWB.quit()" & vbNewLine

                PowershellCommand = "Powershell.exe -command " & PowershellCommand

                Set WshShell = CreateObject("WScript.Shell")

                WshShell.Exec (PowershellCommand)

                Exit Do

            Else:

                MsgBox "Input file is not in excel (.xlsx/.xls) format.", vbOKOnly + vbCritical, "Convert XLS to CSV"

            End If

        ElseIf StrPtr(InputPath) <> 0 Then MsgBox "Please enter the full path of the input excel file.", vbOKOnly + vbExclamation, "Convert XLS to CSV"

        End If

    Loop Until StrPtr(InputPath) = 0

End Sub
</code>```

Body:
So far I only got the code below that only converts to csv and saves it in the same location as the original file.

Also for some unknown reason it converts HALF of the dates to 05/31/2017 for exemple (and the original format is 31.05.2017).

Sub ConvertXLSToCSV()

    Dim InputPath As String

    Dim PowershellCommand As String

    ' To suppress excel prompts and alert messages while the macro is running.

    Application.DisplayAlerts = False

    Do

        ' Taking the input excel file path which needs to be converted to .csv format.

        InputPath = InputBox("Enter the full path of the input excel file.", "Convert XLS to CSV")

        If Trim(InputPath) <> "" Then

            If Dir(InputPath) = vbNullString Then

                MsgBox "File: '" & InputPath & "' doesn't exists.", vbOKOnly + vbCritical, "Convert XLS to CSV"

            ElseIf Split(Dir(InputPath), ".")(1) = "xlsx" Or Split(Dir(InputPath), ".")(1) = "xls" Then

                InputPath = Trim(InputPath)

                ' Opening the input excel file and saving it in .csv using powershell.

                PowershellCommand = "$ExcelWB = new-object -comobject excel.application" & vbNewLine

                PowershellCommand = PowershellCommand & "$ExcelWB = new-object -comobject excel.application" & vbNewLine

                PowershellCommand = PowershellCommand & "$ExcelWB.Visible = $false" & vbNewLine & "$ExcelWB.DisplayAlerts = $false" & vbNewLine

                PowershellCommand = PowershellCommand & "$Workbook = $ExcelWB.Workbooks.Open('" & InputPath & "')" & vbNewLine

                PowershellCommand = PowershellCommand & "$Workbook.SaveAs('" & Left(InputPath, (InStrRev(InputPath, ".", -1, vbTextCompare) - 1)) & ".csv',6)" & vbNewLine

                PowershellCommand = PowershellCommand & "$Workbook.Close($false)" & vbNewLine

                PowershellCommand = PowershellCommand & "$ExcelWB.quit()" & vbNewLine

                PowershellCommand = "Powershell.exe -command " & PowershellCommand

                Set WshShell = CreateObject("WScript.Shell")

                WshShell.Exec (PowershellCommand)

                Exit Do

            Else:

                MsgBox "Input file is not in excel (.xlsx/.xls) format.", vbOKOnly + vbCritical, "Convert XLS to CSV"

            End If

        ElseIf StrPtr(InputPath) <> 0 Then MsgBox "Please enter the full path of the input excel file.", vbOKOnly + vbExclamation, "Convert XLS to CSV"

        End If

    Loop Until StrPtr(InputPath) = 0

End Sub


问:
HtmlAgilityPack doesnt work
I have two windows application by using HtmlAgilityPack .
HtmlAgilityPack doesn't work in my project currently .
It show " The debugger could not locate the source file 'D:\Source\htmlagilitypack.new\Trunk\HtmlAgilityPack\HtmlNodeCollection.cs' ".
Is there any other method to do the same work as HtmlAgilityPack ?
I cant find the problem. I need some help . Thank You</p>

答:
Please try the this...

Visual Studio -> Debug -> Options -> Check both "Enable Just My Code" and "Warn if no user code on lunch (Managed Only)"

Title: HtmlAgilityPack doesnt work


问:
How to input fetch in a function, got Uncaught SyntaxError: Invalid or unexpected token on web browser
I'm new in php query javascript code, I want to make a function for

```<code>while ($rowAnt = mysql_fetch_array($resultQueryAntenna))
            {
                echo "<option value=\'".$rowAnt['Antenna']."\'>".$rowAnt['Antenna']." </option>";
            }
</code>```

so I can use it in many area, but I got this error:

Uncaught SyntaxError: Invalid or unexpected token in the web browser

This is web browser (source) error: web browser(source) error

This is my code :

```<code>`$resultQueryAntenna = mysql_query($queryAntenna) or die(mysql_error()."`[".$queryAntenna."]");

function test1(){
     while ($rowAnt = mysql_fetch_array($resultQueryAntenna))
        {
            echo "<option value=\'".$rowAnt['Antenna']."\'>".$rowAnt['Antenna']." </option>";
        }
}
<script>

$(document).ready(function(){
      var i=1;
      $('#add').click(function(){
           i++;
           $('#dynamic_field').append('<tr id="row'+i+'" valign="middle" style="height:45px;">\
                <td width="10%" style="text-align:right; padding-right:20px;">\
                    <select class="form-control" id="type" name="type" onchange="">\
                      <?php
                            while ($rowType = mysql_fetch_array($resultQueryType))
                            {
                                echo "<option value=\'".$rowType['type_name']."\'>".$rowType['type_name']." </option>";
                            }
                        ?>\
                    </select>\
                </td>\
                <td width="35%">\
                <select class="form-control" id="antenna" name="antenna" onchange="">\
                      <option value="">-- None --</option>\
                      <?php test1();?>\
                </select>\
                </td>\
                .........................................
</code>```

Did I do something wrong? My code inside the function works if I don't put them in a function.

答:
You can't break a string over multiple lines in JavaScript.

You could concatenate them, like this:

```<code>$('#dynamic_field').append('<tr id="row'+i+'" valign="middle" style="height:45px;">'
  + '<td width="10%" style="text-align:right; padding-right:20px;">'
  + ...
</code>```

Or, if you use ECMAScript 6, you can use template strings:

```<code>$('#dynamic_field').append(`<tr id="row'+i+'" valign="middle" style="height:45px;">
  <td width="10%" style="text-align:right; padding-right:20px;">
  ...`
</code>```

Body:
I'm new in php query javascript code, I want to make a function for

while ($rowAnt = mysql_fetch_array($resultQueryAntenna))
            {
                echo "<option value=\'".$rowAnt['Antenna']."\'>".$rowAnt['Antenna']." </option>";
            }

so I can use it in many area, but I got this error:

Uncaught SyntaxError: Invalid or unexpected token in the web browser

This is web browser (source) error: web browser(source) error

This is my code :

`$resultQueryAntenna = mysql_query($queryAntenna) or die(mysql_error()."`[".$queryAntenna."]");

function test1(){
     while ($rowAnt = mysql_fetch_array($resultQueryAntenna))
        {
            echo "<option value=\'".$rowAnt['Antenna']."\'>".$rowAnt['Antenna']." </option>";
        }
}

Body:
You can't break a string over multiple lines in JavaScript.

You could concatenate them, like this:

$('#dynamic_field').append('<tr id="row'+i+'" valign="middle" style="height:45px;">'
  + '<td width="10%" style="text-align:right; padding-right:20px;">'
  + ...

Or, if you use ECMAScript 6, you can use template strings:

$('#dynamic_field').append(`<tr id="row'+i+'" valign="middle" style="height:45px;">
  <td width="10%" style="text-align:right; padding-right:20px;">
  ...`