问:
How do I invalidate the old images when request for a new one is initiated in React?
Have a look my code below, I have create a pen for it too: https://codepen.io/segmentationfaulter/pen/YEEaxK

The problem is that when I click on change image button, the old image stays there for a while until the new image is loaded. What I want is that the old image is invalidated straight away and empty space is shown for the new image. How can I achieve this in react? If you can't spot the issue, try opening it in private mode so that caching doesn't affect it.

const images = [
  'http://via.placeholder.com/550x550',
  'http://via.placeholder.com/750x750'
]

class MyImage extends React.Component {
  constructor() {
    super()
    this.state = {
      currentImageIndex: 0
    }
  }
  changeImage() {
    this.setState((prevState) => {
      if (prevState.currentImageIndex) {
        return {
          currentImageIndex: 0
        }
      } else {
        return {
          currentImageIndex: 1
        }
      }
    })
  }
  render() {
    return ( <
      div >
      <
      img src = {
        this.props.images[this.state.currentImageIndex]
      }
      /> <
      button onClick = {
        this.changeImage.bind(this)
      } >
      change image <
      /button> <
      /div>
    )
  }
}

ReactDOM.render( < MyImage images = {
      images
    }
    />, document.getElementById('root'))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  display: block;
}

button {
  margin-top: 15px;
}</code>```

```

答:
Possible way may be:

put empty picture if state is changed

fetch the image and then replace empty image from response

Body:
Have a look my code below, I have create a pen for it too: https://codepen.io/segmentationfaulter/pen/YEEaxK

The problem is that when I click on change image button, the old image stays there for a while until the new image is loaded. What I want is that the old image is invalidated straight away and empty space is shown for the new image. How can I achieve this in react? If you can't spot the issue, try opening it in private mode so that caching doesn't affect it.

const images = [
  'http://via.placeholder.com/550x550',
  'http://via.placeholder.com/750x750'
]

class MyImage extends React.Component {
  constructor() {
    super()
    this.state = {
      currentImageIndex: 0
    }
  }
  changeImage() {
    this.setState((prevState) => {
      if (prevState.currentImageIndex) {
        return {
          currentImageIndex: 0
        }
      } else {
        return {
          currentImageIndex: 1
        }
      }
    })
  }
  render() {
    return ( <
      div >
      <
      img src = {
        this.props.images[this.state.currentImageIndex]
      }
      /> <
      button onClick = {
        this.changeImage.bind(this)
      } >
      change image <
      /button> <
      /div>
    )
  }
}

ReactDOM.render( < MyImage images = {
      images
    }
    />, document.getElementById('root'))

img {
  display: block;
}

button {
  margin-top: 15px;
}


来源: stackexchange

问:
Delete statement not executed in postgresql
I am creating a transaction where I want to update a user in one table and delete some data in another that belongs to that user. But only the first query is executed, not the second one. In the delete statement  in the second query code is a comma-separated std::string.

```<code>pqxx::connection c(connectionString);

try {
    pqxx::work w(c);
    pqxx::result r;

    c.prepare("user", "update user set started = null, finished = null, task = $1 where id = $2");
    r = w.prepared("user")(task)(email).exec();

    c.prepare("belongings", "delete from belongings where id in " \
        "(select id from info where code in ($1) and id = $2)");
    r = w.prepared("belongings")(code)(id).exec();

    w.commit();
}
</code>```

I read this SO-thread that explain how to run multiple queries before commit(). So I must be making a mistake in the second delete statement but can't find the reason.

答:
The code parameter is interpreted as a single literal. You can try to use the alternative syntax of any(array expression), e.g.:

```<code>code = "{abc,def}";     // instead of code = "'abc','def'"
...

c.prepare("belongings", "delete from belongings where id in " \
    "(select id from info where code = any ($1) and id = $2)");
r = w.prepared("belongings")(code)(id).exec();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating a transaction where I want to update a user in one table and delete some data in another that belongs to that user. But only the first query is executed, not the second one. In the delete statement  in the second query code is a comma-separated std::string.

pqxx::connection c(connectionString);

try {
    pqxx::work w(c);
    pqxx::result r;

    c.prepare("user", "update user set started = null, finished = null, task = $1 where id = $2");
    r = w.prepared("user")(task)(email).exec();

    c.prepare("belongings", "delete from belongings where id in " \
        "(select id from info where code in ($1) and id = $2)");
    r = w.prepared("belongings")(code)(id).exec();

    w.commit();
}

I read this SO-thread that explain how to run multiple queries before commit(). So I must be making a mistake in the second delete statement but can't find the reason.

Body:
The code parameter is interpreted as a single literal. You can try to use the alternative syntax of any(array expression), e.g.:

code = "{abc,def}";     // instead of code = "'abc','def'"
...

c.prepare("belongings", "delete from belongings where id in " \
    "(select id from info where code = any ($1) and id = $2)");
r = w.prepared("belongings")(code)(id).exec();


问:
Azure App Service applicationHost.config Set server variable is working but not working
We are trying to rewrite the "host" header given a header of "X-CF-ORIGIN" - this works locally, however, in the app service, all logging indicates it has worked but we don't seem to see the effect.

We expect to get a 500 error for an incorrect HOST header, however, the site resolves as if the host header has not been changed.

Also, our XDT transform indicates it has worked (see below).

This was initially raised on Kudu Github but have been directed to here for Azure App Service IIS questions.

A code example:
https://github.com/Workshop2/webforms-host-header-rewrite-spike

Live example:
http://webforms-fun.azurewebsites.net/   with XDT transform

Our rewrite rule:

```<code><rule name="CDN Host Header Rewrite" stopProcessing="false">
  <match url=".*" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
    <add input="{HTTP_X_CF_ORIGIN}" pattern="(.+)" />
  </conditions>
  <serverVariables>
    <set name="HTTP_HOST" value="{C:1}" />
  </serverVariables>
  <action type="None" />
</rule>
</code>```

Our XDT Transform:

```<code><?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.webServer>
        <rewrite>
            <allowedServerVariables>
            <add name="HTTP_HOST" xdt:Transform="InsertIfMissing" />
            </allowedServerVariables>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

applicationHost (found via IIS Manager):

```<code><rewrite>
  <allowedServerVariables>
    <add name="HTTP_HOST" />
  </allowedServerVariables>
  <globalRules />
  <outboundRules />
  <providers />
  <rewriteMaps />
  <rules />
</rewrite>
</code>```

Failed Request Tracking:

Testing

If I create a test rule to prove the HTTP_HOST is being altered, it correctly uses the HTTP_HOST data set via the X-CF-ORIGIN header:

```<code><rule name="test" stopProcessing="true">
  <match url=".*" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
    <add input="{HTTP_X_CF_ORIGIN}" pattern=".+" />
    <add input="{HTTP_HOST}" pattern="(.+)" />
  </conditions>
  <action type="Redirect" url="http://some-site.com/{C:1}" redirectType="Temporary" />
</rule>
</code>```

Please help - what have we missed?

答:
I have found that Azure doesn't like setting the HTTP_HOST server variable. It works correctly if you use the HTTP_DISGUISED_HOST

Change this line in the rewrite rule:

```<code><set name="HTTP_HOST" value="{C:1}" />
</code>```

to this:

```<code><set name="HTTP_DISGUISED_HOST" value="{C:1}" />
</code>```

Change this line in the applicationHost.xdt:

```<code><add name="HTTP_HOST" xdt:Transform="InsertIfMissing" />
</code>```

to this:

```<code><add name="HTTP_DISGUISED_HOST" xdt:Transform="InsertIfMissing" />
</code>```

Body:
We are trying to rewrite the "host" header given a header of "X-CF-ORIGIN" - this works locally, however, in the app service, all logging indicates it has worked but we don't seem to see the effect.

We expect to get a 500 error for an incorrect HOST header, however, the site resolves as if the host header has not been changed.

Also, our XDT transform indicates it has worked (see below).

This was initially raised on Kudu Github but have been directed to here for Azure App Service IIS questions.

A code example:
https://github.com/Workshop2/webforms-host-header-rewrite-spike

Live example:
http://webforms-fun.azurewebsites.net/   with XDT transform

Our rewrite rule:

<rule name="CDN Host Header Rewrite" stopProcessing="false">
  <match url=".*" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
    <add input="{HTTP_X_CF_ORIGIN}" pattern="(.+)" />
  </conditions>
  <serverVariables>
    <set name="HTTP_HOST" value="{C:1}" />
  </serverVariables>
  <action type="None" />
</rule>

Our XDT Transform:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.webServer>
        <rewrite>
            <allowedServerVariables>
            <add name="HTTP_HOST" xdt:Transform="InsertIfMissing" />
            </allowedServerVariables>
        </rewrite>
    </system.webServer>
</configuration>

applicationHost (found via IIS Manager):

<rewrite>
  <allowedServerVariables>
    <add name="HTTP_HOST" />
  </allowedServerVariables>
  <globalRules />
  <outboundRules />
  <providers />
  <rewriteMaps />
  <rules />
</rewrite>

Failed Request Tracking:

Testing

If I create a test rule to prove the HTTP_HOST is being altered, it correctly uses the HTTP_HOST data set via the X-CF-ORIGIN header:

<rule name="test" stopProcessing="true">
  <match url=".*" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
    <add input="{HTTP_X_CF_ORIGIN}" pattern=".+" />
    <add input="{HTTP_HOST}" pattern="(.+)" />
  </conditions>
  <action type="Redirect" url="http://some-site.com/{C:1}" redirectType="Temporary" />
</rule>

Please help - what have we missed?

Body:
I have found that Azure doesn't like setting the HTTP_HOST server variable. It works correctly if you use the HTTP_DISGUISED_HOST

Change this line in the rewrite rule:

<set name="HTTP_HOST" value="{C:1}" />

to this:

<set name="HTTP_DISGUISED_HOST" value="{C:1}" />

Change this line in the applicationHost.xdt:

<add name="HTTP_HOST" xdt:Transform="InsertIfMissing" />

to this:

<add name="HTTP_DISGUISED_HOST" xdt:Transform="InsertIfMissing" />


问:
webpack replace only one file in library (bootstrap)
In project used angular 2 + webpack + bootstrap

I want use custom theme for bootstrap - replace node_modules/../bootstrap.css with ./Content/bootstrap.min.css

I add alias for that

alias: {
            'bootstrap/dist/css/bootstrap.css': './Content/bootstrap.min.css',
        }
```

<p>but have errors</p>

<blockquote>
```Can't resolve '../fonts/glyphicons-halflings-regular.eot' in '\Content'
 @ ./Content/bootstrap.min.css
```

How I can replace a file but not change the folder for depend resources

example

glyphicons-halflings-regular.eot must be searched in \node_modules not in Content

答:
Maybe another alias that says: </p>

```<code>'./Content/fonts': 'node_modules/bootstrap/dist/fonts'
</code>```

<p>Seems a bit hacky, but maybe give it a try. </p>

Body:
In project used angular 2 + webpack + bootstrap

I want use custom theme for bootstrap - replace node_modules/../bootstrap.css with ./Content/bootstrap.min.css

I add alias for that

alias: {
            'bootstrap/dist/css/bootstrap.css': './Content/bootstrap.min.css',
        }

but have errors

Can't resolve '../fonts/glyphicons-halflings-regular.eot' in '\Content'
 @ ./Content/bootstrap.min.css

How I can replace a file but not change the folder for depend resources

example

glyphicons-halflings-regular.eot must be searched in \node_modules not in Content

Body:
Maybe another alias that says:

'./Content/fonts': 'node_modules/bootstrap/dist/fonts'

Seems a bit hacky, but maybe give it a try.


问:
Custom function to create an index of results
I’m trying to create a function which creates an index (starting at 100) and then adjust this index according to the results of investments. So, in a nutshell, if the first investment gives an profit of 5%, then the index will stand 105, if the second result is -7%, then the index stands at 97.65. In this question when I use the word "index", I'm not referring to the index function of the zoo package.

Besides creating this index, my goal is also to create an function which can be applied to various subsets of my complete data set (i.e. with the use of sapply and it's friends).

Here’s the function which I have so far (data at end of this question):

```<code>CalculateIndex <- function(x){
    totalAccount <- accountValueStart
    if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){
        indexedValues <- 100 + ( 100 *((((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100))
        # Update the accountvalue
        totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    else{ # the value is not the first
        indexedValues <- c(indexedValues,
                indexedValues[-1] + (indexedValues[-1] *(((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100)
                )
            # Update the accountvalue
            totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    return(indexedValues)
}
</code>```

In words the function does (read: is intended to do) the following:
If the value is the first, use 100 as an starting point for the index. If the value is not the first, use the previous calculated index value as the starting point for calculating the new index value. Besides this, the function also takes the weight of the individual result (compared with the totalAccount value) into account.

The problem:
Using this CalculateIndex function on the theData data frame gives the following incorrect output:

```<code>> CalculateIndex(theData)
 [1]  99.97901  99.94180  99.65632 101.88689 100.89309  98.92878 102.02911 100.49159  98.52955 102.02243  98.43655 100.76502  99.34869 100.76401 101.18014  99.75136  97.90130
[18] 100.39935  99.81311 101.34961
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used
</code>```

Edit:
Wow, I already got an vote down, though I thought my question was already too long. Sorry, I thought/think the problem lay inside my loop, so I didn't want to bore you with the details, which I thought would only give less answers. Sorry, misjudgement on my part.

The problem is, with the above output from CalculateIndex, that the results are wildly different from Excel. Even though this could be resulting from rounding errors (as Joris mentions below), I doubt it. In comparison with the Excel results, the R results differ quite some:

```<code>R output    Excel calculate values
99,9790085700   99,97900857
99,9418035700   99,92081189
99,6563228600   99,57713687
101,8868850000  101,4639947
100,8930864300  102,3570786
98,9287771400   101,2858564
102,0291071400  103,3149664
100,4915864300  103,806556
98,5295542900   102,3361186
102,0224285700  104,3585552
98,4365550000   102,795089
100,7650171400  103,5601228
99,3486857100   102,9087897
100,7640057100  103,6728077
101,1801400000  104,8529634
99,7513600000   104,6043164
97,9013000000   102,5055298
100,3993485700  102,9048999
99,8131085700   102,7179995
101,3496071400  104,0676555
</code>```

I think it would be fair to say that the difference in output isn't the result of R versus Excel problems, but more an error in my function. So, let's focus on the function.

The manual calculation of the function
The function uses different variables:

Size.Units.; this is the number of units which are bought at the EntryPrice.

EntryPrice: the price at which the stocks are bought,

TradeResult.Percent.: the percentage gain or loss resulting from the investment,

TradeResult.Currency.: the currency value ($) of the gain or loss resulting from the investment,

These variables are used in the following section of the function:

```<code>100 + ( 100 *((((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100))
</code>```

and

```<code>indexedValues[-1] + (indexedValues[-1] *(((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100)
</code>```

Both of the formula's are essentially the same, with the difference that the the first starts at 100, and the second uses the previous value to calculate the new indexed value.

The formula can be broken down in different steps:

First, x$Size.Units. * x$EntryPrice determines the total position that was taken, in the sense that buying 100 shares at an price of 48.98 gives an position of $4898.

The resulting total position is then divided by the total account size (i.e. totalAccount). This is needed to correct the impact of one position relative to the complete portfolio. For example, if our 100 shares bought at 48.98 drop 10 percent, the calculated index (i.e. the CalculateIndex function) doesn't have to drop 10%, because off course not all the money in totalAccount is invested in one stock. So, by dividing the total position by the totalAccount we get an ratio which tells us how much money is invested. For example, the position with the size of 4898 dollar (on a total account of 14000) results in a total account loss of 3.49% if the stock drops 10%. (i.e. 4898 / 14000 = 0.349857. 0.349857 * 10% = 3.49857%)

This ratio (of invested amount versus total amount) is then in the formula multiplied with x$TradeResult.Percent., so to get the percentage impact on the total account (see calculation example in the previous paragraph).

As an last step, the percentage loss on the total account is applied to the index value (which starts at 100). In this case, the first investment in 100 shares bought at 48.89 dollar let's the index drop from it starting point at 100 to 99.97901, reflecting the losing trade's impact on the total account.

End of Edit

Stripping the function clean and then adding a part of the formula at a time, so to uncover the error, I came to the following step where the error seems to reside:

```<code>CalculateIndex <- function(x){
    totalAccount <- accountValueStart
    if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){
        indexedValues <- totalAccount
        # Update the accountvalue
        totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    else{ # the value is not the first
        indexedValues <- c(indexedValues, totalAccount)
            # Update the accountvalue
            totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    return(indexedValues)
}
> CalculateIndex(theData)
[1] 14000
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used
</code>```

So, it seems that if I just use the totalAccount variable, the function doesn’t get updated correctly. This seems to suggest there is some error with the basics of the if else statement, because it only outputs the first value.

If I remove the else statement from the function, I do get values for each of the rows in theData. However, these are then wrongly calculated. So, it seems to me that there is some error in how this function updates the totalAccount variable. I don’t see where I made an error, so any suggestion would be highly appreciated. What am I doing wrong?

The Data

Here’s what my data looks like:

```<code>> theData
   Size.Units. EntryPrice TradeResult.Percent. TradeResult.Currency.
1          100      48.98                -0.06                    -3
11         100      32.59                -0.25                    -8
12         100      32.51                -1.48                   -48
2          100      49.01                 5.39                   264
13         100      32.99                 3.79                   125
14         100      34.24                -4.38                  -150
3          100      51.65                 5.50                   284
4          100      48.81                 1.41                    69
15         100      35.74                -5.76                  -206
5          100      49.50                 5.72                   283
6          100      46.67                -4.69                  -219
16         100      33.68                 3.18                   107
7          100      44.48                -2.05                   -91
17         100      32.61                 3.28                   107
8          100      45.39                 3.64                   165
9          100      47.04                -0.74                   -35
10         100      47.39                -6.20                  -294
18         100      33.68                 1.66                    56
19         100      33.12                -0.79                   -26
20         100      32.86                 5.75                   189

theData <- structure(list(X = c(1L, 11L, 12L, 2L, 13L, 14L, 3L, 4L, 15L,
    5L, 6L, 16L, 7L, 17L, 8L, 9L, 10L, 18L, 19L, 20L), Size.Units. = c(100L,
    100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L,
    100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L), EntryPrice = c(48.98,
    32.59, 32.51, 49.01, 32.99, 34.24, 51.65, 48.81, 35.74, 49.5,
    46.67, 33.68, 44.48, 32.61, 45.39, 47.04, 47.39, 33.68, 33.12,
    32.86), TradeResult.Percent. = c(-0.06, -0.25, -1.48, 5.39, 3.79,
    -4.38, 5.5, 1.41, -5.76, 5.72, -4.69, 3.18, -2.05, 3.28, 3.64,
    -0.74, -6.2, 1.66, -0.79, 5.75), TradeResult.Currency. = c(-3L,
    -8L, -48L, 264L, 125L, -150L, 284L, 69L, -206L, 283L, -219L,
    107L, -91L, 107L, 165L, -35L, -294L, 56L, -26L, 189L)), .Names = c("X",
    "Size.Units.", "EntryPrice", "TradeResult.Percent.", "TradeResult.Currency."
    ), class = "data.frame", row.names = c(NA, -20L))

# Set the account start @ 14000
> accountValueStart <- 14000
</code>```

答:
The warning message is coming from this line:

```<code>if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){
</code>```

It is easy to see why; x$TradeResult.Currency is a vector and thus the comparison with head(x$TradeResult.Currency., n = 1) yields a vector of logicals. (By the way, why not x$TradeResult.Currency[1] instead of the head() call?). if() requires a single logical not a vector of logicals, and that is what the warning is about. ifelse() is useful if you want to do one of two things depending upon a condition that gives a vector of logicals.

In effect, what you are doing is only entering the if() part of the statement and it gets executed once only, because the first element of x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1) is TRUE and R ignores the others.

```<code>> if(c(TRUE, FALSE)) {
+ print("Hi")
+ } else {
+ print("Bye")
+ }
[1] "Hi"
Warning message:
In if (c(TRUE, FALSE)) { :
  the condition has length > 1 and only the first element will be used
> ifelse(c(TRUE, FALSE), print("Hi"), print("Bye"))
[1] "Hi"
[1] "Bye"
[1] "Hi"  "Bye"
</code>```

As to solving your real problem:

```<code>CalculateIndex2 <- function(x, value, start = 100) {
    rowSeq <- seq_len(NROW(x))
    totalAc <- cumsum(c(value, x$TradeResult.Currency.))[rowSeq]
    idx <- numeric(length = nrow(x))
    interm <- (((x$Size.Units. * x$EntryPrice) / totalAc) *
               x$TradeResult.Percent.) / 100
    for(i in rowSeq) {
        idx[i] <- start + (start * interm[i])
        start <- idx[i]
    }
    idx
}
</code>```

which when used on theData gives:

```<code>> CalculateIndex2(theData, 14000)
 [1]  99.97901  99.92081  99.57714 101.46399 102.35708 101.28586 103.31497
 [8] 103.80656 102.33612 104.35856 102.79509 103.56012 102.90879 103.67281
[15] 104.85296 104.60432 102.50553 102.90490 102.71800 104.06766
</code>```

What you want is a recursive function (IIRC); the current index is some function of the previous index. These are hard to solve in a vectorised way in R, hence the loop.

ContentLicense: CC BY-SA 2.5

Body:
I’m trying to create a function which creates an index (starting at 100) and then adjust this index according to the results of investments. So, in a nutshell, if the first investment gives an profit of 5%, then the index will stand 105, if the second result is -7%, then the index stands at 97.65. In this question when I use the word "index", I'm not referring to the index function of the zoo package.

Besides creating this index, my goal is also to create an function which can be applied to various subsets of my complete data set (i.e. with the use of sapply and it's friends).

Here’s the function which I have so far (data at end of this question):

CalculateIndex <- function(x){
    totalAccount <- accountValueStart
    if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){
        indexedValues <- 100 + ( 100 *((((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100))
        # Update the accountvalue
        totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    else{ # the value is not the first
        indexedValues <- c(indexedValues,
                indexedValues[-1] + (indexedValues[-1] *(((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100)
                )
            # Update the accountvalue
            totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    return(indexedValues)
}

In words the function does (read: is intended to do) the following:
If the value is the first, use 100 as an starting point for the index. If the value is not the first, use the previous calculated index value as the starting point for calculating the new index value. Besides this, the function also takes the weight of the individual result (compared with the totalAccount value) into account.

The problem:
Using this CalculateIndex function on the theData data frame gives the following incorrect output:

> CalculateIndex(theData)
 [1]  99.97901  99.94180  99.65632 101.88689 100.89309  98.92878 102.02911 100.49159  98.52955 102.02243  98.43655 100.76502  99.34869 100.76401 101.18014  99.75136  97.90130
[18] 100.39935  99.81311 101.34961
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used

Edit:
Wow, I already got an vote down, though I thought my question was already too long. Sorry, I thought/think the problem lay inside my loop, so I didn't want to bore you with the details, which I thought would only give less answers. Sorry, misjudgement on my part.

The problem is, with the above output from CalculateIndex, that the results are wildly different from Excel. Even though this could be resulting from rounding errors (as Joris mentions below), I doubt it. In comparison with the Excel results, the R results differ quite some:

R output    Excel calculate values
99,9790085700   99,97900857
99,9418035700   99,92081189
99,6563228600   99,57713687
101,8868850000  101,4639947
100,8930864300  102,3570786
98,9287771400   101,2858564
102,0291071400  103,3149664
100,4915864300  103,806556
98,5295542900   102,3361186
102,0224285700  104,3585552
98,4365550000   102,795089
100,7650171400  103,5601228
99,3486857100   102,9087897
100,7640057100  103,6728077
101,1801400000  104,8529634
99,7513600000   104,6043164
97,9013000000   102,5055298
100,3993485700  102,9048999
99,8131085700   102,7179995
101,3496071400  104,0676555

I think it would be fair to say that the difference in output isn't the result of R versus Excel problems, but more an error in my function. So, let's focus on the function.

The manual calculation of the function
The function uses different variables:

Size.Units.; this is the number of units which are bought at the EntryPrice.

EntryPrice: the price at which the stocks are bought,

TradeResult.Percent.: the percentage gain or loss resulting from the investment,

TradeResult.Currency.: the currency value ($) of the gain or loss resulting from the investment,

These variables are used in the following section of the function:

100 + ( 100 *((((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100))

and

indexedValues[-1] + (indexedValues[-1] *(((x$Size.Units. * x$EntryPrice) / totalAccount) * x$TradeResult.Percent.) / 100)

Both of the formula's are essentially the same, with the difference that the the first starts at 100, and the second uses the previous value to calculate the new indexed value.

The formula can be broken down in different steps:

First, x$Size.Units. * x$EntryPrice determines the total position that was taken, in the sense that buying 100 shares at an price of 48.98 gives an position of $4898.

The resulting total position is then divided by the total account size (i.e. totalAccount). This is needed to correct the impact of one position relative to the complete portfolio. For example, if our 100 shares bought at 48.98 drop 10 percent, the calculated index (i.e. the CalculateIndex function) doesn't have to drop 10%, because off course not all the money in totalAccount is invested in one stock. So, by dividing the total position by the totalAccount we get an ratio which tells us how much money is invested. For example, the position with the size of 4898 dollar (on a total account of 14000) results in a total account loss of 3.49% if the stock drops 10%. (i.e. 4898 / 14000 = 0.349857. 0.349857 * 10% = 3.49857%)

This ratio (of invested amount versus total amount) is then in the formula multiplied with x$TradeResult.Percent., so to get the percentage impact on the total account (see calculation example in the previous paragraph).

As an last step, the percentage loss on the total account is applied to the index value (which starts at 100). In this case, the first investment in 100 shares bought at 48.89 dollar let's the index drop from it starting point at 100 to 99.97901, reflecting the losing trade's impact on the total account.

End of Edit

Stripping the function clean and then adding a part of the formula at a time, so to uncover the error, I came to the following step where the error seems to reside:

CalculateIndex <- function(x){
    totalAccount <- accountValueStart
    if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){
        indexedValues <- totalAccount
        # Update the accountvalue
        totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    else{ # the value is not the first
        indexedValues <- c(indexedValues, totalAccount)
            # Update the accountvalue
            totalAccount <- totalAccount + x$TradeResult.Currency.
    }
    return(indexedValues)
}
> CalculateIndex(theData)
[1] 14000
Warning message:
In if (x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)) { :
  the condition has length > 1 and only the first element will be used

So, it seems that if I just use the totalAccount variable, the function doesn’t get updated correctly. This seems to suggest there is some error with the basics of the if else statement, because it only outputs the first value.

If I remove the else statement from the function, I do get values for each of the rows in theData. However, these are then wrongly calculated. So, it seems to me that there is some error in how this function updates the totalAccount variable. I don’t see where I made an error, so any suggestion would be highly appreciated. What am I doing wrong?

The Data

Here’s what my data looks like:

> theData
   Size.Units. EntryPrice TradeResult.Percent. TradeResult.Currency.
1          100      48.98                -0.06                    -3
11         100      32.59                -0.25                    -8
12         100      32.51                -1.48                   -48
2          100      49.01                 5.39                   264
13         100      32.99                 3.79                   125
14         100      34.24                -4.38                  -150
3          100      51.65                 5.50                   284
4          100      48.81                 1.41                    69
15         100      35.74                -5.76                  -206
5          100      49.50                 5.72                   283
6          100      46.67                -4.69                  -219
16         100      33.68                 3.18                   107
7          100      44.48                -2.05                   -91
17         100      32.61                 3.28                   107
8          100      45.39                 3.64                   165
9          100      47.04                -0.74                   -35
10         100      47.39                -6.20                  -294
18         100      33.68                 1.66                    56
19         100      33.12                -0.79                   -26
20         100      32.86                 5.75                   189

theData <- structure(list(X = c(1L, 11L, 12L, 2L, 13L, 14L, 3L, 4L, 15L,
    5L, 6L, 16L, 7L, 17L, 8L, 9L, 10L, 18L, 19L, 20L), Size.Units. = c(100L,
    100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L,
    100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L), EntryPrice = c(48.98,
    32.59, 32.51, 49.01, 32.99, 34.24, 51.65, 48.81, 35.74, 49.5,
    46.67, 33.68, 44.48, 32.61, 45.39, 47.04, 47.39, 33.68, 33.12,
    32.86), TradeResult.Percent. = c(-0.06, -0.25, -1.48, 5.39, 3.79,
    -4.38, 5.5, 1.41, -5.76, 5.72, -4.69, 3.18, -2.05, 3.28, 3.64,
    -0.74, -6.2, 1.66, -0.79, 5.75), TradeResult.Currency. = c(-3L,
    -8L, -48L, 264L, 125L, -150L, 284L, 69L, -206L, 283L, -219L,
    107L, -91L, 107L, 165L, -35L, -294L, 56L, -26L, 189L)), .Names = c("X",
    "Size.Units.", "EntryPrice", "TradeResult.Percent.", "TradeResult.Currency."
    ), class = "data.frame", row.names = c(NA, -20L))

# Set the account start @ 14000
> accountValueStart <- 14000

Body:
The warning message is coming from this line:

if(x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1)){

It is easy to see why; x$TradeResult.Currency is a vector and thus the comparison with head(x$TradeResult.Currency., n = 1) yields a vector of logicals. (By the way, why not x$TradeResult.Currency[1] instead of the head() call?). if() requires a single logical not a vector of logicals, and that is what the warning is about. ifelse() is useful if you want to do one of two things depending upon a condition that gives a vector of logicals.

In effect, what you are doing is only entering the if() part of the statement and it gets executed once only, because the first element of x$TradeResult.Currency == head(x$TradeResult.Currency., n = 1) is TRUE and R ignores the others.

> if(c(TRUE, FALSE)) {
+ print("Hi")
+ } else {
+ print("Bye")
+ }
[1] "Hi"
Warning message:
In if (c(TRUE, FALSE)) { :
  the condition has length > 1 and only the first element will be used
> ifelse(c(TRUE, FALSE), print("Hi"), print("Bye"))
[1] "Hi"
[1] "Bye"
[1] "Hi"  "Bye"

As to solving your real problem:

CalculateIndex2 <- function(x, value, start = 100) {
    rowSeq <- seq_len(NROW(x))
    totalAc <- cumsum(c(value, x$TradeResult.Currency.))[rowSeq]
    idx <- numeric(length = nrow(x))
    interm <- (((x$Size.Units. * x$EntryPrice) / totalAc) *
               x$TradeResult.Percent.) / 100
    for(i in rowSeq) {
        idx[i] <- start + (start * interm[i])
        start <- idx[i]
    }
    idx
}

which when used on theData gives:

> CalculateIndex2(theData, 14000)
 [1]  99.97901  99.92081  99.57714 101.46399 102.35708 101.28586 103.31497
 [8] 103.80656 102.33612 104.35856 102.79509 103.56012 102.90879 103.67281
[15] 104.85296 104.60432 102.50553 102.90490 102.71800 104.06766

What you want is a recursive function (IIRC); the current index is some function of the previous index. These are hard to solve in a vectorised way in R, hence the loop.


问:
"glDrawElements: attempt to access out of range vertices in attribute 3" using Mapzen vector tiles
Suddenly I run into lots of these warnings in the console when using mapzen vector tiles with mapbox-gl:

[.Offscreen-For-WebGL-0x2c91ee109c00]GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 3

Before it was working fine.

答: Noticing it happened during zooming from level 15 and higher; and also that I had no warnings when using a simplified stylesheet I found it to be that the stylesheet requirements have altered. In my case I had a filtervalue in one of my stylesheetlayers of yes which in new version should be true. For more details how to update your stylesheet you could use this.


问:
Unit test does not pass when error is thrown
I have the following JS class:

```<code>class MyDispatcher {

  subscribe(eventName, handler) {

    if (typeof eventName !== 'string') {
        throw new Error('eventName must be a string');
    }

   //some other code
  }

}
</code>```

I have this Jest unit test for it:

```<code>test('Non string event fails', () => {
    expect(MyDispatcher.subscribe(3, 'myHandler')).toThrow();
});
</code>```

The problem is that when I run the test, it fails with this error:

```<code>● myDispatcher › Non string event fails

    eventName must be a string

      at MyDispatcher.subscribe (src/modules/MyDispatcher.js:10:7)
      at Object.<anonymous> (src/modules/__tests__/MyDispatcherTest.js:26:31)
</code>```

I can't understand why the test fails. The method throws an error, which is exactly what I'm testing for. Therefore, the test should pass, right?

I tried also this test:

```<code>expect(MyDispatcher.subscribe(3, 'myHandler')).toThrowError('eventName must be a string');
</code>```

and this test:

```<code>expect(MyDispatcher.subscribe(3, 'myHandler')).toThrow(new Error('eventName must be a string'));
</code>```

However, they both fail with the same error message.

Any idea why these tests fail?

答:
The MyDispatcher.subscribe(3, 'myHandler') function call is throwing an exception before even executing the actual test, replace

```<code>expect(MyDispatcher.subscribe(3, 'myHandler')).toThrow();
</code>```

with

```<code>expect(() => MyDispatcher.subscribe(3, 'myHandler')).toThrow();
</code>```

Body:
I have the following JS class:

class MyDispatcher {

  subscribe(eventName, handler) {

    if (typeof eventName !== 'string') {
        throw new Error('eventName must be a string');
    }

   //some other code
  }

}

I have this Jest unit test for it:

test('Non string event fails', () => {
    expect(MyDispatcher.subscribe(3, 'myHandler')).toThrow();
});

The problem is that when I run the test, it fails with this error:

● myDispatcher › Non string event fails

    eventName must be a string

      at MyDispatcher.subscribe (src/modules/MyDispatcher.js:10:7)
      at Object.<anonymous> (src/modules/__tests__/MyDispatcherTest.js:26:31)

I can't understand why the test fails. The method throws an error, which is exactly what I'm testing for. Therefore, the test should pass, right?

I tried also this test:

expect(MyDispatcher.subscribe(3, 'myHandler')).toThrowError('eventName must be a string');

and this test:

expect(MyDispatcher.subscribe(3, 'myHandler')).toThrow(new Error('eventName must be a string'));

However, they both fail with the same error message.

Any idea why these tests fail?

Body:
The MyDispatcher.subscribe(3, 'myHandler') function call is throwing an exception before even executing the actual test, replace

expect(MyDispatcher.subscribe(3, 'myHandler')).toThrow();

with

expect(() => MyDispatcher.subscribe(3, 'myHandler')).toThrow();


问:
webpack-dev-server 'Cannot GET /'
I have the following webpack config:

```<code>module.exports = {
  entry: "./src/index.js",
  output: {
    path: __dirname + '/dist',
    // publicPath: __dirname + '/dist/',
    filename: "bundle.js"
  },
  devServer: {
    contentBase: "/dist",
    hot: true,
  }
}
</code>```

My understanding is that contentBase tells the webpack dev server where to serve files from.  So if I go to localhost:8080/test.txt, under this configuration the file at myProjectRoot/dist/test/txt will be sent by the server to the browser.  Is that correct? What does output.publicPath have to do with all that?

Now I have index.html and bundle.js sitting in myProjectRoot/dist/ right now.  (although I think bundle.js is a bit of a confusing factor because its actually the in memory bundle that is returned by webpack-dev-server but nonetheless).  Given my previous paragraph, I'd expect the server to return index.html to the browser.  Since the contentBase is /dist and index.html's path on disk is ./dist/index.html.

But instead I see: Cannot GET /

So again, if I go to http://localhost:8080/bundle.js I see the full javascript bundle (up to date with what was last saved in my text editor).  But then /index.html wins up with Cannot GET /?

What am I missing?

答:
You need to set relative or absolute path in devServer.contentBase.

webpack-dev-server do not use your project as root directory, so it does not resolve /dist to folder within your project directory.

Try this:

```<code>module.exports = {
  entry: "./src/index.js",
  output: {
    path: __dirname + '/dist',
    filename: "bundle.js"
  },
  devServer: {
    contentBase: __dirname + '/dist'
    // contentBase: 'dist'
  }
}
</code>```

Title: webpack-dev-server 'Cannot GET /'

Body:
I have the following webpack config:

module.exports = {
  entry: "./src/index.js",
  output: {
    path: __dirname + '/dist',
    // publicPath: __dirname + '/dist/',
    filename: "bundle.js"
  },
  devServer: {
    contentBase: "/dist",
    hot: true,
  }
}

My understanding is that contentBase tells the webpack dev server where to serve files from.  So if I go to localhost:8080/test.txt, under this configuration the file at myProjectRoot/dist/test/txt will be sent by the server to the browser.  Is that correct? What does output.publicPath have to do with all that?

Now I have index.html and bundle.js sitting in myProjectRoot/dist/ right now.  (although I think bundle.js is a bit of a confusing factor because its actually the in memory bundle that is returned by webpack-dev-server but nonetheless).  Given my previous paragraph, I'd expect the server to return index.html to the browser.  Since the contentBase is /dist and index.html's path on disk is ./dist/index.html.

But instead I see: Cannot GET /

So again, if I go to http://localhost:8080/bundle.js I see the full javascript bundle (up to date with what was last saved in my text editor).  But then /index.html wins up with Cannot GET /?

What am I missing?

Body:
You need to set relative or absolute path in devServer.contentBase.

webpack-dev-server do not use your project as root directory, so it does not resolve /dist to folder within your project directory.

Try this:

module.exports = {
  entry: "./src/index.js",
  output: {
    path: __dirname + '/dist',
    filename: "bundle.js"
  },
  devServer: {
    contentBase: __dirname + '/dist'
    // contentBase: 'dist'
  }
}


问:
Swift 4: "Non-nominal type 'T' does not support explicit initialization"
I'm using this extension in order to retrieve HTTP headers within a urlSession callback:

```<code>extension HTTPURLResponse {

    func get(_ header: String) -> String? {
        let keyValues = allHeaderFields.map { (String(describing: $0.key).lowercased(), String(describing: $0.value)) }

        if let headerValue = keyValues.filter({ $0.0 == header.lowercased() }).first {
            return headerValue.1
        }
        return nil
    }

}
</code>```

This works well and allows me to retrieve header elements like so:

```<code>    if let metaInt = httpResponse.get("icy-metaint") {
        self.icyMetaInt = Int(metaInt)
    }
</code>```

Now I wanted it to make a little bit more elegant by introducing a generic function:

```<code>func getHeader<T>(_ httpResponse: HTTPURLResponse, _ headerName: String) -> T? {
        guard let element = httpResponse.get(headerName) else {
            return nil
        }
        return T(element)
}
</code>```

The intention is to use statements like this:

```<code>self.icyMetaInt = getHeader(httpResponse, "icy-metaint")
</code>```

I believe something like that would work in C# or so. But the Swift compiler complains:

Non-nominal type 'T' does not support explicit initialization

for

```<code>return T(element)
</code>```

Even though if I use

```<code>return T.init(element)
</code>```

Is there any chance to achieve what I'm having in mind?

EDIT: Added T? (must have been lost while editing)

答:
This happens because the compiler doesn't know which initializer it is supposed call, because what you are doing is simply too general, as the error states.
What you are trying to achieve can be done, but the implementation depends on what you are achieve.

In short, if you want to be able to initialize a lot of different types, be it primitives or objects, you should define a new protocol, extend each type to implement this protocol as you see fit and have the T Type restricted to this protocol.

Example:

```<code>protocol HTTPHeaderProtocol {
    init(_ headerProtocolString: String?)
}

class MyCustomObject: HTTPHeaderProtocol {
    var myString = ""
    required init(_ headerProtocolString: String?) {
        self.myString = headerProtocolString ?? ""
    }

}

extension String: HTTPHeaderProtocol {
    init(_ headerProtocolString: String?) {
        self.init(headerProtocolString)
    }
}

extension Int: HTTPHeaderProtocol {
    init(_ headerProtocolString: String?) {
        self.init(headerProtocolString)
    }
}

extension HTTPURLResponse {

    func get(_ header: String) -> String? {
        let keyValues = allHeaderFields.map { (String(describing: $0.key).lowercased(), String(describing: $0.value)) }

        if let headerValue = keyValues.filter({ $0.0 == header.lowercased() }).first {
            return headerValue.1
        }
        return nil
    }
    func getHeader<T:HTTPHeaderProtocol>(_ httpResponse: HTTPURLResponse, _ headerName: String) -> T? {
        guard let element = httpResponse.get(headerName) else {
            return nil
        }
        return T(element)
    }
}
</code>```

This will work, hope that helps:)

Body:
I'm using this extension in order to retrieve HTTP headers within a urlSession callback:

extension HTTPURLResponse {

    func get(_ header: String) -> String? {
        let keyValues = allHeaderFields.map { (String(describing: $0.key).lowercased(), String(describing: $0.value)) }

        if let headerValue = keyValues.filter({ $0.0 == header.lowercased() }).first {
            return headerValue.1
        }
        return nil
    }

}

This works well and allows me to retrieve header elements like so:

    if let metaInt = httpResponse.get("icy-metaint") {
        self.icyMetaInt = Int(metaInt)
    }

Now I wanted it to make a little bit more elegant by introducing a generic function:

func getHeader<T>(_ httpResponse: HTTPURLResponse, _ headerName: String) -> T? {
        guard let element = httpResponse.get(headerName) else {
            return nil
        }
        return T(element)
}

The intention is to use statements like this:

self.icyMetaInt = getHeader(httpResponse, "icy-metaint")

I believe something like that would work in C# or so. But the Swift compiler complains:

Non-nominal type 'T' does not support explicit initialization

for

return T(element)

Even though if I use

return T.init(element)

Is there any chance to achieve what I'm having in mind?

EDIT: Added T? (must have been lost while editing)

Body:
This happens because the compiler doesn't know which initializer it is supposed call, because what you are doing is simply too general, as the error states.
What you are trying to achieve can be done, but the implementation depends on what you are achieve.

In short, if you want to be able to initialize a lot of different types, be it primitives or objects, you should define a new protocol, extend each type to implement this protocol as you see fit and have the T Type restricted to this protocol.

Example:

protocol HTTPHeaderProtocol {
    init(_ headerProtocolString: String?)
}

class MyCustomObject: HTTPHeaderProtocol {
    var myString = ""
    required init(_ headerProtocolString: String?) {
        self.myString = headerProtocolString ?? ""
    }

}

extension String: HTTPHeaderProtocol {
    init(_ headerProtocolString: String?) {
        self.init(headerProtocolString)
    }
}

extension Int: HTTPHeaderProtocol {
    init(_ headerProtocolString: String?) {
        self.init(headerProtocolString)
    }
}

extension HTTPURLResponse {

    func get(_ header: String) -> String? {
        let keyValues = allHeaderFields.map { (String(describing: $0.key).lowercased(), String(describing: $0.value)) }

        if let headerValue = keyValues.filter({ $0.0 == header.lowercased() }).first {
            return headerValue.1
        }
        return nil
    }
    func getHeader<T:HTTPHeaderProtocol>(_ httpResponse: HTTPURLResponse, _ headerName: String) -> T? {
        guard let element = httpResponse.get(headerName) else {
            return nil
        }
        return T(element)
    }
}

This will work, hope that helps:)


问:
double quotes inside double quotes
i am writing the following connection string into web.config
but it giving me error.what is the correct way to write it?</p>

```<code><add name="stargaze_stargazeConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf";Integrated Security=True;User Instance=True"/>
</code>```

答:
Shouldn't it be like:</p>

```<code><add name="stargaze_stargazeConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=\"D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf\";Integrated Security=True;User Instance=True"/>
</code>```

Title: double quotes inside double quotes

Body:
i am writing the following connection string into web.config
but it giving me error.what is the correct way to write it?

<add name="stargaze_stargazeConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf";Integrated Security=True;User Instance=True"/>

Body:
Shouldn't it be like:

<add name="stargaze_stargazeConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=\"D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf\";Integrated Security=True;User Instance=True"/>


问:
Postgres: use function that returns a string in another function
I've a PostgreSQL function that returns a string. I want to use this function into another one but I obtain an error.

These are the sample functions, with get_some_string that returns text, and use_the_string where I want to call the previous one and store the result in a variable:

```<code>CREATE OR REPLACE FUNCTION public.get_some_string()

RETURNS text AS
$func$
DECLARE

BEGIN

  return 'mystring';

END
$func$ LANGUAGE plpgsql VOLATILE;

CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := select public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;
</code>```

If I run this query I obtain the error:

```<code>ERROR:  syntax error at or near "select"
LINE 24:   mytext := select public.get_some_string();
</code>```

What I'm doing wrong? How can I use the return value of the first function into the second one?

答:
The second one must be:

```<code>RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  select public.get_some_string() into mytext;

END
$func$ LANGUAGE plpgsql VOLATILE;
</code>```

or

```<code>mytext := (select public.get_some_string());
</code>```

or

```<code>mytext := public.get_some_string();
</code>```

Body:
I've a PostgreSQL function that returns a string. I want to use this function into another one but I obtain an error.

These are the sample functions, with get_some_string that returns text, and use_the_string where I want to call the previous one and store the result in a variable:

CREATE OR REPLACE FUNCTION public.get_some_string()

RETURNS text AS
$func$
DECLARE

BEGIN

  return 'mystring';

END
$func$ LANGUAGE plpgsql VOLATILE;

CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := select public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;

If I run this query I obtain the error:

ERROR:  syntax error at or near "select"
LINE 24:   mytext := select public.get_some_string();

What I'm doing wrong? How can I use the return value of the first function into the second one?

Body:
The second one must be:

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  select public.get_some_string() into mytext;

END
$func$ LANGUAGE plpgsql VOLATILE;

or

mytext := (select public.get_some_string());

or

mytext := public.get_some_string();


问:
wpml languages redirecting to default
I'm not too familiar with WPML and I site I am working on is using it. Everything was working fine, but now it has been noticed that when you go to a different language domain (e.g. www.domain.com/es/pagename) the site seems to rewrite the address to (www.domain.com/pagename) removing the language directory from the web address making some language pages unaccessable.
This is not occurring on all pages though.

I checked the htaccess file and the rewrite are their.

Any help or information on this would be great.

答: Problem ended up being 'Custom Permalinks' plugin. Doesn't play nice with WPML.</p>

Title: wpml languages redirecting to default


问:
HTML & CSS - Links doesn't work
I have made a very simple website using HTML and CSS, I have added a few links as well but only one of the links actually work. There are 4 links in total and only the one at the bottom of the code will work. Please help. This is my HTML code:

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {  margin: 0;  padding: 0;  border: 0;  font-size: 100%;  font: inherit;  vertical-align: baseline;}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}

ol,ul {
  list-style: none;
}

blockquote,q {
  quotes: none;
}

blockquote:before,blockquote:after,q:before,q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.nav {
  float: left;
}

.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}

.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}

.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}

.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}

html {
  box-sizing: border-box;
}

*,
*:before,*:after {
  box-sizing: inherit;
}

a {
  text-decoration: none;
}

.header {
  text-align: center;
}

.hemsidan {
  background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
  height: 1389px;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
  <div class="container">
    <div class="hemsidan"><img src="images/hemsidan.png" height="1389" width="1366" alt=""></div>
    <div class="centered">Centered</div>
    <nav>
      <ul class="nav">
        <li class="home">Home</li>
        <li class="faq">FAQ</li>
        <li class="shop">Shop</li>
        <li class="contact">Contact us</li>
      </ul>
    </nav>
  </div>
</header></code>```

I am very new to HTML and CSS so forgive me for the horrible coding, I just want the links to work.

答:
Your li elements are absolutely positioned over each other. This means that last li covers and blocks previous li-s.

Instead of absolute positioning and padding-rights do this:

```<code>.home {
    display: inline-block;
}
.faq{
    display: inline-block;
}
.shop{
    display: inline-block;
}
.contact{
    display: inline-block;
}
</code>```

(There is really no need for ul and li elements at all. Just put your links inside nav block and give them some padding)

Title: HTML & CSS - Links doesn't work

Body:
I have made a very simple website using HTML and CSS, I have added a few links as well but only one of the links actually work. There are 4 links in total and only the one at the bottom of the code will work. Please help. This is my HTML code:

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {  margin: 0;  padding: 0;  border: 0;  font-size: 100%;  font: inherit;  vertical-align: baseline;}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}

ol,ul {
  list-style: none;
}

blockquote,q {
  quotes: none;
}

blockquote:before,blockquote:after,q:before,q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.nav {
  float: left;
}

.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}

.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}

.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}

.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}

html {
  box-sizing: border-box;
}

*,
*:before,*:after {
  box-sizing: inherit;
}

a {
  text-decoration: none;
}

.header {
  text-align: center;
}

.hemsidan {
  background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
  height: 1389px;
  width: 100%;
}

Centered

Home

FAQ

Shop

Contact us

I am very new to HTML and CSS so forgive me for the horrible coding, I just want the links to work.

Body:
Your li elements are absolutely positioned over each other. This means that last li covers and blocks previous li-s.

Instead of absolute positioning and padding-rights do this:

.home {
    display: inline-block;
}
.faq{
    display: inline-block;
}
.shop{
    display: inline-block;
}
.contact{
    display: inline-block;
}

(There is really no need for ul and li elements at all. Just put your links inside nav block and give them some padding)


答:
Try to assign a random key prop to the img element every time it switches to another image. This forces react to recreate the element.

```<code>constructor () {
  super()
  this.state = {
    currentImageIndex: 0,
    imgKey: Math.random()
  }
}
changeImage () {
   this.setState((prevState) => {
     if (prevState.currentImageIndex) {
       return { currentImageIndex: 0, imgKey: Math.random() }
     } else {
       return { currentImageIndex: 1, imgKey: Math.random() }
     }
   })
 }

render () {
    return (
      <div>
        <img key={this.state.imgKey} src={this.props.images[this.state.currentImageIndex]} />
        <button onClick={this.changeImage.bind(this)}>
          change image
        </button>
      </div>
    )
  }
}
</code>```

Title: How do I invalidate the old images when request for a new one is initiated in React?

Body:
Have a look my code below, I have create a pen for it too: https://codepen.io/segmentationfaulter/pen/YEEaxK

The problem is that when I click on change image button, the old image stays there for a while until the new image is loaded. What I want is that the old image is invalidated straight away and empty space is shown for the new image. How can I achieve this in react? If you can't spot the issue, try opening it in private mode so that caching doesn't affect it.

const images = [
  'http://via.placeholder.com/550x550',
  'http://via.placeholder.com/750x750'
]

class MyImage extends React.Component {
  constructor() {
    super()
    this.state = {
      currentImageIndex: 0
    }
  }
  changeImage() {
    this.setState((prevState) => {
      if (prevState.currentImageIndex) {
        return {
          currentImageIndex: 0
        }
      } else {
        return {
          currentImageIndex: 1
        }
      }
    })
  }
  render() {
    return ( <
      div >
      <
      img src = {
        this.props.images[this.state.currentImageIndex]
      }
      /> <
      button onClick = {
        this.changeImage.bind(this)
      } >
      change image <
      /button> <
      /div>
    )
  }
}

ReactDOM.render( < MyImage images = {
      images
    }
    />, document.getElementById('root'))

img {
  display: block;
}

button {
  margin-top: 15px;
}

Body:
Try to assign a random key prop to the img element every time it switches to another image. This forces react to recreate the element.

constructor () {
  super()
  this.state = {
    currentImageIndex: 0,
    imgKey: Math.random()
  }
}
changeImage () {
   this.setState((prevState) => {
     if (prevState.currentImageIndex) {
       return { currentImageIndex: 0, imgKey: Math.random() }
     } else {
       return { currentImageIndex: 1, imgKey: Math.random() }
     }
   })
 }

render () {
    return (
      <div>
        <img key={this.state.imgKey} src={this.props.images[this.state.currentImageIndex]} />
        <button onClick={this.changeImage.bind(this)}>
          change image
        </button>
      </div>
    )
  }
}


问:
Detect Safari using jQuery
Though both are Webkit based browsers, Safari urlencodes quotation marks in the URL while Chrome does not.

Therefore I need to distinguish between these two in JS.

jQuery's browser detection docs mark "safari" as deprecated.

Is there a better method or do I just stick with the deprecated value for now?

答:
This will determine whether the browser is Safari or not.</p>

```<code>if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
    alert(its safari);
}else {
    alert('its not safari');
}
</code>```

Title: Detect Safari using jQuery

Body:
This will determine whether the browser is Safari or not.

if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
    alert(its safari);
}else {
    alert('its not safari');
}


问:
Swift4 - JSON Decodable issue with array (Cannot subscript a value)
I'm parsing weather JSON using Swift 4 Decodable, and i have an issue with array data. I'm think i may be a bit wrong with model (because there are bunch of decodable structs), please help.

JSON Data from the weather API:

```<code>{"coord":{"lon":-43.21,"lat":-22.9},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],
"base":"stations","main":{"temp":299.37,"pressure":1008,"humidity":51,"temp_min":296.15,"temp_max":302.15},
"visibility":10000,"wind":{"speed":4.1,"deg":320},"clouds":{"all":0},
"dt":1510909200,"sys":{"type":1,"id":4565,"message":0.0023,"country":"BR","sunrise":1510905615,
"sunset":1510953350},"id":3451190,"name":"Rio de Janeiro","cod":200}
</code>```

Model:

```<code>struct WeatherData:Decodable {
let coord:CoordDict?
let weather:[WeatherArr]?
let base: String?
let main:MainDict?
let visibility:Int?
let wind:WindDict?
let clouds:CloudsDict?
let dt:Int?
let sys:SysDict?
let id:Int?
let name:String?
let cod:Int?}

struct CoordDict:Decodable {
let lon: Double?
let lat: Double?}

struct WeatherArr:Decodable {
let id: Int?
let main:String?
let description:String?
let icon: String?}

struct MainDict:Decodable {
let temp:Double?
let pressure:Double?
let humidity:Int?
let temp_min:Double?
let temp_max:Double?
let sea_level:Double?
let grnd_level:Double?}

struct WindDict:Decodable {
let speed:Double?
let deg:Double?}

struct CloudsDict:Decodable {
let all: Int?}

struct SysDict:Decodable {
let type:Int?
let id:Int?
let message:Double?
let country:String?
let sunrise:Int?
let sunset:Int?}
</code>```

Parsing JSON data using JSONDecoder:

```<code>    let jsonUrlString = ("https://api.openweathermap.org/data/2.5/weather?lat=\(lat!)&lon=\(lon!)&APPID=\(apikey)")

    guard let url = URL(string: jsonUrlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, err) in

        //check err
        if err != nil {
            print("Error:\(String(describing: err))")
        }

        guard let data = data else { return }
        //do stuff

        do {

            let weatherData = try JSONDecoder().decode(WeatherData.self, from: data)

            print(weatherData.name, weatherData.weather)

   //Here i can't parse the weather Array, and get xcode error

     if let wArr = weatherData.weather! as? Array<AnyObject> {
                if let weatherIcon = wArr["icon"] {
                  icon = weatherIcon
                    }
                }
        } catch let jsonErr {
            print("Error:\(jsonErr)")
        }

        }.resume()//URLSession
</code>```

ERROR msg: Cannot subscript a value of type 'Array' with an index of type 'String'.

How can i fix this? How can i parse weather array elements?

答:
Declare weather in the WeatherData struct as non-optional. There is always a weather

```<code>let weather : [WeatherArr]
</code>```

Get the first item if the array and the icon

```<code>if let currentWeather = weatherData.weather.first {
   if let weatherIcon = currentWeather.icon  {
      print(weatherIcon)
   }
}
</code>```

Body:
I'm parsing weather JSON using Swift 4 Decodable, and i have an issue with array data. I'm think i may be a bit wrong with model (because there are bunch of decodable structs), please help.

JSON Data from the weather API:

{"coord":{"lon":-43.21,"lat":-22.9},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],
"base":"stations","main":{"temp":299.37,"pressure":1008,"humidity":51,"temp_min":296.15,"temp_max":302.15},
"visibility":10000,"wind":{"speed":4.1,"deg":320},"clouds":{"all":0},
"dt":1510909200,"sys":{"type":1,"id":4565,"message":0.0023,"country":"BR","sunrise":1510905615,
"sunset":1510953350},"id":3451190,"name":"Rio de Janeiro","cod":200}

Model:

struct WeatherData:Decodable {
let coord:CoordDict?
let weather:[WeatherArr]?
let base: String?
let main:MainDict?
let visibility:Int?
let wind:WindDict?
let clouds:CloudsDict?
let dt:Int?
let sys:SysDict?
let id:Int?
let name:String?
let cod:Int?}

struct CoordDict:Decodable {
let lon: Double?
let lat: Double?}

struct WeatherArr:Decodable {
let id: Int?
let main:String?
let description:String?
let icon: String?}

struct MainDict:Decodable {
let temp:Double?
let pressure:Double?
let humidity:Int?
let temp_min:Double?
let temp_max:Double?
let sea_level:Double?
let grnd_level:Double?}

struct WindDict:Decodable {
let speed:Double?
let deg:Double?}

struct CloudsDict:Decodable {
let all: Int?}

struct SysDict:Decodable {
let type:Int?
let id:Int?
let message:Double?
let country:String?
let sunrise:Int?
let sunset:Int?}

Parsing JSON data using JSONDecoder:

    let jsonUrlString = ("https://api.openweathermap.org/data/2.5/weather?lat=\(lat!)&lon=\(lon!)&APPID=\(apikey)")

    guard let url = URL(string: jsonUrlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, err) in

        //check err
        if err != nil {
            print("Error:\(String(describing: err))")
        }

        guard let data = data else { return }
        //do stuff

        do {

            let weatherData = try JSONDecoder().decode(WeatherData.self, from: data)

            print(weatherData.name, weatherData.weather)

   //Here i can't parse the weather Array, and get xcode error

     if let wArr = weatherData.weather! as? Array<AnyObject> {
                if let weatherIcon = wArr["icon"] {
                  icon = weatherIcon
                    }
                }
        } catch let jsonErr {
            print("Error:\(jsonErr)")
        }

        }.resume()//URLSession

ERROR msg: Cannot subscript a value of type 'Array' with an index of type 'String'.

How can i fix this? How can i parse weather array elements?

Body:
Declare weather in the WeatherData struct as non-optional. There is always a weather

let weather : [WeatherArr]

Get the first item if the array and the icon

if let currentWeather = weatherData.weather.first {
   if let weatherIcon = currentWeather.icon  {
      print(weatherIcon)
   }
}


问:
Check if a given key already exists in a dictionary and increment it
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

```<code>my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1
</code>```

答:
As you can see from the many answers, there are several solutions. One instance of LBYL (look before you leap) has not been mentioned yet, the has_key() method:</p>

```<code>my_dict = {}

def add (key):
    if my_dict.has_key(key):
        my_dict[key] += 1
    else:
        my_dict[key] = 1

if __name__ == '__main__':
    add("foo")
    add("bar")
    add("foo")
    print my_dict
</code>```

OwnerDisplayName: Ben

ContentLicense: CC BY-SA 4.0

Body:
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1

Body:
As you can see from the many answers, there are several solutions. One instance of LBYL (look before you leap) has not been mentioned yet, the has_key() method:

my_dict = {}

def add (key):
    if my_dict.has_key(key):
        my_dict[key] += 1
    else:
        my_dict[key] = 1

if __name__ == '__main__':
    add("foo")
    add("bar")
    add("foo")
    print my_dict

OwnerDisplayName: bortzmeyer


问:
Problem with validates_uniqueness_of
I'm using rails 2.3.5 and Authlogic in our website, and I have been getting errors on the database through hoptoad of users with duplicated emails trying to be saved. The problem is, obviously I have the validates_uniqueness_of :email on the model.

On my tests here in development I get the expected validation error and the user is not saved, but in production, I keep getting this errors on the DB layer.

I've tested with case sensitive emails and it also validated correctly.

I've checked and the class and there is no attr_accessor or any other attribute override, and I don't think Authlogic would do it in a wrong way...

What could be happening in production? Are there any cases where rails validates doesn't work?

答:
Have you tried recreating the scenario. Why should throw errors that warrant Hoptoad Notification. I mean, basically if you have a it should not save the user and not throw an error for hoptoad to notify you about.

Also with authlogic, i don't think you are required to specify the validate_uniqueness_of for email. Usually authlogic will take care of that for you.

So I guess, its time for you to deep dive.

Look at the logs, and try recreating this error locally. Its always best to retrace the steps leading to error.

More details, error stack , code would definitely be helpful.

Title: Problem with validates_uniqueness_of


问:
error: illegal character: \65279 java android studio?
I am trying to learn working with Android studio and I am relatively new in this field. So, I built this small application that actually just opens up the camera but then when I build the project, I am getting this annoying error which says "Error:(15, 33) error: illegal character: \65279" . I have done my research online and made sure that all my file encoding are in UTF-8 and still the error doesnt seem to go away. This is my java class.</p>

```<code>package com.example.user.cameraapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.os.Bundle;
import android.content.pm.PackageInfo;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class CameraActivity extends AppCompatActivity {

    static final int REQUEST_IMAGE_CAPTURE =1;
    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        Button btn1 = (Button)findViewById(R.id.startBtn);
        img = (ImageView)findViewById(R.id.imageview);

        //Disable the button if the user has no camera
        if(!hasCamera()){
            btn1.setEnabled(false);
        }
    }

    private boolean hasCamera() {
        return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
    }

    private void launchCamera(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //Take a picture pass results to onActivityResult

        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);

    }

    //If you want to return the image taken

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==REQUEST_IMAGE_CAPTURE && resultCode== RESULT_OK){
            Bundle extras = data.getExtras();
            Bitmap photo = (Bitmap)extras.get("data");
            img.setImageBitmap(photo);

        }
    }
}
//The error points to the specific import 'import android.widget.ImageView;

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.example.user.cameraapp"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
}
</code>```

答: It's complaining about the first 3 bytes which have been added as BOM header. See: https://www.experts-exchange.com/questions/23653934/UTF-8-java-file-dont-compile-correctly-because-of-BOM.html</p>

Body:
I am trying to learn working with Android studio and I am relatively new in this field. So, I built this small application that actually just opens up the camera but then when I build the project, I am getting this annoying error which says "Error:(15, 33) error: illegal character: \65279" . I have done my research online and made sure that all my file encoding are in UTF-8 and still the error doesnt seem to go away. This is my java class.

package com.example.user.cameraapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.os.Bundle;
import android.content.pm.PackageInfo;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class CameraActivity extends AppCompatActivity {

    static final int REQUEST_IMAGE_CAPTURE =1;
    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        Button btn1 = (Button)findViewById(R.id.startBtn);
        img = (ImageView)findViewById(R.id.imageview);

        //Disable the button if the user has no camera
        if(!hasCamera()){
            btn1.setEnabled(false);
        }
    }

    private boolean hasCamera() {
        return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
    }

    private void launchCamera(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //Take a picture pass results to onActivityResult

        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);

    }

    //If you want to return the image taken

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==REQUEST_IMAGE_CAPTURE && resultCode== RESULT_OK){
            Bundle extras = data.getExtras();
            Bitmap photo = (Bitmap)extras.get("data");
            img.setImageBitmap(photo);

        }
    }
}
//The error points to the specific import 'import android.widget.ImageView;

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.example.user.cameraapp"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
}


问:
CkEditor Template Changes won't take effect
I downloaded ckeditor, unpacked, installed and all that stuff. It is working fine but I CANNOT change templates in /plugins/templates/templates/default.js. I even deleted them, not working.

Is this how I change templates? (I am desperate here)

PLease HELP!

答:
Clearing the browser cache definitely worked.

Go to /vendors/ckeditor/plugins/templates/templates/default.js

Make certain to place every HTML tag and any text between two commas, along with a plus-sign at the end of the ending-commas.

FYI - The plus-sign should NOT come after the VERY LAST HTML tag.

=========================

EXAMPLE:

https://github.com/ckeditor/ckeditor-dev/blob/master/plugins/templates/templates/default.js