问:
dropdown Arrow unicode icon static position css small devices
I'm trying to implement an accordion for FAQ. I have problems with the arrow icons in small screens, so each time I press the down arrow it should be switched for the up arrow icon and also located on the same place. But once I click the down arrow the up arrow appears slightly more on the top (on smartphone view). I tried with margin but not success. I would like to know how to keep both icons at the same place each time I switch from one to the other by clicking on it.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight) {
            panel.style.maxHeight = null;
        } else {
            panel.style.maxHeight = panel.scrollHeight + "px";
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button.accordion {

  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
  font-size: 18px;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */

button.accordion.active, button.accordion:hover {
  background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.4s ease-out;
}

button.accordion:after {

  font-family: 'Arial Unicode MS', 'Consolas';
  content: "\2304";

  font-size: 60px !important;
  color: #777;
  float: left;
  margin-left: 5px;
  margin-top: -3vh ;
}

button.accordion.active:after {
  content: "\2303";
  max-height: 1vh;

}</code>```

    <button type="button" class="accordion">First Question</button>

Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto.

    <button type="button" class="accordion">Second Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Third Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fourth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fifth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Sixth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

```

答:
i would set the arrow as a background image then change it depending on the state of the button (active or not), then you can position the image as you like. note only use background-position when its in its original state.</p>

```<code>.accordion{
    background-image: url("down arrow"); //path to image
    background-position: right center; //edit depending on your needs
    }
    .accordion.active{
    background-image: url("up arrow"); //path to image
    }
</code>```

Body:
I'm trying to implement an accordion for FAQ. I have problems with the arrow icons in small screens, so each time I press the down arrow it should be switched for the up arrow icon and also located on the same place. But once I click the down arrow the up arrow appears slightly more on the top (on smartphone view). I tried with margin but not success. I would like to know how to keep both icons at the same place each time I switch from one to the other by clicking on it.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight) {
            panel.style.maxHeight = null;
        } else {
            panel.style.maxHeight = panel.scrollHeight + "px";
        }
    }
}

button.accordion {

  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
  font-size: 18px;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */

button.accordion.active, button.accordion:hover {
  background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.4s ease-out;
}

button.accordion:after {

  font-family: 'Arial Unicode MS', 'Consolas';
  content: "\2304";

  font-size: 60px !important;
  color: #777;
  float: left;
  margin-left: 5px;
  margin-top: -3vh ;
}

button.accordion.active:after {
  content: "\2303";
  max-height: 1vh;

}

    <button type="button" class="accordion">First Question</button>

Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto.

    <button type="button" class="accordion">Second Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Third Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fourth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fifth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Sixth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

Body:
i would set the arrow as a background image then change it depending on the state of the button (active or not), then you can position the image as you like. note only use background-position when its in its original state.

.accordion{
    background-image: url("down arrow"); //path to image
    background-position: right center; //edit depending on your needs
    }
    .accordion.active{
    background-image: url("up arrow"); //path to image
    }


来源: stackexchange

问:
.Swf skips to 3rd frame
I have a 6 frame .swf that is for some reason jumping to the 3rd frame upon loading.
This problem occurs in every browser except IE. I'm using AS2.
This is the actionscript for the first frame:

```<code>stop();

var SKUName = _root.SKUName;
var ProductImage = _root.ProductImage;
var ProductPrice = _root.ProductPrice;

var tbValue:String = String(iSize.text);

if(SKUName != undefined) {
    gotoAndPlay(6);
} else {
}
</code>```

The 6th frame just contains a stop(); action.

Any idea of why this is happening?

Thanks for any help.
Philip

答:
Maybe you need an preloader - Flash will start to play even before it's fully loaded and this can cause problems.

It looks like your project is AS3 so try to add something like this on your second frame (move everything else behind the second frame):

```<code>if (stage.loaderInfo.bytesLoaded < stage.loaderInfo.bytesTotal) {
    this.gotoAndPlay(1);
} else {

}
</code>```

or this will work as well:

```<code>this.loaderInfo.addEventListener(Event.COMPLETE, selfComplete);
</code>```

ContentLicense: CC BY-SA 2.5

Title: .Swf skips to 3rd frame

Body:
I have a 6 frame .swf that is for some reason jumping to the 3rd frame upon loading.
This problem occurs in every browser except IE. I'm using AS2.
This is the actionscript for the first frame:

stop();

var SKUName = _root.SKUName;
var ProductImage = _root.ProductImage;
var ProductPrice = _root.ProductPrice;

var tbValue:String = String(iSize.text);

if(SKUName != undefined) {
    gotoAndPlay(6);
} else {
}

The 6th frame just contains a stop(); action.

Any idea of why this is happening?

Thanks for any help.
Philip

Body:
Maybe you need an preloader - Flash will start to play even before it's fully loaded and this can cause problems.

It looks like your project is AS3 so try to add something like this on your second frame (move everything else behind the second frame):

if (stage.loaderInfo.bytesLoaded < stage.loaderInfo.bytesTotal) {
    this.gotoAndPlay(1);
} else {

}

or this will work as well:

this.loaderInfo.addEventListener(Event.COMPLETE, selfComplete);


问:
Concatenate Layer Errors
I am using keras 2.02 and tensorflow 1.3 to build a convolution net with multiple sizes of filters. The code is shown below.

```<code>flts=100
kernel_sizes=[2,3,4]
submodels = []
for kw in kernel_sizes:    # kernel sizes
    submodel = Sequential()
    submodel.add(embedding_layer)
    submodel.add(Dropout(0.2))
    submodel.add(Conv1D(filters=flts,
                        kernel_size=kw,
                        padding='same',
                        activation='relu'))
    submodel.add(MaxPooling1D(pool_size=kw))
    submodels.append(submodel)

big_model = Sequential()
#concat = Concatenate(axis=1)     #line B
#big_model.add(concat(submodels)) #line C
big_model.add(Merge(submodels, mode="concat", concat_axis=1))  #line A
big_model.add(LSTM(units=100, return_sequences=True))
big_model.add(GlobalMaxPooling1D())
#big_model.add(Dropout(0.2))
big_model.add(Dense(2, activation='softmax'))
big_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
</code>```

When using the deprecated code as on line A, it works ok. But when this is replaced by lines B,C, an error is generated as below:

```<code>--> 141     big_model.add(concat(submodels))
        big_model.add = <bound method Sequential.add of <keras.models.Sequential object>>
        concat = <keras.layers.merge.Concatenate object>
        submodels = [<keras.models.Sequential object>, <keras.models.Sequential object>, <keras.models.Sequential object>]
    142     big_model.add(LSTM(units=100, return_sequences=True))
    143     big_model.add(GlobalMaxPooling1D())
    144     #big_model.add(Dropout(0.2))
    145     big_model.add(Dense(2, activation='softmax'))

........

/home/zqz/Programs/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in int_shape(x=<keras.models.Sequential object>)
    404         (2, 2)
    405     ```
    406     """
    407     if hasattr(x, '_keras_shape'):
    408         return x._keras_shape
--> 409     shape = x.get_shape()
        shape = undefined
        x.get_shape = undefined
    410     try:
    411         return tuple([i.__int__() for i in shape])
    412     except ValueError:
    413         return None

AttributeError: 'Sequential' object has no attribute 'get_shape'
___________________________________________________________________
```

I don't know what I should do to fix this?

Thanks in advance

ContentLicense: CC BY-SA 3.0

Title: Concatenate Layer Errors

Body:
I am using keras 2.02 and tensorflow 1.3 to build a convolution net with multiple sizes of filters. The code is shown below.

flts=100
kernel_sizes=[2,3,4]
submodels = []
for kw in kernel_sizes:    # kernel sizes
    submodel = Sequential()
    submodel.add(embedding_layer)
    submodel.add(Dropout(0.2))
    submodel.add(Conv1D(filters=flts,
                        kernel_size=kw,
                        padding='same',
                        activation='relu'))
    submodel.add(MaxPooling1D(pool_size=kw))
    submodels.append(submodel)

big_model = Sequential()
#concat = Concatenate(axis=1)     #line B
#big_model.add(concat(submodels)) #line C
big_model.add(Merge(submodels, mode="concat", concat_axis=1))  #line A
big_model.add(LSTM(units=100, return_sequences=True))
big_model.add(GlobalMaxPooling1D())
#big_model.add(Dropout(0.2))
big_model.add(Dense(2, activation='softmax'))
big_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

When using the deprecated code as on line A, it works ok. But when this is replaced by lines B,C, an error is generated as below:

--> 141     big_model.add(concat(submodels))
        big_model.add = <bound method Sequential.add of <keras.models.Sequential object>>
        concat = <keras.layers.merge.Concatenate object>
        submodels = [<keras.models.Sequential object>, <keras.models.Sequential object>, <keras.models.Sequential object>]
    142     big_model.add(LSTM(units=100, return_sequences=True))
    143     big_model.add(GlobalMaxPooling1D())
    144     #big_model.add(Dropout(0.2))
    145     big_model.add(Dense(2, activation='softmax'))

........

/home/zqz/Programs/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in int_shape(x=<keras.models.Sequential object>)
    404         (2, 2)
    405     ```
    406     """
    407     if hasattr(x, '_keras_shape'):
    408         return x._keras_shape
--> 409     shape = x.get_shape()
        shape = undefined
        x.get_shape = undefined
    410     try:
    411         return tuple([i.__int__() for i in shape])
    412     except ValueError:
    413         return None

AttributeError: 'Sequential' object has no attribute 'get_shape'
___________________________________________________________________

I don't know what I should do to fix this?

Thanks in advance

Body:
I'll suggest using the functional API when your model contains branches. The Concatenate layer takes a list of tensors as its input. In this case, the list should contain the output tensors of the submodels.

submodel_outputs = [model.output for model in submodels]
x = Concatenate(axis=1)(submodel_outputs)

x = LSTM(units=100, return_sequences=True)(x)
x = GlobalMaxPooling1D()(x)
x = Dropout(0.2)(x)
x = Dense(2, activation='softmax')(x)

big_model = Model(inputs=embedding_layer.input, outputs=x)
big_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
big_model.summary()

__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
embedding_1_input (InputLayer)  (None, None)         0
__________________________________________________________________________________________________
embedding_1 (Embedding)         (None, None, 64)     64000       embedding_1_input[0][0]
__________________________________________________________________________________________________
dropout_3 (Dropout)             (None, None, 64)     0           embedding_1[0][0]
__________________________________________________________________________________________________
dropout_4 (Dropout)             (None, None, 64)     0           embedding_1[0][0]
__________________________________________________________________________________________________
dropout_5 (Dropout)             (None, None, 64)     0           embedding_1[0][0]
__________________________________________________________________________________________________
conv1d_4 (Conv1D)               (None, None, 100)    12900       dropout_3[0][0]
__________________________________________________________________________________________________
conv1d_5 (Conv1D)               (None, None, 100)    19300       dropout_4[0][0]
__________________________________________________________________________________________________
conv1d_6 (Conv1D)               (None, None, 100)    25700       dropout_5[0][0]
__________________________________________________________________________________________________
max_pooling1d_4 (MaxPooling1D)  (None, None, 100)    0           conv1d_4[0][0]
__________________________________________________________________________________________________
max_pooling1d_5 (MaxPooling1D)  (None, None, 100)    0           conv1d_5[0][0]
__________________________________________________________________________________________________
max_pooling1d_6 (MaxPooling1D)  (None, None, 100)    0           conv1d_6[0][0]
__________________________________________________________________________________________________
concatenate_7 (Concatenate)     (None, None, 100)    0           max_pooling1d_4[0][0]
                                                                 max_pooling1d_5[0][0]
                                                                 max_pooling1d_6[0][0]
__________________________________________________________________________________________________
lstm_4 (LSTM)                   (None, None, 100)    80400       concatenate_7[0][0]
__________________________________________________________________________________________________
global_max_pooling1d_4 (GlobalM (None, 100)          0           lstm_4[0][0]
__________________________________________________________________________________________________
dropout_7 (Dropout)             (None, 100)          0           global_max_pooling1d_4[0][0]
__________________________________________________________________________________________________
dense_4 (Dense)                 (None, 2)            202         dropout_7[0][0]
==================================================================================================
Total params: 202,502
Trainable params: 202,502
Non-trainable params: 0
__________________________________________________________________________________________________

For using Model with the Scikit-Learn API:

class MyKerasClassifier(KerasClassifier):
    def predict(self, x, **kwargs):
        kwargs = self.filter_sk_params(self.model.predict, kwargs)
        proba = self.model.predict(x, **kwargs)
        if proba.shape[-1] > 1:
            classes = proba.argmax(axis=-1)
        else:
            classes = (proba > 0.5).astype('int32')
        return self.classes_[classes]

Originally in KerasClassifier.predict(), the function predict_classes() is called to obtain the predicted classes. You can override this function and compute the classes from the probabilities to avoid the need of predict_classes().


问:
How send json object to rest services from angular?
I try to send the json object to rest services but I get some error like this:

http://localhost:8080/api/v1/cardLimit 400 (Bad Request);

Wrap to JSON

```<code> public class GameLimit implements Serializable {

    private static final long serialVersionUID = 1L;

    private LimitType firstLimit;
    private LimitType secondLimit;

    public LimitType getFirstLimit() {
        return firstLimit;
    }

    public void setFirstLimit(LimitType firstLimit) {
        this.firstLimit = firstLimit;
    }

    public LimitType getSecondLimit() {
        return secondLimit;
    }

    public void setSecondLimit(LimitType secondLimit) {
        this.secondLimit = secondLimit;
    }
}

public class LimitType implements Serializable{

    private static final long serialVersionUID = 1L;

    private BigDecimal limit;
    private String type;
    private String status;

    public BigDecimal getLimit() {
        return limit;
    }

    public void setLimit(BigDecimal limit) {
        this.limit = limit;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
</code>```

Limit request object

```<code>public class LimitReq extends GameLimit {

    private String key;

    public String getKey() {
        return key;
    }
}
</code>```

RestController:

```<code>@RequestMapping(value = "/GameLimit", method = RequestMethod.POST)
    public Response setCardLimit(@RequestBody GameLimitReq request) throws Exception {
        return limitService.updateGameLimit(request);
    }
</code>```

TypeScript client:

```<code>changeLimits(firstLimit: IWidgetLimit, secondLimit: IWidgetLimit, key: string): ng.IPromise<any> {
            return this.$http.post(this.apiPrefix + '/GameLimit', {
                'firstLimit': {
                    limit: firstLimit.limit,
                    type: firstLimit.type,
                    status: firstLimit.status
                },
                'secondLimit': {
                    limit: secondLimit.limit,
                    type: secondLimit.type,
                    status: secondLimit.status,
                },

                key: key
            }).then(function (response: any) {
                return response.data;
            }.bind(this));
        }
</code>```

答:
It's because your json is not being formed properly.
And there are multiple reasons for that

Your Keys are supposed to be strings, and wrapped in quotes. eg: use "type" instead of type.

You have a comma at the end of the line

```<code>status: secondLimit.status,
</code>```

Remove that comma.

After you are done with it, validate a sample output on jsonlint.com or a similar service. It will help you figure out errors.

Body:
I try to send the json object to rest services but I get some error like this:

http://localhost:8080/api/v1/cardLimit 400 (Bad Request);

Wrap to JSON

 public class GameLimit implements Serializable {

    private static final long serialVersionUID = 1L;

    private LimitType firstLimit;
    private LimitType secondLimit;

    public LimitType getFirstLimit() {
        return firstLimit;
    }

    public void setFirstLimit(LimitType firstLimit) {
        this.firstLimit = firstLimit;
    }

    public LimitType getSecondLimit() {
        return secondLimit;
    }

    public void setSecondLimit(LimitType secondLimit) {
        this.secondLimit = secondLimit;
    }
}

public class LimitType implements Serializable{

    private static final long serialVersionUID = 1L;

    private BigDecimal limit;
    private String type;
    private String status;

    public BigDecimal getLimit() {
        return limit;
    }

    public void setLimit(BigDecimal limit) {
        this.limit = limit;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

Limit request object

public class LimitReq extends GameLimit {

    private String key;

    public String getKey() {
        return key;
    }
}

RestController:

@RequestMapping(value = "/GameLimit", method = RequestMethod.POST)
    public Response setCardLimit(@RequestBody GameLimitReq request) throws Exception {
        return limitService.updateGameLimit(request);
    }

TypeScript client:

changeLimits(firstLimit: IWidgetLimit, secondLimit: IWidgetLimit, key: string): ng.IPromise<any> {
            return this.$http.post(this.apiPrefix + '/GameLimit', {
                'firstLimit': {
                    limit: firstLimit.limit,
                    type: firstLimit.type,
                    status: firstLimit.status
                },
                'secondLimit': {
                    limit: secondLimit.limit,
                    type: secondLimit.type,
                    status: secondLimit.status,
                },

                key: key
            }).then(function (response: any) {
                return response.data;
            }.bind(this));
        }

Body:
It's because your json is not being formed properly.
And there are multiple reasons for that

Your Keys are supposed to be strings, and wrapped in quotes. eg: use "type" instead of type.

You have a comma at the end of the line

status: secondLimit.status,

Remove that comma.

After you are done with it, validate a sample output on jsonlint.com or a similar service. It will help you figure out errors.


问:
How to hide php warning in yii2?
My yii2 web application is hosted on shared server.

it is showing php warning - " PHP Core Warning – yii\base\ErrorException
PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20100525/imagick.so' - libMagickWand.so.2:

cannot open shared object file: No such file or directory"
now i want to disable php warning in my yii2 application how to achive that?

答:
This can be achieved by changing two parameters in index.php file.

1) Setting YII_DEBUG to false

```<code>defined('YII_DEBUG') or define('YII_DEBUG', false);
</code>```

2) Setting YII_ENV to prod from dev

```<code>defined('YII_ENV') or define('YII_ENV', 'prod');
</code>```

Title: How to hide php warning in yii2?

Body:
This can be achieved by changing two parameters in index.php file.

1) Setting YII_DEBUG to false

defined('YII_DEBUG') or define('YII_DEBUG', false);

2) Setting YII_ENV to prod from dev

defined('YII_ENV') or define('YII_ENV', 'prod');


问:
Adding image to aframe entity in React
I'm trying to add an image to an Aframe entity component in React. Here's how I'm adding the image as a material on the plane geometry:

```<code><Entity geometry="primitive: plane; width: 30; height: 30"
                material={{src: "url(assets/image2.jpg)"}}
                position="0 -2 0"
                rotation="-90 0 0">
</Entity>
</code>```

However, the image is not displaying. The image loaded properly in raw html, but isn't working with React and JSX.

I'm getting the follow errors in the console:

components:texture:warn $s is not a valid video +1s assets/image2.jpg

[.Offscreen-For-WebGL-0x7fb65d129a00]RENDER WARNING: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering.

答:
The right way to pass the material attribute value  can be

declare it in render() method like this

```<code>let material = {
            shader: 'flat',
            src : './imagepath.jpg'
        };
</code>```

then  in your entity component pass like this

```<code> <Entity  geometry={{primitive: 'sphere', radius: 5000}} material={material}  />
</code>```

If everything is good and even then your image is not displayed, please make sure you have imported these all:-

```<code>import React from 'react';
import 'aframe';
import 'babel-polyfill';
import {Entity} from 'aframe-react';
</code>```

Title: Adding image to aframe entity in React

Body:
I'm trying to add an image to an Aframe entity component in React. Here's how I'm adding the image as a material on the plane geometry:

<Entity geometry="primitive: plane; width: 30; height: 30"
                material={{src: "url(assets/image2.jpg)"}}
                position="0 -2 0"
                rotation="-90 0 0">
</Entity>

However, the image is not displaying. The image loaded properly in raw html, but isn't working with React and JSX.

I'm getting the follow errors in the console:

components:texture:warn $s is not a valid video +1s assets/image2.jpg

[.Offscreen-For-WebGL-0x7fb65d129a00]RENDER WARNING: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering.

Body:
The right way to pass the material attribute value  can be

declare it in render() method like this

let material = {
            shader: 'flat',
            src : './imagepath.jpg'
        };

then  in your entity component pass like this

 <Entity  geometry={{primitive: 'sphere', radius: 5000}} material={material}  />

If everything is good and even then your image is not displayed, please make sure you have imported these all:-

import React from 'react';
import 'aframe';
import 'babel-polyfill';
import {Entity} from 'aframe-react';


问:
Difference between Docker Swarm vs Swarm mode?
What difference between initialization swarm over this commands:

```<code>docker swarm init --advertise-addr <manager-ip>
docker -H <worker-ip> swarm join --token <worker-token>
</code>```

And this one:

```<code>docker run swarm manage <consul-ip>
docker -H <worker-ip> run swarm join --advertise=<worker-ip> <consul-ip>
</code>```

Why we need swarm image?

答:
Docker Swarm (also Swarm classic) is fundamentally different from Swarm Mode. Native Swarm functionality will continue to be supported in Docker 1.12 release, this is done to preserve backward compatibility.

Docker Swram (classic):

Separate from Docker Engine and can run as Container

Needs external KV store like Consul, etcd, Zookeeper

Usage example:

```<code>docker run swarm manage <consul-ip>
docker -H <worker-ip> run swarm join --advertise=<worker-ip> <consul-ip>
</code>```

Swarm Mode (new, preferable):

Integrated inside Docker engine

No need of separate external KV store

Usage example:

```<code>docker swarm init --advertise-addr <manager-ip>
docker -H <worker-ip> swarm join --token <worker-token>
</code>```

Source: Comparing Swarm, Swarmkit and Swarm Mode

Great answer on another question like this one: The relation between “docker/swarm” and “docker/swarmkit”

Body:
What difference between initialization swarm over this commands:

docker swarm init --advertise-addr <manager-ip>
docker -H <worker-ip> swarm join --token <worker-token>

And this one:

docker run swarm manage <consul-ip>
docker -H <worker-ip> run swarm join --advertise=<worker-ip> <consul-ip>

Why we need swarm image?

Body:
Docker Swarm (also Swarm classic) is fundamentally different from Swarm Mode. Native Swarm functionality will continue to be supported in Docker 1.12 release, this is done to preserve backward compatibility.

Docker Swram (classic):

Separate from Docker Engine and can run as Container

Needs external KV store like Consul, etcd, Zookeeper

Usage example:

docker run swarm manage <consul-ip>
docker -H <worker-ip> run swarm join --advertise=<worker-ip> <consul-ip>

Swarm Mode (new, preferable):

Integrated inside Docker engine

No need of separate external KV store

Usage example:

docker swarm init --advertise-addr <manager-ip>
docker -H <worker-ip> swarm join --token <worker-token>

Source: Comparing Swarm, Swarmkit and Swarm Mode

Great answer on another question like this one: The relation between “docker/swarm” and “docker/swarmkit”


问:
How do I write a for loop in C
Why does the following code loop 5000 times instead of the 5 times I expect?</p>

```<code>int height = 5;

for (int height; height > 0; height -= 1){
    printf('Something')  }
}
</code>```

答:
Why do you have to redefine variables in a for loop in C

That may be because of the fact that you want to preserve/use the value of variable after the loop.

In case of

```<code>int height = 5;

for (int h = height; h > 0; h--){
    printf('Something')  }
}
</code>```

height will have value 5. While in case of

```<code>int height = 5;

for (height; height > 0; height--){
    printf('Something')  }
}
</code>```

height will have value zero after the for loop.

Title: How do I write a for loop in C

Body:
Why does the following code loop 5000 times instead of the 5 times I expect?

int height = 5;

for (int height; height > 0; height -= 1){
    printf('Something')  }
}

Body:
Why do you have to redefine variables in a for loop in C

That may be because of the fact that you want to preserve/use the value of variable after the loop.

In case of

int height = 5;

for (int h = height; h > 0; h--){
    printf('Something')  }
}

height will have value 5. While in case of

int height = 5;

for (height; height > 0; height--){
    printf('Something')  }
}

height will have value zero after the for loop.


问:
Return records where 2 columns don't match
I want to find records where two columns don't match. In order to do this I need to divide one of the columns by 100 (as it is in %).

My table:

```<code>|artno|artno2|Quantity_Percent|Quantity_pcs|
|1111 |aaaa  |       28       |    0,28    |
|1111 |bbbb  |        0,65    |    0,017   |
</code>```

Query:

```<code>Select artno, artno2, (Quantity_Percent / 100) as Percent, Quantity_pcs
From Table1
Where artno = '1111'
</code>```

Turns this in to:

```<code>|artno|artno2|     Percent    |Quantity_pcs|
|1111 |aaaa  |        0,28    |    0,28    |
|1111 |bbbb  |        0,0065  |    0,017   |
</code>```

So far so good; but if I want the query to return only the 2nd row where the  Quantity_Percent and Quantity_pcs columns don't match, how do I do that?

Thanks in advance.

SisU

答:
you can use the condition for Quality_Percent and Quality_pcs don't match...
just add the below condition
SELECT * FROM ([YOUR_QUERY]) WHERE Percent!=Quality_pcs

So that your query will be like below

SELECT * FROM (SELECT artno, artno2, (Quantity_Percent / 100) as Percent, Quantity_pcs
FROM Table1
WHERE artno = '1111')
WHERE  Percent != Quality_pcs

Hope this will help you

Body:
I want to find records where two columns don't match. In order to do this I need to divide one of the columns by 100 (as it is in %).

My table:

|artno|artno2|Quantity_Percent|Quantity_pcs|
|1111 |aaaa  |       28       |    0,28    |
|1111 |bbbb  |        0,65    |    0,017   |

Query:

Select artno, artno2, (Quantity_Percent / 100) as Percent, Quantity_pcs
From Table1
Where artno = '1111'

Turns this in to:

|artno|artno2|     Percent    |Quantity_pcs|
|1111 |aaaa  |        0,28    |    0,28    |
|1111 |bbbb  |        0,0065  |    0,017   |

So far so good; but if I want the query to return only the 2nd row where the  Quantity_Percent and Quantity_pcs columns don't match, how do I do that?

Thanks in advance.

SisU


问:
WeakReference not collected in curly brackets?

This fails

```<code>public void testWeak() throws Exception {
    waitGC();
    {
        Sequence a = Sequence.valueOf("123456789");
        assert Sequence.used() == 1;
        a.toString();
    }
    waitGC();
}

private void waitGC() throws InterruptedException {
    Runtime.getRuntime().gc();
    short count = 0;
    while (count < 100 && Sequence.used() > 0) {
        Thread.sleep(10);
        count++;
    }
    assert Sequence.used() == 0: "Not removed!";
}
</code>```

The test fails. Telling Not removed!.

This works:

```<code>public void testAWeak() throws Exception {
    waitGC();
    extracted();
    waitGC();
}
private void extracted() throws ChecksumException {
    Sequence a = Sequence.valueOf("123456789");
    assert Sequence.used() == 1;
    a.toString();
}
private void waitGC() throws InterruptedException {
    Runtime.getRuntime().gc();
    short count = 0;
    while (count < 100 && Sequence.used() > 0) {
        Thread.sleep(10);
        count++;
    }
    assert Sequence.used() == 0: "Not removed!";
}
</code>```

It seems like the curly brackets does not affect the weakness.

Some official resources?

答:
Scope is a compile-time thing. It is not determining the reachability of objects at runtime, only has an indirect influence due to implementation details.

Consider the following variation of your test:

```<code>static boolean WARMUP;
public void testWeak1() throws Exception {
    variant1();
    WARMUP = true;
    for(int i=0; i<10000; i++) variant1();
    WARMUP = false;
    variant1();
}
private void variant1() throws Exception {
    AtomicBoolean track = new AtomicBoolean();
    {
        Trackable a = new Trackable(track);
        a.toString();
    }
    if(!WARMUP) System.out.println("variant1: "
                      +(waitGC(track)? "collected": "not collected"));
}
public void testWeak2() throws Exception {
    variant2();
    WARMUP = true;
    for(int i=0; i<10000; i++) variant2();
    WARMUP = false;
    variant2();
}
private void variant2() throws Exception {
    AtomicBoolean track = new AtomicBoolean();
    {
        Trackable a = new Trackable(track);
        a.toString();
        if(!WARMUP) System.out.println("variant2: "
                      +(waitGC(track)? "collected": "not collected"));
    }
}
static class Trackable {
    final AtomicBoolean backRef;
    public Trackable(AtomicBoolean backRef) {
        this.backRef = backRef;
    }
    @Override
    protected void finalize() throws Throwable {
        backRef.set(true);
    }
}

private boolean waitGC(AtomicBoolean b) throws InterruptedException {
    for(int count = 0; count < 10 && !b.get(); count++) {
        Runtime.getRuntime().gc();
        Thread.sleep(1);
    }
    return b.get();
}
</code>```

on my machine, it prints:

variant1: not collected
variant1: collected
variant2: not collected
variant2: collected
```

<p>If you can’t reproduce it, you may have to raise the number of warmup iterations.</p>

<p>What it demonstrates: whether <code>a</code> is in scope (variant 2) or not (variant 1) doesn’t matter, in either case, the object has not been collected in cold execution, but got collected after a number of warmup iterations, in other words, after the optimizer kicked in.</p>

<hr>

<p>Formally, <code>a</code> is <em>always</em> eligible for garbage collection at the point we’re invoking <code>waitGC()</code>, as it is unused from this point. This is how reachability is defined:</p>

<blockquote>
  <p>A <em>reachable</em> object is any object that can be accessed in any potential continuing computation from any live thread.</p>
</blockquote>

<p>In this example, the object can not be accessed by potential continuing computation, as no such subsequent computation that would access the object exists. However, there is no guaranty that a particular JVM’s garbage collector is always capable of identifying all of those objects at each time. In fact, even a JVM not having a garbage collector at all would still comply to the specification, though perhaps not the intent.</p>

<p>The possibility of code optimizations having an effect on the reachability analysis has also explicitly mentioned in the specification:</p>

<blockquote>
  <p>Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a Java compiler or code generator may choose to set a variable or parameter that will no longer be used to <code>null</code> to cause the storage for such an object to be potentially reclaimable sooner.</p>
</blockquote>

<hr>

<p>So what happens technically?</p>

<p>As said, scope is a compile-time thing. At the bytecode level, leaving the scope defined by the curly braces has no effect. The variable <code>a</code> is out of scope, but its storage within the stack frame still exists holding the reference until overwritten by another variable or until the method completes. The compiler is free to reuse the storage for another variable, but in this example, no such variable exists. So the two variants of the example above actually generate identical bytecode.</p>

<p>In an unoptimized execution, the still existing reference within the stack frame is treated like a reference preventing the object’s collection. In an optimized execution, the reference is only held until its last actual use. Inlining of its fields can allow its collection even earlier, up to the point that it is collected right after construction (or not getting constructed at all, if it hadn’t a <code>finalize()</code> method). The extreme end is finalize() called on strongly reachable object in Java 8…</p>

<p>Things change, when you insert another variable, e.g.</p>

```private void variant1() throws Exception {
    AtomicBoolean track = new AtomicBoolean();
    {
        Trackable a = new Trackable(track);
        a.toString();
    }
    String message = "variant1: ";
    if(!WARMUP) System.out.println(message
                      +(waitGC(track)? "collected": "not collected"));
}
```

<p>Then, the storage of <code>a</code> is reused by <code>message</code> after <code>a</code>’s scope ended (that’s of course, compiler specific) and the object gets collected, even in the unoptimized execution.</p>

<p>Note that the crucial aspect is the actual overwriting of the storage. If you use</p>

```private void variant1() throws Exception {
    AtomicBoolean track = new AtomicBoolean();
    {
        Trackable a = new Trackable(track);
        a.toString();
    }
    if(!WARMUP)
    {
        String message = "variant1: "
                       +(waitGC(track)? "collected": "not collected");
        System.out.println(message);
    }
}
```

The message variable uses the same storage as a, but its assignment only happens after the invocation of waitGC(track), so you get the same unoptimized execution behavior as in the original variant.

By the way, don’t use short for local loop variables. Java always uses int for byte, short, char, and int calculations (as you know, e.g. when trying to write shortVariable = shortVariable + 1;) and requiring it to cut the result value to short (which still happens implicitly when you use shortVariable++), adds an additional operation, so if you thought, using short improved the efficiency, notice that it actually is the opposite.

Body:
This fails

public void testWeak() throws Exception {
    waitGC();
    {
        Sequence a = Sequence.valueOf("123456789");
        assert Sequence.used() == 1;
        a.toString();
    }
    waitGC();
}

private void waitGC() throws InterruptedException {
    Runtime.getRuntime().gc();
    short count = 0;
    while (count < 100 && Sequence.used() > 0) {
        Thread.sleep(10);
        count++;
    }
    assert Sequence.used() == 0: "Not removed!";
}

The test fails. Telling Not removed!.

This works:

public void testAWeak() throws Exception {
    waitGC();
    extracted();
    waitGC();
}
private void extracted() throws ChecksumException {
    Sequence a = Sequence.valueOf("123456789");
    assert Sequence.used() == 1;
    a.toString();
}
private void waitGC() throws InterruptedException {
    Runtime.getRuntime().gc();
    short count = 0;
    while (count < 100 && Sequence.used() > 0) {
        Thread.sleep(10);
        count++;
    }
    assert Sequence.used() == 0: "Not removed!";
}

It seems like the curly brackets does not affect the weakness.

Some official resources?

Body:
Scope is a compile-time thing. It is not determining the reachability of objects at runtime, only has an indirect influence due to implementation details.

Consider the following variation of your test:

static boolean WARMUP;
public void testWeak1() throws Exception {
    variant1();
    WARMUP = true;
    for(int i=0; i<10000; i++) variant1();
    WARMUP = false;
    variant1();
}
private void variant1() throws Exception {
    AtomicBoolean track = new AtomicBoolean();
    {
        Trackable a = new Trackable(track);
        a.toString();
    }
    if(!WARMUP) System.out.println("variant1: "
                      +(waitGC(track)? "collected": "not collected"));
}
public void testWeak2() throws Exception {
    variant2();
    WARMUP = true;
    for(int i=0; i<10000; i++) variant2();
    WARMUP = false;
    variant2();
}
private void variant2() throws Exception {
    AtomicBoolean track = new AtomicBoolean();
    {
        Trackable a = new Trackable(track);
        a.toString();
        if(!WARMUP) System.out.println("variant2: "
                      +(waitGC(track)? "collected": "not collected"));
    }
}
static class Trackable {
    final AtomicBoolean backRef;
    public Trackable(AtomicBoolean backRef) {
        this.backRef = backRef;
    }
    @Override
    protected void finalize() throws Throwable {
        backRef.set(true);
    }
}

private boolean waitGC(AtomicBoolean b) throws InterruptedException {
    for(int count = 0; count < 10 && !b.get(); count++) {
        Runtime.getRuntime().gc();
        Thread.sleep(1);
    }
    return b.get();
}

on my machine, it prints:

variant1: not collected
variant1: collected
variant2: not collected
variant2: collected

If you can’t reproduce it, you may have to raise the number of warmup iterations.

What it demonstrates: whether a is in scope (variant 2) or not (variant 1) doesn’t matter, in either case, the object has not been collected in cold execution, but got collected after a number of warmup iterations, in other words, after the optimizer kicked in.

Formally, a is always eligible for garbage collection at the point we’re invoking waitGC(), as it is unused from this point. This is how reachability is defined:

A reachable object is any object that can be accessed in any potential continuing computation from any live thread.

In this example, the object can not be accessed by potential continuing computation, as no such subsequent computation that would access the object exists. However, there is no guaranty that a particular JVM’s garbage collector is always capable of identifying all of those objects at each time. In fact, even a JVM not having a garbage collector at all would still comply to the specification, though perhaps not the intent.

The possibility of code optimizations having an effect on the reachability analysis has also explicitly mentioned in the specification:

Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a Java compiler or code generator may choose to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner.

So what happens technically?

As said, scope is a compile-time thing. At the bytecode level, leaving the scope defined by the curly braces has no effect. The variable a is out of scope, but its storage within the stack frame still exists holding the reference until overwritten by another variable or until the method completes. The compiler is free to reuse the storage for another variable, but in this example, no such variable exists. So the two variants of the example above actually generate identical bytecode.

In an unoptimized execution, the still existing reference within the stack frame is treated like a reference preventing the object’s collection. In an optimized execution, the reference is only held until its last actual use. Inlining of its fields can allow its collection even earlier, up to the point that it is collected right after construction (or not getting constructed at all, if it hadn’t a finalize() method). The extreme end is finalize() called on strongly reachable object in Java 8…

Things change, when you insert another variable, e.g.

private void variant1() throws Exception {
    AtomicBoolean track = new AtomicBoolean();
    {
        Trackable a = new Trackable(track);
        a.toString();
    }
    String message = "variant1: ";
    if(!WARMUP) System.out.println(message
                      +(waitGC(track)? "collected": "not collected"));
}

Then, the storage of a is reused by message after a’s scope ended (that’s of course, compiler specific) and the object gets collected, even in the unoptimized execution.

Note that the crucial aspect is the actual overwriting of the storage. If you use

private void variant1() throws Exception {
    AtomicBoolean track = new AtomicBoolean();
    {
        Trackable a = new Trackable(track);
        a.toString();
    }
    if(!WARMUP)
    {
        String message = "variant1: "
                       +(waitGC(track)? "collected": "not collected");
        System.out.println(message);
    }
}

The message variable uses the same storage as a, but its assignment only happens after the invocation of waitGC(track), so you get the same unoptimized execution behavior as in the original variant.

By the way, don’t use short for local loop variables. Java always uses int for byte, short, char, and int calculations (as you know, e.g. when trying to write shortVariable = shortVariable + 1;) and requiring it to cut the result value to short (which still happens implicitly when you use shortVariable++), adds an additional operation, so if you thought, using short improved the efficiency, notice that it actually is the opposite.


问:
Retrieve annotated and concrete methods in class
I have 1 interface, 1 abstract class and 1 concrete class. The annotation @Handler is used in two methods in the interface and abstract class:

public interface A<T> {
    @Handler
    void a(T data);
}

public abstract class B<V> implements A<Integer> {
    @Override
    void a(Integer data) {
        // implementation
    }

    @Handler
    public abstract void b(V data);
}

public class C extends B<String> {
    @Override
    void b(String data) {
        // implementation
    }
}
```

<p>I'd like to retrieve all concrete methods that are decorated with <code>@Handler</code> from the concrete class <code>C</code> (including those from superclasses) along with their parameters, i.e.</p>

```B.a(java.lang.Integer)
C.b(java.lang.String)
```

<p>I tried using Apache Commons Lang's <code>MethodUtils.getMethodsListWithAnnotation()</code>, but it could only find the abstract methods (where the annotations are actually placed), without parameters' info:</p>

```A.a(java.lang.Object)
B.b(java.lang.Object)
```

Is it possible to retrieve the concrete methods along with their parameter types from the abstract ones?

答:
Sure, once you get the Method handles, you can check whether the method is abstract by using Modifier.isAbstract(method.getModifiers()).

If you want to retrieve classes that extend a given class (without knowing them in advance) that's a different matter entirely - you might want to look here: How do you find all subclasses of a given class in Java? for a library that helps you do that. Once you get those classes, you can check via standard methods (Class::getDeclaredMethod()) whether they override the relevant method and whether the override is concrete.

Body:
I have 1 interface, 1 abstract class and 1 concrete class. The annotation @Handler is used in two methods in the interface and abstract class:

public interface A<T> {
    @Handler
    void a(T data);
}

public abstract class B<V> implements A<Integer> {
    @Override
    void a(Integer data) {
        // implementation
    }

    @Handler
    public abstract void b(V data);
}

public class C extends B<String> {
    @Override
    void b(String data) {
        // implementation
    }
}

I'd like to retrieve all concrete methods that are decorated with @Handler from the concrete class C (including those from superclasses) along with their parameters, i.e.

B.a(java.lang.Integer)
C.b(java.lang.String)

I tried using Apache Commons Lang's MethodUtils.getMethodsListWithAnnotation(), but it could only find the abstract methods (where the annotations are actually placed), without parameters' info:

A.a(java.lang.Object)
B.b(java.lang.Object)

Is it possible to retrieve the concrete methods along with their parameter types from the abstract ones?


问:
Visual Studio 2017 cordova not building apk
I'm trying to compile a cordova project to apk using Visual Studio 2017, but it gives me this message:

platform android already added

It is not generating an apk. I followed various tutorials but it's no use. I can't get it to work. What to do?

答:
You have to run it on a android simulator or a android phone for it to build a APK.

For clarification:
Yes you have to use a "device" that is actually running android for Visual Studio to actually build the APK, just building the solution won't work.

You can either use your phone, or the microsoft android simulators for this.
Running it in the browser doesn't use the APK so VS doesn't build it.

You can find more here http://taco.visualstudio.com/en-us/docs/tutorial-package-publish-readme/#package-the-android-version-of-your-app


问:
Using comma-formatted numbers for DecimalField in Wagtail page admin
I have a request from a client to have page admin fields that they can add/read numbers into  with commas such as 1,000,000.

The Django model field to store the value would be a django.db.models.fields.DecimalField instance.

From looking at the Django docs, this is something that’s supported by the django.forms.fields.DecimalField localized property, but I can’t find a way of enforcing it in the Wagtail admin, even when subclassing the Wagtail BaseFieldPanel __init__ function with self.bound_field.field.localize = True.

答:
Thanks @lb-ben-johnston - also to the Wagtail team who pointed me in a similar direction.

I have it working now in a loosely coupled fashion with this:

```<code>from django.forms.fields import DecimalField
from wagtail.wagtailadmin.forms import WagtailAdminPageForm

class ProductPageForm(WagtailAdminPageForm):

    def __init__(self, *args, **kwargs):
        super(ProductPageForm, self).__init__(*args, **kwargs)
        for key, field in self.fields.items():
            if isinstance(field, DecimalField):
                field.localize = True
                field.widget.is_localized = True

# The Page class to localize

class LocalizedPage(Page):

    base_form_class = ProductPageForm

    # Rest of page class
</code>```

Make sure you explictly pass a TextInput widget to the field handler:

```<code>FieldPanel('localized_field', widget=TextInput)
</code>```

Finally, make sure that the thousand separator flag is explicitly set in your settings.py or base.py:

```<code>USE_THOUSAND_SEPARATOR = True
</code>```

Body:
Thanks @lb-ben-johnston - also to the Wagtail team who pointed me in a similar direction.

I have it working now in a loosely coupled fashion with this:

from django.forms.fields import DecimalField
from wagtail.wagtailadmin.forms import WagtailAdminPageForm

class ProductPageForm(WagtailAdminPageForm):

    def __init__(self, *args, **kwargs):
        super(ProductPageForm, self).__init__(*args, **kwargs)
        for key, field in self.fields.items():
            if isinstance(field, DecimalField):
                field.localize = True
                field.widget.is_localized = True

# The Page class to localize

class LocalizedPage(Page):

    base_form_class = ProductPageForm

    # Rest of page class

Make sure you explictly pass a TextInput widget to the field handler:

FieldPanel('localized_field', widget=TextInput)

Finally, make sure that the thousand separator flag is explicitly set in your settings.py or base.py:

USE_THOUSAND_SEPARATOR = True


问:
Creating a kafka consumer using spark streaming
I have started kafka, created a topic and a producer. Now I want to read messages sent from that producer. My code

```<code>def main(args: Array[String]){
    val sparkConf = new SparkConf()
    val spark = new SparkContext(sparkConf)

    val streamingContext = new StreamingContext(spark, Seconds(5))
    val kafkaStream = KafkaUtils.createStream(streamingContext
      , "localhost:2181"
      , "test-group"
      , Map("test" -> 1))
    kafkaStream.print
    streamingContext.start
    streamingContext.awaitTermination
  }
</code>```

The dependencies I use

```<code>  <properties>
    <spark.version>1.6.2</spark.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_2.11</artifactId>
      <version>${spark.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-streaming_2.11</artifactId>
      <version>${spark.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-sql_2.11</artifactId>
      <version>${spark.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-streaming-kafka_2.11</artifactId>
      <version>${spark.version}</version>
    </dependency>
  </dependencies>
</code>```

But every time I try to run it in idea I get

```<code>Exception in thread "main" java.lang.NoSuchMethodError: scala.Predef$.$conforms()Lscala/Predef$$less$colon$less;
    at org.apache.spark.util.Utils$.getSystemProperties(Utils.scala:1582)
    at org.apache.spark.SparkConf.<init>(SparkConf.scala:59)
    at org.apache.spark.SparkConf.<init>(SparkConf.scala:53)
    at com.mypackage.KafkaConsumer$.main(KafkaConsumer.scala:10)
    at com.mypackage.KafkaConsumer.main(KafkaConsumer.scala)
</code>```

Other questions here point to conflicts between dependencies.

I use scala 2.10.5 and spark 1.6.2. I tried them in other projects, they worked fine.

Line 10 in this case is val sparkConf = new SparkConf()

I try to run the app in the IDEA without packaging it.
What can be the reason for this problem?

答:
It's an error with Scala version. You're are using different versions of scala in your code and dependencies.

You said you're using scala 2.10 but you import spark-XX_2.11 dependencies. Unify your scala version.

Body:
I have started kafka, created a topic and a producer. Now I want to read messages sent from that producer. My code

def main(args: Array[String]){
    val sparkConf = new SparkConf()
    val spark = new SparkContext(sparkConf)

    val streamingContext = new StreamingContext(spark, Seconds(5))
    val kafkaStream = KafkaUtils.createStream(streamingContext
      , "localhost:2181"
      , "test-group"
      , Map("test" -> 1))
    kafkaStream.print
    streamingContext.start
    streamingContext.awaitTermination
  }

The dependencies I use

  <properties>
    <spark.version>1.6.2</spark.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_2.11</artifactId>
      <version>${spark.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-streaming_2.11</artifactId>
      <version>${spark.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-sql_2.11</artifactId>
      <version>${spark.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-streaming-kafka_2.11</artifactId>
      <version>${spark.version}</version>
    </dependency>
  </dependencies>

But every time I try to run it in idea I get

Exception in thread "main" java.lang.NoSuchMethodError: scala.Predef$.$conforms()Lscala/Predef$$less$colon$less;
    at org.apache.spark.util.Utils$.getSystemProperties(Utils.scala:1582)
    at org.apache.spark.SparkConf.<init>(SparkConf.scala:59)
    at org.apache.spark.SparkConf.<init>(SparkConf.scala:53)
    at com.mypackage.KafkaConsumer$.main(KafkaConsumer.scala:10)
    at com.mypackage.KafkaConsumer.main(KafkaConsumer.scala)

Other questions here point to conflicts between dependencies.

I use scala 2.10.5 and spark 1.6.2. I tried them in other projects, they worked fine.

Line 10 in this case is val sparkConf = new SparkConf()

I try to run the app in the IDEA without packaging it.
What can be the reason for this problem?


问:
WPF application exits immediately when showing a dialog before startup
Update: I guess, what I need is to understand what is the "correct", "supported" way to show a dialog before application start in WPF.

Here's the code:

```<code>    public partial class App : Application
    {
        [STAThread]
        public static void Main()
        {
            var app = new App();
            app.InitializeComponent();

            new DialogWindow().ShowDialog();

            app.Run( new MainWindow() );
        }
    }
</code>```

The DialogWindow shows up as expected.

But after closing it, the application exits immediately. MainWindow doesn't show up at all!

I have done some debugging and traced the problem to this:

When the dialog is created, it becomes app's MainWindow, since there is no MainWindow at the moment.

Therefore, closing the dialog causes the application to post ShutdownCallback on the dispatcher queue.

However, the dispatcher doesn't run long enough to execute the callback.

Therefore, once app.Run is called subsequently, the first thing on the queue is ShutdownCallback, which, naturally, causes the app to close immediately.

Given this analysis, there is an obvious workaround: create MainWindow right after App, thus making it app's MainWindow, which would prevent DialogWindow from causing application closure.

However, here is what bothers me.

First, this looks like a dirty hack to me. I mean, there is no explicit reason for creating windows in this order, and I have only found this through some debugging. This can't be the supported way.

Second, this is clearly a bug. I mean, if creating a second window after shutdown wasn't supported explicitly, it should've thrown some InvalidOperationException, right?

Thirdly, not only is this a bug, but it looks like a very naive one, something like a multithreading beginner would create.

All this leads me to believe that maybe I don't get something fundamental here? Maybe I don't make sense at all? Maybe it all should be done in some different fashion?

Here's some background:

The application has to do some bootstrapping on startup. Check this and that, setup exception handlers, logging - you know, the usual stuff. In this process, it may become necessary to ask the user for some help - which is what the dialog is for.

I absolutely don't want to put all that in some kind of state machine that executes on MainWindow.IsVisibleChanged or something like that. I would like to keep it really simple, short and straightforward - the way bootstrap code is supposed to be, so that it's easy to spot bugs with a naked eye.

答:
By default, the ShutdownMode of a WPF application is OnLastWindowClose. In your code you show a single window and then close it. So the last window is closed and the application shuts down. Then while shutting down, you show another window. Since the application is shutting down, the window is immediately closed.

So everything is working as designed and programmed by you.

However, you want to do something different: The window you show first as the only window is supposed to be a "special window", and after closing it you want to continue executing, show your "main window" and then exit the application once it (or all windows associated with the app) closes.

The easiest way: First set the shutdown mode to OnExplicitShutdown, then after showing the main window set it to OnLastWindowClose or OnMainWindowClose. In code:

```<code>public static void Main()
{
    var app = new App();
    app.InitializeComponent();

    app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
    new DialogWindow().ShowDialog();

    var mainWindow = new MainWindow();
    app.MainWindow = mainWindow;
    app.Run(mainWindow);
    // When the window has loaded, it should then set the app.ShutdownMode to what you actually want.
}
</code>```

EDIT:
I am not sure what exactly you are doing. The code you gave will not compile, since when properly using a WPF application class (with an App.xaml build-action as ApplicationDefinition), a Main method is already defined. If you just have a class derived from Application, you have no InitializeComponent() method. The only way to get you code to compile was by manually changing the build-action to Page. However, in that case, Application.Current == app.

So what occurs is the following:

The application starts. Since no WPF-application has been created so far, Application.Current is null. This also means no dispatcher-loop is running and dispatcher messages are unhandled (note that the dispatcher loop also handles windows messages).

A new App-object is created. Since Application.Current is null, it sets itself as Application.Current.

Application.Current.MainWindow is null and Application.Current.Windows is an empty list.

Since ShutdownMode is OnLastWindowClose, once the last window of the current application (i.e. app) closes, shutdown starts.

The DialogBox is shown modally. Since no dispatcher-loop is running, the ShowDialog() itself runs a "local" dispatcher-loop.

Actually this is two parts: First the window is created. It belongs to the current application, so it adds itself to Application.Current.Windows. Since it is the first window shown and Application.Current.MainWindow is null, it also sets itself as main window. Secondly, the window is shown modally.

Since Application.Current.Windows is now non-empty, once it is empty, shutdown will start.

The user closes the dialog window. As part of being closed, the window removes itself from Application.Current.Windows. Also, since it is the MainWindow, this is set to null. Since Application.Current.Windows is now empty, shutdown starts. However, since there is no dispatcher-loop running, nothing is done yet (only an internal flag or similar is set).

If you had used app.Run(new DialogWindow()); app.Run(new MainWindow());, you would have an exception while creating the MainWindow, since in this case the dispatcher-loop is running properly. Thus, it can actually shutting itself down, so when the MainWindow is created, it throws an exception since the dispatcher-loop is already shut down.

MainWindow is created. As above, it adds itself to Application.Current.Windows and sets itself as Application.Current.MainWindow.

However, the condition for shutting down the application has already been reached. But, so far, the application had no chance to do something.

Now Run() is called. The dispatcher-loop starts again and now has a chance to shutdown the application. So it shuts down the application and closes any open windows.

So again, no bug.

So one way to solve this is to change to OnExplicitShutdown. Then in step 4, no reason for shutting down is reached. Better (as in more like a normal WPF application) would be to have a proper ApplicationDefinition. Remove the StartupUri from the App.xaml and instead handle the Startup event:

```<code>private void OnStartup(object sender, StartupEventArgs e)
{
    this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
    new DialogWindow().ShowDialog();

    var mainWindow = new MainWindow();
    this.ShutdownMode = ShutdownMode.OnLastWindowClose; // or OnMainWindowClose
    mainWindow.Show();
}
</code>```

Since we have OnExplicitShudown while closing the dialog window, there is no reason for the application to start shutting down at that point. Then, after creating the MainWindow, we again have a window as main window and as (one of the) application windows. So then we can switch to the shutdown mode we actually want and show the main window.

Body:
Update: I guess, what I need is to understand what is the "correct", "supported" way to show a dialog before application start in WPF.

Here's the code:

    public partial class App : Application
    {
        [STAThread]
        public static void Main()
        {
            var app = new App();
            app.InitializeComponent();

            new DialogWindow().ShowDialog();

            app.Run( new MainWindow() );
        }
    }

The DialogWindow shows up as expected.

But after closing it, the application exits immediately. MainWindow doesn't show up at all!

I have done some debugging and traced the problem to this:

When the dialog is created, it becomes app's MainWindow, since there is no MainWindow at the moment.

Therefore, closing the dialog causes the application to post ShutdownCallback on the dispatcher queue.

However, the dispatcher doesn't run long enough to execute the callback.

Therefore, once app.Run is called subsequently, the first thing on the queue is ShutdownCallback, which, naturally, causes the app to close immediately.

Given this analysis, there is an obvious workaround: create MainWindow right after App, thus making it app's MainWindow, which would prevent DialogWindow from causing application closure.

However, here is what bothers me.

First, this looks like a dirty hack to me. I mean, there is no explicit reason for creating windows in this order, and I have only found this through some debugging. This can't be the supported way.

Second, this is clearly a bug. I mean, if creating a second window after shutdown wasn't supported explicitly, it should've thrown some InvalidOperationException, right?

Thirdly, not only is this a bug, but it looks like a very naive one, something like a multithreading beginner would create.

All this leads me to believe that maybe I don't get something fundamental here? Maybe I don't make sense at all? Maybe it all should be done in some different fashion?

Here's some background:

The application has to do some bootstrapping on startup. Check this and that, setup exception handlers, logging - you know, the usual stuff. In this process, it may become necessary to ask the user for some help - which is what the dialog is for.

I absolutely don't want to put all that in some kind of state machine that executes on MainWindow.IsVisibleChanged or something like that. I would like to keep it really simple, short and straightforward - the way bootstrap code is supposed to be, so that it's easy to spot bugs with a naked eye.

Body:
By default, the ShutdownMode of a WPF application is OnLastWindowClose. In your code you show a single window and then close it. So the last window is closed and the application shuts down. Then while shutting down, you show another window. Since the application is shutting down, the window is immediately closed.

So everything is working as designed and programmed by you.

However, you want to do something different: The window you show first as the only window is supposed to be a "special window", and after closing it you want to continue executing, show your "main window" and then exit the application once it (or all windows associated with the app) closes.

The easiest way: First set the shutdown mode to OnExplicitShutdown, then after showing the main window set it to OnLastWindowClose or OnMainWindowClose. In code:

public static void Main()
{
    var app = new App();
    app.InitializeComponent();

    app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
    new DialogWindow().ShowDialog();

    var mainWindow = new MainWindow();
    app.MainWindow = mainWindow;
    app.Run(mainWindow);
    // When the window has loaded, it should then set the app.ShutdownMode to what you actually want.
}

EDIT:
I am not sure what exactly you are doing. The code you gave will not compile, since when properly using a WPF application class (with an App.xaml build-action as ApplicationDefinition), a Main method is already defined. If you just have a class derived from Application, you have no InitializeComponent() method. The only way to get you code to compile was by manually changing the build-action to Page. However, in that case, Application.Current == app.

So what occurs is the following:

The application starts. Since no WPF-application has been created so far, Application.Current is null. This also means no dispatcher-loop is running and dispatcher messages are unhandled (note that the dispatcher loop also handles windows messages).

A new App-object is created. Since Application.Current is null, it sets itself as Application.Current.

Application.Current.MainWindow is null and Application.Current.Windows is an empty list.

Since ShutdownMode is OnLastWindowClose, once the last window of the current application (i.e. app) closes, shutdown starts.

The DialogBox is shown modally. Since no dispatcher-loop is running, the ShowDialog() itself runs a "local" dispatcher-loop.

Actually this is two parts: First the window is created. It belongs to the current application, so it adds itself to Application.Current.Windows. Since it is the first window shown and Application.Current.MainWindow is null, it also sets itself as main window. Secondly, the window is shown modally.

Since Application.Current.Windows is now non-empty, once it is empty, shutdown will start.

The user closes the dialog window. As part of being closed, the window removes itself from Application.Current.Windows. Also, since it is the MainWindow, this is set to null. Since Application.Current.Windows is now empty, shutdown starts. However, since there is no dispatcher-loop running, nothing is done yet (only an internal flag or similar is set).

If you had used app.Run(new DialogWindow()); app.Run(new MainWindow());, you would have an exception while creating the MainWindow, since in this case the dispatcher-loop is running properly. Thus, it can actually shutting itself down, so when the MainWindow is created, it throws an exception since the dispatcher-loop is already shut down.

MainWindow is created. As above, it adds itself to Application.Current.Windows and sets itself as Application.Current.MainWindow.

However, the condition for shutting down the application has already been reached. But, so far, the application had no chance to do something.

Now Run() is called. The dispatcher-loop starts again and now has a chance to shutdown the application. So it shuts down the application and closes any open windows.

So again, no bug.

So one way to solve this is to change to OnExplicitShutdown. Then in step 4, no reason for shutting down is reached. Better (as in more like a normal WPF application) would be to have a proper ApplicationDefinition. Remove the StartupUri from the App.xaml and instead handle the Startup event:

private void OnStartup(object sender, StartupEventArgs e)
{
    this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
    new DialogWindow().ShowDialog();

    var mainWindow = new MainWindow();
    this.ShutdownMode = ShutdownMode.OnLastWindowClose; // or OnMainWindowClose
    mainWindow.Show();
}

Since we have OnExplicitShudown while closing the dialog window, there is no reason for the application to start shutting down at that point. Then, after creating the MainWindow, we again have a window as main window and as (one of the) application windows. So then we can switch to the shutdown mode we actually want and show the main window.


问:
How to write query with outer joins and multiple OR criteria?
In this query we perform outer joins from a large table release to two tables release_event and release_barcode. These must be outer joins, because in the results we want to return releases which don't have entries in either table:

```<code>SELECT r.source_uri AS su_on_r, r.title AS t_on_r, release_event.cat, release_barcode.barcode
FROM   release r
    left join release_event event ON r.source_uri = event.source_uri
    left join release_barcode barcode ON r.source_uri = barcode.source_uri
WHERE  ( event.cat IN ( '3145422912' ) AND event.label_name = 'UTV Records' )
    OR barcode.barcode IN ( '731454229128' )
</code>```

When analysed, this performs a sequential scan on the release table:

```<code>|   ->  Sort  (cost=2169219.61..2169219.65 rows=13 width=66)                                                                                |
|         Sort Key: r.source_uri                                                                                |
|         ->  Hash Left Join  (cost=721970.94..2169219.37 rows=13 width=66)                                                                                |
|               Hash Cond: ((r.source_uri)::text = (barcode.source_uri)::text)                                                                                |
|               Filter: ((((event.cat)::text = '3145422912'::text) AND ((event.label_name)::text = 'UTV Records'::text)) OR ((barcode.barcode)::text = '731454229128'::text)) |
|               ->  Hash Right Join  (cost=589927.01..1568193.22 rows=11405330 width=88)                                                                                |
|                     Hash Cond: ((event.source_uri)::text = (r.source_uri)::text)                                                                                |
|                     ->  Seq Scan on release_event event  (cost=0.00..283078.30 rows=11405330 width=65)                                                                      |
|                     ->  Hash  (cost=324393.56..324393.56 rows=10963956 width=66)                                                                                |
|                           ->  Seq Scan on release r  (cost=0.00..324393.56 rows=10963956 width=66)                                                                          |
|               ->  Hash  (cost=63125.97..63125.97 rows=2965197 width=60)                                                                                |
|                     ->  Seq Scan on release_barcode barcode  (cost=0.00..63125.97 rows=2965197 width=6
</code>```

If I have just one of the above criteria, the query planner (Postgresql) understands this, using the indexes to limit results from release:

```<code>|   ->  Sort  (cost=42.26..42.27 rows=3 width=66)                                                                               |
|         Sort Key: r.source_uri                                                                                |
|         ->  Nested Loop  (cost=0.99..42.24 rows=3 width=66)                                                                   |
|               ->  Index Scan using release_barcode_barcode_idx on release_barcode barcode  (cost=0.43..16.47 rows=3 width=47) |
|                     Index Cond: ((barcode)::text = '731454229128'::text)                                                      |
|               ->  Index Scan using release_pkey on release r  (cost=0.56..8.58 rows=1 width=66)                               |
|                     Index Cond: ((source_uri)::text = (barcode.source_uri)::text)
</code>```

How can I rewrite queries with outer joins and multiple OR'd criteria to first limit the joined tables and only lookup the release table for any of those rows that match?

答:
You might try writing this using exists:

```<code>SELECT r.source_uri as su_on_r, r.title as t_on_r
FROM release r
WHERE EXISTS (SELECT 1
              FROM release_event re
              WHERE r.source_uri = re.source_uri AND
                    re.cat IN ( '3145422912' ) AND re.label_name = 'UTV Records'
             ) OR
      EXISTS (SELECT 1
              FROM release_barcode rb
              WHERE r.source_uri = rb.source_uri AND
                    rb.barcode IN ( '731454229128' )
             );
</code>```

For these queries, I would recommend indexes on release_event(source_uri, cat, label_name) and release_barcode(source_uri, barcode).

You can also phrase the query using union (to remove duplicates):

```<code>SELECT r.source_uri AS su_on_r, r.title AS t_on_r
FROM release r JOIN
     release_event event
     ON r.source_uri = event.source_uri
WHERE  event.cat IN ( '3145422912' ) AND event.label_name = 'UTV Records'
UNION
SELECT r.source_uri AS su_on_r, r.title AS t_on_r
FROM release r JOIN
     release_barcode
     ON r.source_uri = barcode.source_uri
WHERE barcode.barcode IN ( '731454229128' )  ;
</code>```

Body:
In this query we perform outer joins from a large table release to two tables release_event and release_barcode. These must be outer joins, because in the results we want to return releases which don't have entries in either table:

SELECT r.source_uri AS su_on_r, r.title AS t_on_r, release_event.cat, release_barcode.barcode
FROM   release r
    left join release_event event ON r.source_uri = event.source_uri
    left join release_barcode barcode ON r.source_uri = barcode.source_uri
WHERE  ( event.cat IN ( '3145422912' ) AND event.label_name = 'UTV Records' )
    OR barcode.barcode IN ( '731454229128' )

When analysed, this performs a sequential scan on the release table:

|   ->  Sort  (cost=2169219.61..2169219.65 rows=13 width=66)                                                                                |
|         Sort Key: r.source_uri                                                                                |
|         ->  Hash Left Join  (cost=721970.94..2169219.37 rows=13 width=66)                                                                                |
|               Hash Cond: ((r.source_uri)::text = (barcode.source_uri)::text)                                                                                |
|               Filter: ((((event.cat)::text = '3145422912'::text) AND ((event.label_name)::text = 'UTV Records'::text)) OR ((barcode.barcode)::text = '731454229128'::text)) |
|               ->  Hash Right Join  (cost=589927.01..1568193.22 rows=11405330 width=88)                                                                                |
|                     Hash Cond: ((event.source_uri)::text = (r.source_uri)::text)                                                                                |
|                     ->  Seq Scan on release_event event  (cost=0.00..283078.30 rows=11405330 width=65)                                                                      |
|                     ->  Hash  (cost=324393.56..324393.56 rows=10963956 width=66)                                                                                |
|                           ->  Seq Scan on release r  (cost=0.00..324393.56 rows=10963956 width=66)                                                                          |
|               ->  Hash  (cost=63125.97..63125.97 rows=2965197 width=60)                                                                                |
|                     ->  Seq Scan on release_barcode barcode  (cost=0.00..63125.97 rows=2965197 width=6

If I have just one of the above criteria, the query planner (Postgresql) understands this, using the indexes to limit results from release:

|   ->  Sort  (cost=42.26..42.27 rows=3 width=66)                                                                               |
|         Sort Key: r.source_uri                                                                                |
|         ->  Nested Loop  (cost=0.99..42.24 rows=3 width=66)                                                                   |
|               ->  Index Scan using release_barcode_barcode_idx on release_barcode barcode  (cost=0.43..16.47 rows=3 width=47) |
|                     Index Cond: ((barcode)::text = '731454229128'::text)                                                      |
|               ->  Index Scan using release_pkey on release r  (cost=0.56..8.58 rows=1 width=66)                               |
|                     Index Cond: ((source_uri)::text = (barcode.source_uri)::text)

How can I rewrite queries with outer joins and multiple OR'd criteria to first limit the joined tables and only lookup the release table for any of those rows that match?

Body:
You might try writing this using exists:

SELECT r.source_uri as su_on_r, r.title as t_on_r
FROM release r
WHERE EXISTS (SELECT 1
              FROM release_event re
              WHERE r.source_uri = re.source_uri AND
                    re.cat IN ( '3145422912' ) AND re.label_name = 'UTV Records'
             ) OR
      EXISTS (SELECT 1
              FROM release_barcode rb
              WHERE r.source_uri = rb.source_uri AND
                    rb.barcode IN ( '731454229128' )
             );

For these queries, I would recommend indexes on release_event(source_uri, cat, label_name) and release_barcode(source_uri, barcode).

You can also phrase the query using union (to remove duplicates):

SELECT r.source_uri AS su_on_r, r.title AS t_on_r
FROM release r JOIN
     release_event event
     ON r.source_uri = event.source_uri
WHERE  event.cat IN ( '3145422912' ) AND event.label_name = 'UTV Records'
UNION
SELECT r.source_uri AS su_on_r, r.title AS t_on_r
FROM release r JOIN
     release_barcode
     ON r.source_uri = barcode.source_uri
WHERE barcode.barcode IN ( '731454229128' )  ;


问:
How to reuse prefix fast when adding new key in IntelliJ Resource Bundle
I have resource bundles with keys grouped by many levels of prefixes. Example:

admin.common.alert.warning.security.passwordInsecure.tooShort
  admin.common.alert.warning.security.passwordInsecure.noNumbers

I would like to easily add new keys by reusing certain prefixes, without having to select the prefix, open it in edit mode, copy it, close the dialog, open the add dialog and paste the prefix before adding the suffix.

In eclipse, when viewing the keys hierarchically, I can select a prefix where I want to add a new key, press the add button and the prefix is automatically filled in in the add dialog. Example:

In IDEA this doesn't happen. Is there any setting or plugin may help speed up adding new keys?

Note: I am using IDEA Community 2017

答: Use Refactor | Copy (F5 default shortcut) action on a certain selected property.


问:
Create a document only if it doesn't exist in Firebase Firestore
What I am trying to achieve is very simple. I need to create a user entry in the database only if it doesn't exist.

The app flow:

Create a user with Firebase Auth (obtain UID)

Create a user document in the database using UID as the key

The client code (create operation):

```<code>this.db.doc('users/' + uid).set({username: Santa})
</code>```

The firestore rules:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow create: if
        request.auth != null &&
        request.auth.uid == uid &&
        !exists(/databases/$(database)/documents/users/$(uid));
      allow update: if request.auth != null && request.auth.uid == uid;
    }
  }
}
</code>```

Additional info:

As you may already know the code doesn't work. Everytime I run the client-side code the current user is completely replaced with a new document. However, if I delete the following line from the rules everything works as expected:

```<code>allow update: if request.auth != null && request.auth.uid == uid;
</code>```

But now the question arises, how do I secure data inside user document from unauthorised modifications? Any advice?

答:
Use logic in your code, but not in rules. Add addOnCompleteListener to user collection and after get the result do some actions.

```<code>getUsers.document(userUID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> doc) {
     if(!doc.getResult().exists()){
        //add new user
    }
}
</code>```

}

Rules:

```<code>match /UsersProfile/{document=**} {
  allow read, write: if request.auth != null;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What I am trying to achieve is very simple. I need to create a user entry in the database only if it doesn't exist.

The app flow:

Create a user with Firebase Auth (obtain UID)

Create a user document in the database using UID as the key

The client code (create operation):

this.db.doc('users/' + uid).set({username: Santa})

The firestore rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow create: if
        request.auth != null &&
        request.auth.uid == uid &&
        !exists(/databases/$(database)/documents/users/$(uid));
      allow update: if request.auth != null && request.auth.uid == uid;
    }
  }
}

Additional info:

As you may already know the code doesn't work. Everytime I run the client-side code the current user is completely replaced with a new document. However, if I delete the following line from the rules everything works as expected:

allow update: if request.auth != null && request.auth.uid == uid;

But now the question arises, how do I secure data inside user document from unauthorised modifications? Any advice?

Body:
Use logic in your code, but not in rules. Add addOnCompleteListener to user collection and after get the result do some actions.

getUsers.document(userUID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> doc) {
     if(!doc.getResult().exists()){
        //add new user
    }
}

}

Rules:

match /UsersProfile/{document=**} {
  allow read, write: if request.auth != null;
}


问:
How to resize a sprite after changing it's texture
Say I have a size 25x25 SKSpriteNode and I change the node's .texture property to a texture that is size 50x50. It seems like it is trying to shrink the new texture to fit size 25x25, the original size of the node. But how can I change the node's size to adapt to the new size of the texture, in this example 50x50.

In short, I want my sprite to resize to fit the dimensions of the new texture.

```<code>override func applyEffect() {
    switch(tier) {
    case 2:
        sprite.texture = SKTexture(imageNamed: "clock2")
    case 3:
        sprite.texture = SKTexture(imageNamed: "clock3")
    case 4:
        sprite.texture = SKTexture(imageNamed: "clock4")
    default:
        print("")
    }
}
</code>```

Thanks!

答:
You can set the node to resize when you add a new texture, by setting the resize parameter to true</p>

```<code> let newTexture = SKTexture(imageNamed: "someNewTexture")
 someNode.run(SKAction.setTexture(newTexture, resize: true))
</code>```

Body:
Say I have a size 25x25 SKSpriteNode and I change the node's .texture property to a texture that is size 50x50. It seems like it is trying to shrink the new texture to fit size 25x25, the original size of the node. But how can I change the node's size to adapt to the new size of the texture, in this example 50x50.

In short, I want my sprite to resize to fit the dimensions of the new texture.

override func applyEffect() {
    switch(tier) {
    case 2:
        sprite.texture = SKTexture(imageNamed: "clock2")
    case 3:
        sprite.texture = SKTexture(imageNamed: "clock3")
    case 4:
        sprite.texture = SKTexture(imageNamed: "clock4")
    default:
        print("")
    }
}

Thanks!

Body:
You can set the node to resize when you add a new texture, by setting the resize parameter to true

 let newTexture = SKTexture(imageNamed: "someNewTexture")
 someNode.run(SKAction.setTexture(newTexture, resize: true))


问:
Header Authorization not working on Sub Domain
I have this function for Basic Authorization for my API.

```<code>private function authorize() {
    $headers = apache_request_headers();
    if(isset($headers['Authorization'])){
        if ($headers['Authorization'] == '14abd57ece42d9489aeae6e1865064751') { //'akif&&nadeem'
            return true;
        }
    }
    return false;
}
</code>```

It works well on my API domain domain.com/api/actionname

But it does not work [Fails Authorization] when I try to access my API via a Sub Domain subdomain.domain.com/api/actionname

All code is correctly in place and API is performing perfectly without Authorization. Any idea how can I fix this?

Output of the Headers is as follows:

```<code>array(9) {
   ["Host"]=>
     string(24) "ultimate.bleupage.online"
     ["Connection"]=>
     string(10) "keep-alive"
     ["User-Agent"]=>
     string(115) "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
     ["Cache-Control"]=>
     string(8) "no-cache"
     ["Postman-Token"]=>
     string(36) "6330a309-ffcf-d72e-936a-bf10ff154d45"
     ["Accept"]=>
     string(3) "*/*"
     ["Accept-Encoding"]=>
     string(13) "gzip, deflate"
     ["Accept-Language"]=>
    string(26) "en-GB,en-US;q=0.8,en;q=0.6"
     ["Cookie"]=>
     string(36) "PHPSESSID=p2m0cc7sq7kn8fk2motvrobnn4"
   }
</code>```

答:
Try using some other parameter key than Authorization, like Auth, because sometimes Apache filters away the Authorization header you can get more info here Apache 2.4 + PHP-FPM and Authorization headers.

which you can access, like this(with $_SERVER):

```<code>$_SERVER['HTTP_AUTH']
</code>```

Or Like this(with apache_request_headers):

```<code>apache_request_headers()['Auth'];
</code>```

Body:
I have this function for Basic Authorization for my API.

private function authorize() {
    $headers = apache_request_headers();
    if(isset($headers['Authorization'])){
        if ($headers['Authorization'] == '14abd57ece42d9489aeae6e1865064751') { //'akif&&nadeem'
            return true;
        }
    }
    return false;
}

It works well on my API domain domain.com/api/actionname

But it does not work [Fails Authorization] when I try to access my API via a Sub Domain subdomain.domain.com/api/actionname

All code is correctly in place and API is performing perfectly without Authorization. Any idea how can I fix this?

Output of the Headers is as follows:

array(9) {
   ["Host"]=>
     string(24) "ultimate.bleupage.online"
     ["Connection"]=>
     string(10) "keep-alive"
     ["User-Agent"]=>
     string(115) "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
     ["Cache-Control"]=>
     string(8) "no-cache"
     ["Postman-Token"]=>
     string(36) "6330a309-ffcf-d72e-936a-bf10ff154d45"
     ["Accept"]=>
     string(3) "*/*"
     ["Accept-Encoding"]=>
     string(13) "gzip, deflate"
     ["Accept-Language"]=>
    string(26) "en-GB,en-US;q=0.8,en;q=0.6"
     ["Cookie"]=>
     string(36) "PHPSESSID=p2m0cc7sq7kn8fk2motvrobnn4"
   }

Body:
Try using some other parameter key than Authorization, like Auth, because sometimes Apache filters away the Authorization header you can get more info here Apache 2.4 + PHP-FPM and Authorization headers.

which you can access, like this(with $_SERVER):

$_SERVER['HTTP_AUTH']

Or Like this(with apache_request_headers):

apache_request_headers()['Auth'];


问:
How to make Wordpress categories as subdomains without using a plugin?
I was using a plugin called wordpress subdomains 0.6.9 but it has lots of bugs and creating subdomains with this version is risky, I mean later there will be lots of broken links, so is there any way to do this manually, by editing the php code or database values ?
or anything else that will make this work ?
and thank you :D</p>

答:
Are you using Apache2 + permalink? If so, craft some RewriteRule within .htaccess could do it (along with the original permalink).

For example

```<code>RewriteCond %{HTTP_HOST} cat1.my.site
RewriteRule ^.*$ /categories/cat1$0 [R]
</code>```

Or, do 301 redirection

```<code>RewriteCond %{HTTP_HOST} cat1.my.site
RewriteRule ^.*$ http://my.site/categories/cat1$0 [R,L]
</code>```

(Above code is untested so you might want to compare them with doc and test)

http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html

Body:
Are you using Apache2 + permalink? If so, craft some RewriteRule within .htaccess could do it (along with the original permalink).

For example

RewriteCond %{HTTP_HOST} cat1.my.site
RewriteRule ^.*$ /categories/cat1$0 [R]

Or, do 301 redirection

RewriteCond %{HTTP_HOST} cat1.my.site
RewriteRule ^.*$ http://my.site/categories/cat1$0 [R,L]

(Above code is untested so you might want to compare them with doc and test)

http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html


问:
adding an object to an empty  in jQuery
I'm attempting

```<code> var a = $("<a/>");
</code>```

then I'm trying to fill this empty variable with the contents of an object, set to variable 'obj'

```<code>obj = {
 Name: " Ben",
 number: 666,
}
</code>```

I have tried to append a using the various methods

```<code>a.append(obj);
a.append("("+obj+")");
</code>```

but if I then do:

```<code>console.log(a)
</code>```

there is no way to tell if the object is now in the link tag. If I look in the console on the site I can see

```<code>([object Object])
</code>```

rather than the contents. Am I missing something?

答:
You have to use property of object
like below</p>

```<code>var a = $("<a/>");
obj = {
  Name: " Ben",
  number: 666,
 }

a.text(obj.Name + ' ' + obj.number);
</code>```

Title: adding an object to an empty <a/> in jQuery

Body:
I'm attempting

 var a = $("");

then I'm trying to fill this empty variable with the contents of an object, set to variable 'obj'

obj = {
 Name: " Ben",
 number: 666,
}

I have tried to append a using the various methods

a.append(obj);
a.append("("+obj+")");

but if I then do:

console.log(a)

there is no way to tell if the object is now in the link tag. If I look in the console on the site I can see

([object Object])

rather than the contents. Am I missing something?

Body:
You have to use property of object
like below

var a = $("<a/>");
obj = {
  Name: " Ben",
  number: 666,
 }

a.text(obj.Name + ' ' + obj.number);