问:
Flattening Multiple Arrays
I am trying to model cultural dissemination. In the program, I have five characteristics and nine potential outcomes per characteristic. </p>

```<code>dimension <- 10
characteristics <- 5

world <- array(0, dim=c(dimension, dimension, characteristics))

for (i in 1:dimension){
  for (j in 1:dimension){
    for (k in 1:characteristics){
      world[i,j,k] <- sample(c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), 1)
    }
  }
}
</code>```

<p>I would like to be able to flatten the array and create a unique identifier for each potential variation. For example, a world where each array[1,1]=(0,0,0,0,0)=1 all the way to: (9,9,9,9,9)=10^5. Also, this: (1,0,0,0,0)!=(0,0,1,0,0) etc. Any suggestions on how to flatten the dimensions would be greatly appreciated. </p>

答:
I'm interpreting your "(9,9,9,9,9)=10^5" notation differently now.  Do you want every possible combination enumerated (ie, the 10^5) part, accompanied by a count of how many times each quintet appears?

Transform the cube into a list of 2d data frames.  And some dimension indices if you need them somewhere.

```<code>library(magrittr)
lst_ds <- purrr::map(seq_len(characteristics), ~tibble::as_tibble(world[,,.]))
lst_ds <- purrr::map(lst_ds, function(d) { dplyr::mutate(d, dim1= seq_len(nrow(d))) })
</code>```

Transform to an entity-attribute-value style of dataset (ie, super tall).

```<code>ds_eav <- lst_ds %>%
  dplyr::bind_rows(.id = "characteristic") %>%
  tidyr::gather(key=dim2, value=value, -characteristic, -dim1) %>%
  dplyr::mutate(
    characteristic  = paste0("c", characteristic),
    dim2            = as.integer(sub("^V(\\d+)$", "\\1", dim2))
  )
</code>```

Widen so each observed quintet occupies its own row.

```<code>ds_quintet <- ds_eav %>%
  tidyr::spread(key=characteristic, value=value)
</code>```

Enumerate the possible quintets.

```<code>ds_possible <- tidyr::crossing(
  c1 = 0:9,
  c2 = 0:9,
  c3 = 0:9,
  c4 = 0:9,
  c5 = 0:9
)
</code>```

Count the observed quintets, then right join them with all 10^5 possible values.  And replace the NAs (that never occurred in ds_obs with zeros).

```<code>ds_obs <- ds_quintet %>%
  dplyr::select(-dim1, -dim2) %>%
  dplyr::group_by(c1, c2, c3, c4, c5) %>%
  dplyr::summarize(
    frequency = n()
  ) %>%
  dplyr::ungroup() %>%
  dplyr::right_join(ds_possible, by=c("c1", "c2", "c3", "c4", "c5")) %>%
  dplyr::mutate(
    frequency   = dplyr::coalesce(frequency, 0L)
  ) %>%
  dplyr::arrange(c1, c2, c3, c4, c5)
</code>```

Which looks like:

```<code> A tibble: 100,000 x 6
      c1    c2    c3    c4    c5 frequency
   <dbl> <dbl> <dbl> <dbl> <dbl>     <int>
 1     0     0     0     0     0         0
 2     0     0     0     0     1         0
 3     0     0     0     0     2         2
 4     0     0     0     0     3         0
 5     0     0     0     0     4         0
 6     0     0     0     0     5         0
 7     0     0     0     0     6         1
 8     0     0     0     0     7         0
 9     0     0     0     0     8         0
10     0     0     0     0     9         0
# ... with 99,990 more rows
</code>```

Title: Flattening Multiple Arrays

Body:
I am trying to model cultural dissemination. In the program, I have five characteristics and nine potential outcomes per characteristic.

dimension <- 10
characteristics <- 5

world <- array(0, dim=c(dimension, dimension, characteristics))

for (i in 1:dimension){
  for (j in 1:dimension){
    for (k in 1:characteristics){
      world[i,j,k] <- sample(c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), 1)
    }
  }
}

I would like to be able to flatten the array and create a unique identifier for each potential variation. For example, a world where each array[1,1]=(0,0,0,0,0)=1 all the way to: (9,9,9,9,9)=10^5. Also, this: (1,0,0,0,0)!=(0,0,1,0,0) etc. Any suggestions on how to flatten the dimensions would be greatly appreciated.

Body:
I'm interpreting your "(9,9,9,9,9)=10^5" notation differently now.  Do you want every possible combination enumerated (ie, the 10^5) part, accompanied by a count of how many times each quintet appears?

Transform the cube into a list of 2d data frames.  And some dimension indices if you need them somewhere.

library(magrittr)
lst_ds <- purrr::map(seq_len(characteristics), ~tibble::as_tibble(world[,,.]))
lst_ds <- purrr::map(lst_ds, function(d) { dplyr::mutate(d, dim1= seq_len(nrow(d))) })

Transform to an entity-attribute-value style of dataset (ie, super tall).

ds_eav <- lst_ds %>%
  dplyr::bind_rows(.id = "characteristic") %>%
  tidyr::gather(key=dim2, value=value, -characteristic, -dim1) %>%
  dplyr::mutate(
    characteristic  = paste0("c", characteristic),
    dim2            = as.integer(sub("^V(\\d+)$", "\\1", dim2))
  )

Widen so each observed quintet occupies its own row.

ds_quintet <- ds_eav %>%
  tidyr::spread(key=characteristic, value=value)

Enumerate the possible quintets.

ds_possible <- tidyr::crossing(
  c1 = 0:9,
  c2 = 0:9,
  c3 = 0:9,
  c4 = 0:9,
  c5 = 0:9
)

Count the observed quintets, then right join them with all 10^5 possible values.  And replace the NAs (that never occurred in ds_obs with zeros).

ds_obs <- ds_quintet %>%
  dplyr::select(-dim1, -dim2) %>%
  dplyr::group_by(c1, c2, c3, c4, c5) %>%
  dplyr::summarize(
    frequency = n()
  ) %>%
  dplyr::ungroup() %>%
  dplyr::right_join(ds_possible, by=c("c1", "c2", "c3", "c4", "c5")) %>%
  dplyr::mutate(
    frequency   = dplyr::coalesce(frequency, 0L)
  ) %>%
  dplyr::arrange(c1, c2, c3, c4, c5)

Which looks like:

 A tibble: 100,000 x 6
      c1    c2    c3    c4    c5 frequency
   <dbl> <dbl> <dbl> <dbl> <dbl>     <int>
 1     0     0     0     0     0         0
 2     0     0     0     0     1         0
 3     0     0     0     0     2         2
 4     0     0     0     0     3         0
 5     0     0     0     0     4         0
 6     0     0     0     0     5         0
 7     0     0     0     0     6         1
 8     0     0     0     0     7         0
 9     0     0     0     0     8         0
10     0     0     0     0     9         0
# ... with 99,990 more rows


来源: stackexchange

问:
R plotlly add_trace issue when x-axis values are POSIXct
I wish it could be much easier for us to add reference lines in plotly like using geom_vline or geom_hline in ggplot2 or even the abline in base R.

We can use add_trace function to mimic the geom_hline but this time it seems I am adding the wrong x values.

```<code>library(plotly)
library(lubridate)

D = data.frame(
  y = round(rnorm(10),1),
  x = structure(c(1498640394, 1498641854, 1498642201, 1498642515, 1498642749,
            1498643011, 1498643247, 1498643499, 1498643735, 1498643992),
            tzone = "UTC", class = c("POSIXct", "POSIXt"))
)

D$DATE_TIME = lubridate::ymd_hms(D$x)

MIN = min(D$x)

MAX = max(D$x)

H = 0

plot_ly(D, x = ~x, y = ~ y, type = "scatter", mode ="lines+markers") %>%
  add_trace(x = c(MIN, MAX), y = c(H, H), name = "Reference", mode = "lines", line=list(color="red",dash="dash"))
</code>```

I get

The reference line goes way wrong. Why does this happen?

答:
A workaround for this question:

```<code>MIN = min(D$x) - 28800

MAX = max(D$x) - 28800
</code>```

Then the chart is correct for now.

ContentLicense: CC BY-SA 3.0

Body:
I wish it could be much easier for us to add reference lines in plotly like using geom_vline or geom_hline in ggplot2 or even the abline in base R.

We can use add_trace function to mimic the geom_hline but this time it seems I am adding the wrong x values.

library(plotly)
library(lubridate)

D = data.frame(
  y = round(rnorm(10),1),
  x = structure(c(1498640394, 1498641854, 1498642201, 1498642515, 1498642749,
            1498643011, 1498643247, 1498643499, 1498643735, 1498643992),
            tzone = "UTC", class = c("POSIXct", "POSIXt"))
)

D$DATE_TIME = lubridate::ymd_hms(D$x)

MIN = min(D$x)

MAX = max(D$x)

H = 0

plot_ly(D, x = ~x, y = ~ y, type = "scatter", mode ="lines+markers") %>%
  add_trace(x = c(MIN, MAX), y = c(H, H), name = "Reference", mode = "lines", line=list(color="red",dash="dash"))

I get

The reference line goes way wrong. Why does this happen?

Body:
A workaround for this question:

MIN = min(D$x) - 28800

MAX = max(D$x) - 28800

Then the chart is correct for now.


问:
How do I use browser fingerprint in my website?
I want to identify users accessing my API even if they clear the cookies or localstorage wherever I am storing the current session information. I see that browser fingerprinting is one of the ways to achieve this up to some accuracy. I am working on an angular2 project for the frontend. I have the following questions:

Are there any libraries available for angular2 which creates the browser fingerprint? (I have seen ng2-device-detector. This doesn't give much info and also no hashed fingerprint. So, do I have to hash it myself? )

Have seen fingerprintjs2 this does take a lot of info but has no implementation for angular2, but I wonder how would the hashed fingerprint actually matter? For a Request in my API, I will check if the payload contained a fingerprint which already existed in any of the existing sessions? (Really payload? It will just be a POST request. The user can simply send a random long string as the hashed fingerprint and the API will treat the request as if it came from a different person.)

I guess then I will have to use some API which not only generates a hashed fingerprint in the frontend but also validates after the request has reached the API, something like Google's reCaptcha. Are there any APIs like such?

If there aren't any APIs as such then I guess I will have to implement such functionality in my API itself?

Please write your suggestions.

答:
Ankit pretty much answered in relation to Angular. Here is an API that provides a fingerprint so you do not need to implement it yourself:

Browser Fingerprint API

Although this solution is not an Angular component (or what-have-you), you can make an AJAX call to get the fingerprint and submit it to your server.

Full Disclosure: I am the developer of this service.


问:
Get the only latest data from last week and sum some column
Get only latest data from last week and sum some column

I made an example with dat, the actual result and the expected.

http://rextester.com/HMB12638

```<code> --Taking first as example..

--      user    contact         barcode date                in  out dif
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 80
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 90
-- 3    USER2   Guillermo Tole  987654  13.06.2017 05:27:00 400 380 20
-- 4    USER2   Guillermo Tole  281460  12.06.2017 05:26:00 230 190 40
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 6    USER3   Juan Rulfo      123456  12.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240
-- 8    USER3   Pepito Marquez  346234  14.06.2017 05:37:00 450 300 150

 -- This would be the expectation
-- (MOST RECENT in . out) SUM of all the barcodes showed
--      user    contact         barcode date                in  out sum
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 170 (80 + 90)
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 170 (80 + 90)
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240
</code>```

答:
Made it.. just in case somebody need it, it may not be the most elegant work, but at least it works</p>

```<code>-- create a table and keep the IDs you want the info
with tabla as (
    SELECT distinct on( barcode) barcode  as barcode, id, date
    from table1 as tabla
    where date_trunc('day', date) <= '2017-06-25' ::date - (interval '1 week')::interval
 and date >  '2017-06-25'::date - (interval '2 weeks')::interval
    order by barcode, date desc
)
-- make the query using inner join on the previously created table
select user, contact, t1.barcode, t1.date, "in", out, dif ,  sum("in" - out) over (partition by contact order by t1.barcode)
    from table1 t1
      inner join tabla on tabla.id = t1.id
    where date_trunc('day', t1.date) <= '2017-06-25' ::date - (interval '1 week')::interval
 and t1.date >  '2017-06-25'::date - (interval '2 weeks')::interval
 order by contact, barcode, date desc
 -- PD, "in" is a reserved word, i have to keep it with commas
</code>```

Body:
Get only latest data from last week and sum some column

I made an example with dat, the actual result and the expected.

http://rextester.com/HMB12638

 --Taking first as example..

--      user    contact         barcode date                in  out dif
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 80
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 90
-- 3    USER2   Guillermo Tole  987654  13.06.2017 05:27:00 400 380 20
-- 4    USER2   Guillermo Tole  281460  12.06.2017 05:26:00 230 190 40
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 6    USER3   Juan Rulfo      123456  12.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240
-- 8    USER3   Pepito Marquez  346234  14.06.2017 05:37:00 450 300 150

 -- This would be the expectation
-- (MOST RECENT in . out) SUM of all the barcodes showed
--      user    contact         barcode date                in  out sum
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 170 (80 + 90)
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 170 (80 + 90)
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240

Body:
Made it.. just in case somebody need it, it may not be the most elegant work, but at least it works

-- create a table and keep the IDs you want the info
with tabla as (
    SELECT distinct on( barcode) barcode  as barcode, id, date
    from table1 as tabla
    where date_trunc('day', date) <= '2017-06-25' ::date - (interval '1 week')::interval
 and date >  '2017-06-25'::date - (interval '2 weeks')::interval
    order by barcode, date desc
)
-- make the query using inner join on the previously created table
select user, contact, t1.barcode, t1.date, "in", out, dif ,  sum("in" - out) over (partition by contact order by t1.barcode)
    from table1 t1
      inner join tabla on tabla.id = t1.id
    where date_trunc('day', t1.date) <= '2017-06-25' ::date - (interval '1 week')::interval
 and t1.date >  '2017-06-25'::date - (interval '2 weeks')::interval
 order by contact, barcode, date desc
 -- PD, "in" is a reserved word, i have to keep it with commas


问:
Historical / auditable database
This question is related to the schema that can be found in one of my other questions here.  Basically in my database I store users, locations, sensors amongst other things.  All of these things are editable in the system by users, and deletable.

However - when an item is edited or deleted I need to store the old data; I need to be able to see what the data was before the change.

There are also non-editable items in the database, such as "readings".  They are more of a log really.  Readings are logged against sensors, because its the reading for a particular sensor.

If I generate a report of readings, I need to be able to see what the attributes for a location or sensor was at the time of the reading.

Basically I should be able to reconstruct the data for any point in time.

Now, I've done this before and got it working well by adding the following columns to each editable table:

```<code>valid_from
valid_to
edited_by
</code>```

If valid_to = 9999-12-31 23:59:59 then that's the current record.  If valid_to equals valid_from, then the record is deleted.

However, I was never happy with the triggers I needed to use to enforce foreign key consistency.

I can possibly avoid triggers by using the extension to the "PostgreSQL" database.  This provides a column type called "period" which allows you to store a period of time between two dates, and then allows you to do CHECK constraints to prevent overlapping periods.  That might be an answer.

I am wondering though if there is another way.

I've seen people mention using special historical tables, but I don't really like the thought of maintainling 2 tables for almost every 1 table (though it still might be a possibility).

Maybe I could cut down my initial implementation to not bother checking the consistency of records that aren't "current" - i.e. only bother to check constraints on records where the valid_to is 9999-12-31 23:59:59.  Afterall, the people who use historical tables do not seem to have constraint checks on those tables (for the same reason, you'd need triggers).

Does anyone have any thoughts about this?

PS - the title also mentions auditable database.  In the previous system I mentioned, there is always the edited_by field.  This allowed all changes to be tracked so we could always see who changed a record.  Not sure how much difference that might make.

Thanks.

答:
I've run into this situation before as well.  Depending on the amount of data your are trying to keep track of, it can be daunting.  The historical table works nicely for ease of use at times because you can take a 'snapshot' of the record in the history table, then make the changes as needed in the production table.  It's pretty straight forward to implement, however depending on how much data you have and how often it changes, you can end up with very large historical tables.

Another option is logging all changes that allow someone to 'replay' what happened and track it.  Each change is logged into a table or a field (depending on your needs) that keeps track of who, when, and what was changed to what i.e. On Dec 31, 2010 Bob changed the status from 'Open' to 'Closed'.

Which system you want to use usually depends on how you'l need to keep/review/use the data later.  Automated reports, review by a person, some combination of the two, etc.

ContentLicense: CC BY-SA 2.5

Title: Historical / auditable database

Body:
This question is related to the schema that can be found in one of my other questions here.  Basically in my database I store users, locations, sensors amongst other things.  All of these things are editable in the system by users, and deletable.

However - when an item is edited or deleted I need to store the old data; I need to be able to see what the data was before the change.

There are also non-editable items in the database, such as "readings".  They are more of a log really.  Readings are logged against sensors, because its the reading for a particular sensor.

If I generate a report of readings, I need to be able to see what the attributes for a location or sensor was at the time of the reading.

Basically I should be able to reconstruct the data for any point in time.

Now, I've done this before and got it working well by adding the following columns to each editable table:

valid_from
valid_to
edited_by

If valid_to = 9999-12-31 23:59:59 then that's the current record.  If valid_to equals valid_from, then the record is deleted.

However, I was never happy with the triggers I needed to use to enforce foreign key consistency.

I can possibly avoid triggers by using the extension to the "PostgreSQL" database.  This provides a column type called "period" which allows you to store a period of time between two dates, and then allows you to do CHECK constraints to prevent overlapping periods.  That might be an answer.

I am wondering though if there is another way.

I've seen people mention using special historical tables, but I don't really like the thought of maintainling 2 tables for almost every 1 table (though it still might be a possibility).

Maybe I could cut down my initial implementation to not bother checking the consistency of records that aren't "current" - i.e. only bother to check constraints on records where the valid_to is 9999-12-31 23:59:59.  Afterall, the people who use historical tables do not seem to have constraint checks on those tables (for the same reason, you'd need triggers).

Does anyone have any thoughts about this?

PS - the title also mentions auditable database.  In the previous system I mentioned, there is always the edited_by field.  This allowed all changes to be tracked so we could always see who changed a record.  Not sure how much difference that might make.

Thanks.


问:
Python super() and inherited class directory location
I'm trying to figure out how get a system I'm using for a Theme manager for UI project I'm working on to work correctly.

Example:

File Structure:

```<code>element.py    - class Element()
button.py     - class Button(Element)
text.py       - class Text(Element)
input/text.py - class Text(Element)
</code>```

I use class-name for different properties in my theme. (Similar to CSS)

So 'element' could have the text color be white.

I currently have all UI elements inherit from 'Element' and using:

```<code>self.__class__.__name__.lower()
</code>```

This is working for 'Button' and 'Element', the problem comes into play for input.text vs text. Text is for all uses of displaying text so it's in almost all Elements, but the input.text class is named Text as well is used for Text Input and I want to use a property selector like 'input.text' instead of just 'text' that I get now for it with the class.name.

I'm trying to set this up in the end so it has a plugin system for others to add elements and being able to use the directory structure as part of the property selector.

For example:

```<code>Button class: button
Text class: text
Text Input class: text, but in the directory 'input'
</code>```

I am trying to figure out how to get python to check if 'self' in element from a super() call is in a directory below where 'element.py' is. Which would add on the directory name to the class name for the properties it checks against.

End result would be:

```<code>element
button
text
input.text
</code>```

TLDR: I need to know how to check if an inherited class is in a different directory than the base class and what that directory is called.

Thanks for any assistance in figuring this out.

答:
Alright, I found out how to do it the way I wanted to. Just answering the question, while I also think on the comment from @supersam654.

I was able to find out how to get the path from an inherited class with:

```<code>import os, sys

el = os.path.dirname(sys.modules[self.__class__.__module__].__file__).split('/')
base = os.path.dirname(__file__).split('/')
for i in base:
  el.remove(i)
</code>```

Anything left over in 'el' will have individual directory names that I can use.

Body:
I'm trying to figure out how get a system I'm using for a Theme manager for UI project I'm working on to work correctly.

Example:

File Structure:

element.py    - class Element()
button.py     - class Button(Element)
text.py       - class Text(Element)
input/text.py - class Text(Element)

I use class-name for different properties in my theme. (Similar to CSS)

So 'element' could have the text color be white.

I currently have all UI elements inherit from 'Element' and using:

self.__class__.__name__.lower()

This is working for 'Button' and 'Element', the problem comes into play for input.text vs text. Text is for all uses of displaying text so it's in almost all Elements, but the input.text class is named Text as well is used for Text Input and I want to use a property selector like 'input.text' instead of just 'text' that I get now for it with the class.name.

I'm trying to set this up in the end so it has a plugin system for others to add elements and being able to use the directory structure as part of the property selector.

For example:

Button class: button
Text class: text
Text Input class: text, but in the directory 'input'

I am trying to figure out how to get python to check if 'self' in element from a super() call is in a directory below where 'element.py' is. Which would add on the directory name to the class name for the properties it checks against.

End result would be:

element
button
text
input.text

TLDR: I need to know how to check if an inherited class is in a different directory than the base class and what that directory is called.

Thanks for any assistance in figuring this out.

Body:
Alright, I found out how to do it the way I wanted to. Just answering the question, while I also think on the comment from @supersam654.

I was able to find out how to get the path from an inherited class with:

import os, sys

el = os.path.dirname(sys.modules[self.__class__.__module__].__file__).split('/')
base = os.path.dirname(__file__).split('/')
for i in base:
  el.remove(i)

Anything left over in 'el' will have individual directory names that I can use.


问:
Transposing parts of a data frame to individual columns
I am new to R and struggling with it a bit. I have a data frame like this

```<code>reg     12345
val1    1
val2    0
reg     45678
val1    0
val2    0
val3    1
reg     97654
val1    1
reg     567834
val3    1
reg     567845
val2    0
val4    1
</code>```

My goal is to transform data into this format into

```<code> reg     val1    val2    val3    val4
 12345   1       0       0       0
 45678   0       0       1       0
 97654   1       0       0       0
 567834  0       0       1       0
 567845  0       0       0       1
</code>```

Hoping somebody can guide me here. My data source is less than 200 lines and there are no constraints with regards to the approach. Please assume that the
machine running had adequate memory and processing power.

Body:
I am new to R and struggling with it a bit. I have a data frame like this

reg     12345
val1    1
val2    0
reg     45678
val1    0
val2    0
val3    1
reg     97654
val1    1
reg     567834
val3    1
reg     567845
val2    0
val4    1

My goal is to transform data into this format into

 reg     val1    val2    val3    val4
 12345   1       0       0       0
 45678   0       0       1       0
 97654   1       0       0       0
 567834  0       0       1       0
 567845  0       0       0       1

Hoping somebody can guide me here. My data source is less than 200 lines and there are no constraints with regards to the approach. Please assume that the
machine running had adequate memory and processing power.

Body:
Here is an option using dcast

library(data.table)
dcast(setDT(df), cumsum(A=="reg") ~ A, value.var = "B", fill = 0)[, A := NULL][]
#      reg val1 val2 val3 val4
#1:  12345    1    0    0    0
#2:  45678    0    0    1    0
#3:  97654    1    0    0    0
#4: 567834    0    0    1    0
#5: 567845    0    0    0    1


问:
Why is the concept of immutability is embraced in React and its ecosystem?
in ES6, there are additional ways to declare a variable such as let and const

A variable declared with const cannot be re-assigned or re-declared.

Why are there so many const declarations in React application and what are the distinctive benefits from using const over var and let?

答:
It's pretty common to have multiple parts of code relying on the same variable (PI for example) . If that variable is a constant, and immutable, you dont need to worry about it changing at unpredictable times based on who may potentially be writing to it.

If a variable shouldn't change, it should be made a constant to ensure that it it isn't reassigned accidentally. That way you can trust that the value of the variable will always be the same.

Note, const has very little to do with immutability. Even if you have a constant reference to an object, the object itself can still change.


问:
How to use asyncio to download files on s3 bucket
I'm using the following code to download all my files in a s3 bucket:

```<code>def main(bucket_name, destination_dir):
    bucket = boto3.resource('s3').Bucket(bucket_name)
    for obj in bucket.objects.all():
        if obj.key.endswith('/'):
            continue
        destination = '%s/%s' % (bucket_name, obj.key)
        if not os.path.exists(destination):
            os.makedirs(os.path.dirname(destination), exist_ok=True)
        bucket.download_file(obj.key, destination)
</code>```

I would like to know how to make this asynchronous, if possible.

Thank u in advance.

答: Out of the box, boto3 doesn't support asyncio. There's a tracking issue opened on this that offers some workarounds; they may or may not work for your use case. </p>

Body:
I'm using the following code to download all my files in a s3 bucket:

def main(bucket_name, destination_dir):
    bucket = boto3.resource('s3').Bucket(bucket_name)
    for obj in bucket.objects.all():
        if obj.key.endswith('/'):
            continue
        destination = '%s/%s' % (bucket_name, obj.key)
        if not os.path.exists(destination):
            os.makedirs(os.path.dirname(destination), exist_ok=True)
        bucket.download_file(obj.key, destination)

I would like to know how to make this asynchronous, if possible.

Thank u in advance.


问:
How to pass a string as a prop in React Native
I am facing a situation where my  component will not render text unless it is rendered as part of ListView. E.g. This one works great:

```<code><ListView
  dataSource={this.state.dataSource}
  renderRow={(rowData) =>
    <View style={styles.buttonContainer}>
      <Button
        onPress={() => navigate('Team', { team: rowData })}
        title={rowData.name}
      />
    </View>
  }
/>
</code>```

But this one does not work, the button does not show any text as if it didn't receive anything

```<code><View style={styles.container}>
  <View style={styles.buttonContainer}>
    <Button
      onPress={() => navigate('Team')}
      title={'Sample Text'}
    />
  </View>
</View>
</code>```

My Button component return looks like this:

```<code>return (
  <TouchableOpacity onPress={onPress} style={buttonStyle}>
    <Text style={textStyle}>
      {this.props.title}
    </Text>
  </TouchableOpacity>
)
</code>```

I put console.log(this.props.title) on the render() and the following shows up in the remote debugger console:

undefined "Sample Text"

Dependencies in package.json

"react": "16.0.0-alpha.6",
    "react-native": "^0.43.4",
    "react-navigation": "git+https://github.com/react-community/react-navigation.git"

答:
Try removing those brackets because you don't need them:
title='Sample Text'

Body:
I am facing a situation where my  component will not render text unless it is rendered as part of ListView. E.g. This one works great:

<ListView
  dataSource={this.state.dataSource}
  renderRow={(rowData) =>
    <View style={styles.buttonContainer}>
      <Button
        onPress={() => navigate('Team', { team: rowData })}
        title={rowData.name}
      />
    </View>
  }
/>

But this one does not work, the button does not show any text as if it didn't receive anything

<View style={styles.container}>
  <View style={styles.buttonContainer}>
    <Button
      onPress={() => navigate('Team')}
      title={'Sample Text'}
    />
  </View>
</View>

My Button component return looks like this:

return (
  <TouchableOpacity onPress={onPress} style={buttonStyle}>
    <Text style={textStyle}>
      {this.props.title}
    </Text>
  </TouchableOpacity>
)

I put console.log(this.props.title) on the render() and the following shows up in the remote debugger console:

undefined "Sample Text"

Dependencies in package.json

"react": "16.0.0-alpha.6",
    "react-native": "^0.43.4",
    "react-navigation": "git+https://github.com/react-community/react-navigation.git"


问:
implementing drag and resize on the same element
I am trying ti implement resize and drag on the same element. Check this out:

http://jsfiddle.net/Lo8n75dg/

my code so far:

```<code>   $('#dragbar').mousedown(function(e){
        e.preventDefault();
        $(document).mousemove(function(e){
          //$('#position').html(e.pageX +', '+ e.pageY);
          $('#sidebar').css("width",e.pageX+2-100);
          $('#main').css("left",e.pageX+2);
       });
    });

   $(document).mouseup(function(e){
       $(document).unbind('mousemove');
   });

      $('#sidebar').mousedown(function(e){
        e.preventDefault();
        $(document).mousemove(function(e){
          //$('#position').html(e.pageX +', '+ e.pageY);
          $('#sidebar').css("margin-left",e.pageX-100-$('#sidebar').offset().left);
          //$('#main').css("left",e.pageX+2);
       });
    });
</code>```

The idea is that if mouse down happened on the black line, the code preforms resize. If mouse down is on red rectangle, the code make horizontal drag.

This 2 event currently conflict, that is why you see flickering. Any idea how do I fix that?

UPDATE:
http://jsfiddle.net/Lo8n75dg/2/
I added e.stopPropagation() which does part of the trick. There is unfortunately still a lot of flickering going on for reasons unknown to me.

答:
Below seems to work for me in the fiddle. Please use this in both the places.

$('#sidebar').css("position","absolute");
$('#sidebar').css("left",);

Let me know how it works out for you :)

Body:
I am trying ti implement resize and drag on the same element. Check this out:

http://jsfiddle.net/Lo8n75dg/

my code so far:

   $('#dragbar').mousedown(function(e){
        e.preventDefault();
        $(document).mousemove(function(e){
          //$('#position').html(e.pageX +', '+ e.pageY);
          $('#sidebar').css("width",e.pageX+2-100);
          $('#main').css("left",e.pageX+2);
       });
    });

   $(document).mouseup(function(e){
       $(document).unbind('mousemove');
   });

      $('#sidebar').mousedown(function(e){
        e.preventDefault();
        $(document).mousemove(function(e){
          //$('#position').html(e.pageX +', '+ e.pageY);
          $('#sidebar').css("margin-left",e.pageX-100-$('#sidebar').offset().left);
          //$('#main').css("left",e.pageX+2);
       });
    });

The idea is that if mouse down happened on the black line, the code preforms resize. If mouse down is on red rectangle, the code make horizontal drag.

This 2 event currently conflict, that is why you see flickering. Any idea how do I fix that?

UPDATE:
http://jsfiddle.net/Lo8n75dg/2/
I added e.stopPropagation() which does part of the trick. There is unfortunately still a lot of flickering going on for reasons unknown to me.


问:
localhost do not load due to php code
my xampp localhost was working well till i add this code to my php file

```<code><?php while ($notification) {?>
<li>
<?php
  echo $notification['notification'];
  ?>
  </li>
  <?php
} ?>
</code>```

now the page is not loading or partially loading

here $notification is

```<code>$notification_sql= "SELECT id FROM notifications WHERE user_id='{$_SESSION['user']}'";

       $notification_query = mysqli_query($conn, $notification_sql);
      $notification = mysqli_fetch_assoc($notification_query);
</code>```

答:
Before I begin I want to recommend you something: Avoid the use of the while statetements. Unless they are really needed - like in the exact way they are used in the PHP docs (and even then you can find alternatives) - they should be avoided all the time. I present the motive down under.

That said,... it's not $notification['notification'], but $notification['id'].

After you change it, you still remain with the issue: an infinite loop. Because you are using a while loop without changing the state of the loop condition. E.g_ you are validating the $notification array for beeing existent. Because it exists all the time - it's state never beeing changed in the loop - then the iterations will be infinite in number. In order to avoid this dangerous (!!!) situation, you can use the following codes.

Method 1:

Notice the difference: $notification is valid only for the period of a loop step. After each iteration $notification is newly created. And, when mysqli_fetch_assoc() returns FALSE on the (last + 1)-iteration step, then the $notification receives that value and, therefore, the loop ends.

```<code><?php
$notification_sql = "SELECT id FROM notifications WHERE user_id='{$_SESSION['user']}'";

$notification_query = mysqli_query($conn, $notification_sql);

if ($notification_query) {
    while ($notification = mysqli_fetch_assoc($notification_query)) {
        ?>
        <li>
            <?php
            echo $notification['id'];
            ?>
        </li>
        <?php
    }

    mysqli_free_result($notification_query);
}
</code>```

?>

Method 2:

Or, if you want to fetch the results in an array and to output its items later, then you can do it like this:

```<code><?php
$notification_sql = "SELECT id FROM notifications WHERE user_id='{$_SESSION['user']}'";

$notification_query = mysqli_query($conn, $notification_sql);

$notifications = array();

if ($notification_query) {
    while ($row = mysqli_fetch_assoc($notification_query)) {
        $notifications[] = $row['id'];
    }

    mysqli_free_result($notification_query);
}

// OTHER STUFF AFTER FETCHING...
?>

<?php
// LOOPING AT A LATER TIME.
foreach ($notifications as $notificationId) {
    ?>
    <li>
        <?php
        echo $notificationId;
        ?>
    </li>
    <?php
}
?>
</code>```

Other recommendations:

Use prepared statements in order to avoid MySQL injection.

Use exception handling in order to catch all errors and handle them correspondingly. Especially when you run database operations.

Use PDO instead of mysqli.

Here I have provided full code examples of prepared statements combined with exception handling (using mysqli library):

Can't insert info in a server, but i can as localhost (See EDIT 2)

Login using MySqli Prepared Statement (See solution 1 & 2)

Good luck.

Title: localhost do not load due to php code

Body:
my xampp localhost was working well till i add this code to my php file

<?php while ($notification) {?>

<?php
  echo $notification['notification'];
  ?>

  <?php
} ?>

now the page is not loading or partially loading

here $notification is

$notification_sql= "SELECT id FROM notifications WHERE user_id='{$_SESSION['user']}'";

       $notification_query = mysqli_query($conn, $notification_sql);
      $notification = mysqli_fetch_assoc($notification_query);

Body:
Before I begin I want to recommend you something: Avoid the use of the while statetements. Unless they are really needed - like in the exact way they are used in the PHP docs (and even then you can find alternatives) - they should be avoided all the time. I present the motive down under.

That said,... it's not $notification['notification'], but $notification['id'].

After you change it, you still remain with the issue: an infinite loop. Because you are using a while loop without changing the state of the loop condition. E.g_ you are validating the $notification array for beeing existent. Because it exists all the time - it's state never beeing changed in the loop - then the iterations will be infinite in number. In order to avoid this dangerous (!!!) situation, you can use the following codes.

Method 1:

Notice the difference: $notification is valid only for the period of a loop step. After each iteration $notification is newly created. And, when mysqli_fetch_assoc() returns FALSE on the (last + 1)-iteration step, then the $notification receives that value and, therefore, the loop ends.

<?php
$notification_sql = "SELECT id FROM notifications WHERE user_id='{$_SESSION['user']}'";

$notification_query = mysqli_query($conn, $notification_sql);

if ($notification_query) {
    while ($notification = mysqli_fetch_assoc($notification_query)) {
        ?>
        <li>
            <?php
            echo $notification['id'];
            ?>
        </li>
        <?php
    }

    mysqli_free_result($notification_query);
}

?>

Method 2:

Or, if you want to fetch the results in an array and to output its items later, then you can do it like this:

<?php
$notification_sql = "SELECT id FROM notifications WHERE user_id='{$_SESSION['user']}'";

$notification_query = mysqli_query($conn, $notification_sql);

$notifications = array();

if ($notification_query) {
    while ($row = mysqli_fetch_assoc($notification_query)) {
        $notifications[] = $row['id'];
    }

    mysqli_free_result($notification_query);
}

// OTHER STUFF AFTER FETCHING...
?>

<?php
// LOOPING AT A LATER TIME.
foreach ($notifications as $notificationId) {
    ?>
    <li>
        <?php
        echo $notificationId;
        ?>
    </li>
    <?php
}
?>

Other recommendations:

Use prepared statements in order to avoid MySQL injection.

Use exception handling in order to catch all errors and handle them correspondingly. Especially when you run database operations.

Use PDO instead of mysqli.

Here I have provided full code examples of prepared statements combined with exception handling (using mysqli library):

Can't insert info in a server, but i can as localhost (See EDIT 2)

Login using MySqli Prepared Statement (See solution 1 & 2)

Good luck.


问:
setCharAt method not working as expected inside for loop (Java)
I am trying to develop a method to reverse the vowels in a string. For this, I have developed my own small stack. I am iterating backwards through the string twice, once to populate the stack with each vowel I locate, the second time to replace the vowel with the vowel stored at the top of the stack. I have added a bunch of print statements to determine where this is failing and it seems to be failing at the setCharAt method. For testing purposes, I provide a string aeiou and I am expecting to get back uoiea. The chars are getting replaced during each iteration, but unfortunately, they don't stay that way. As of the next iteration, the chars that were replaced on the previous iteration return to what they were before. As a result, I am getting back ueiou, where only the first character in the string is as expected (and the third which is a noop). Here is my code. Any tips are appreciated.

```<code>import java.util.*;

public class Solution {

    static String result;

    static class StackOfVowels {
        static Node top;

        public StackOfVowels() {
            Node top = null;
        }

        static class Node {
            Node next = null;
            char vowel = '\0';
            Node(char value) {
                this.vowel = value;
            }
        }

        public void push(char item) {
            Node node = new Node(item);
            if (top == null) {
                top = node;
            }
            else {
                node.next = top;
                top = node;
            }
        }

        public char top() {
            if (top == null) throw new EmptyStackException();
            return top.vowel;
        }

        public void pop() {
            int result = -1;
            if (top != null) {
                result = top.vowel;
                top = top.next;
            }
        }
    }

    public static String reverseVowels(String s) {

        StackOfVowels stackOfVowels = new StackOfVowels();

        for(int i = s.length()-1; i >= 0; i--) {
            char c = s.charAt(i);
            if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u')) {
                System.out.println("Initial sequence of iterations identified vowel: " + c);
                stackOfVowels.push(c);
                System.out.println("Pushed to stack, current top is: " + stackOfVowels.top());
            }
        }

        for(int j = s.length()-1; j >= 0; j--) {
            char b = s.charAt(j);
            if ((b == 'a') || (b == 'e') || (b == 'i') || (b == 'o') || (b == 'u')) {
                System.out.println("Second sequence of iterations identified vowel: " + b);
                StringBuilder newstr = new StringBuilder(s);
                char d = stackOfVowels.top();
                System.out.println("Variable d set to top of: " + stackOfVowels.top());
                newstr.setCharAt(j, d);
                result = newstr.toString();
                System.out.println("Here is the new string: " + result);
                stackOfVowels.pop();
                System.out.println("Stack was popped");
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "aeiou";
        reverseVowels(s);
        System.out.println("Final result: " + result);
    }
}
</code>```

答:
You generate always a new StringBuilder in your second loop with StringBuilder newstr = new StringBuilder(s);
But you always use ´s´ and not ´result´ to build your new StringBuilder.

It would be better anyways to not create a new Object of StringBuilder in each Iteration.

Also it is confusing that your methode has a return value, which is never used.

Following methode should work:

```<code>public static String reverseVowels(String s) {

    StackOfVowels stackOfVowels = new StackOfVowels();

    for(int i = s.length()-1; i >= 0; i--) {
        char c = s.charAt(i);
        if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u')) {
            System.out.println("Initial sequence of iterations identified vowel: " + c);
            stackOfVowels.push(c);
            System.out.println("Pushed to stack, current top is: " + stackOfVowels.top());
        }
    }
    StringBuilder result_builder = new StringBuilder(s);
    for(int j = s.length()-1; j >= 0; j--) {
        char b = s.charAt(j);

        if ((b == 'a') || (b == 'e') || (b == 'i') || (b == 'o') || (b == 'u')) {
            System.out.println("Second sequence of iterations identified vowel: " + b);
            char d = stackOfVowels.top();
            System.out.println("Variable d set to top of: " + stackOfVowels.top());
            result_builder.setCharAt(j, d);
            stackOfVowels.pop();
            System.out.println("Stack was popped");
        }
    }
    result = result_builder.toString();
    return result_builder.toString();
}
</code>```

Body:
I am trying to develop a method to reverse the vowels in a string. For this, I have developed my own small stack. I am iterating backwards through the string twice, once to populate the stack with each vowel I locate, the second time to replace the vowel with the vowel stored at the top of the stack. I have added a bunch of print statements to determine where this is failing and it seems to be failing at the setCharAt method. For testing purposes, I provide a string aeiou and I am expecting to get back uoiea. The chars are getting replaced during each iteration, but unfortunately, they don't stay that way. As of the next iteration, the chars that were replaced on the previous iteration return to what they were before. As a result, I am getting back ueiou, where only the first character in the string is as expected (and the third which is a noop). Here is my code. Any tips are appreciated.

import java.util.*;

public class Solution {

    static String result;

    static class StackOfVowels {
        static Node top;

        public StackOfVowels() {
            Node top = null;
        }

        static class Node {
            Node next = null;
            char vowel = '\0';
            Node(char value) {
                this.vowel = value;
            }
        }

        public void push(char item) {
            Node node = new Node(item);
            if (top == null) {
                top = node;
            }
            else {
                node.next = top;
                top = node;
            }
        }

        public char top() {
            if (top == null) throw new EmptyStackException();
            return top.vowel;
        }

        public void pop() {
            int result = -1;
            if (top != null) {
                result = top.vowel;
                top = top.next;
            }
        }
    }

    public static String reverseVowels(String s) {

        StackOfVowels stackOfVowels = new StackOfVowels();

        for(int i = s.length()-1; i >= 0; i--) {
            char c = s.charAt(i);
            if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u')) {
                System.out.println("Initial sequence of iterations identified vowel: " + c);
                stackOfVowels.push(c);
                System.out.println("Pushed to stack, current top is: " + stackOfVowels.top());
            }
        }

        for(int j = s.length()-1; j >= 0; j--) {
            char b = s.charAt(j);
            if ((b == 'a') || (b == 'e') || (b == 'i') || (b == 'o') || (b == 'u')) {
                System.out.println("Second sequence of iterations identified vowel: " + b);
                StringBuilder newstr = new StringBuilder(s);
                char d = stackOfVowels.top();
                System.out.println("Variable d set to top of: " + stackOfVowels.top());
                newstr.setCharAt(j, d);
                result = newstr.toString();
                System.out.println("Here is the new string: " + result);
                stackOfVowels.pop();
                System.out.println("Stack was popped");
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "aeiou";
        reverseVowels(s);
        System.out.println("Final result: " + result);
    }
}

Body:
You generate always a new StringBuilder in your second loop with StringBuilder newstr = new StringBuilder(s);
But you always use ´s´ and not ´result´ to build your new StringBuilder.

It would be better anyways to not create a new Object of StringBuilder in each Iteration.

Also it is confusing that your methode has a return value, which is never used.

Following methode should work:

public static String reverseVowels(String s) {

    StackOfVowels stackOfVowels = new StackOfVowels();

    for(int i = s.length()-1; i >= 0; i--) {
        char c = s.charAt(i);
        if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u')) {
            System.out.println("Initial sequence of iterations identified vowel: " + c);
            stackOfVowels.push(c);
            System.out.println("Pushed to stack, current top is: " + stackOfVowels.top());
        }
    }
    StringBuilder result_builder = new StringBuilder(s);
    for(int j = s.length()-1; j >= 0; j--) {
        char b = s.charAt(j);

        if ((b == 'a') || (b == 'e') || (b == 'i') || (b == 'o') || (b == 'u')) {
            System.out.println("Second sequence of iterations identified vowel: " + b);
            char d = stackOfVowels.top();
            System.out.println("Variable d set to top of: " + stackOfVowels.top());
            result_builder.setCharAt(j, d);
            stackOfVowels.pop();
            System.out.println("Stack was popped");
        }
    }
    result = result_builder.toString();
    return result_builder.toString();
}


问:
Java does not recognize ListView variable
I trying to create a ListView in AndroidStudio with value "nome". I created a list and a adapter for this, but my application not recognize variable "services".

This is my activity code

```<code>public class MainActivity extends AppCompatActivity {
    private String service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.list_item1);

        ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services); <-- in this line
        listView.setAdapter(servicesAdapter);

    }

    private List<Services> gerarServices(){
        List<Services> services  = new ArrayList<Services>();
        services.add(criarServices("Home"));
        services.add(criarServices("Delivery"));

        return services;
    }

    private Services criarServices(String nome){
        Services service = new Services(nome);
        return service;
    }
}
</code>```

Any suggestion? Thank's in advance!

答:
The services variable is not in the scope of your onCreate method. As mentioned by @Code-Apprentice, you might want to find out more about scope of local variables.

So, what you might want to do is to invoke the gerarServices() method in the onCreate method and assign it to a local variable which will then be passed to the ArrayAdapter. Like so:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.list_item1);

    List<Services> services = gerarServices();

    ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services);
    listView.setAdapter(servicesAdapter);

}
</code>```

or

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.list_item1);

    ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, gerarServices());
    listView.setAdapter(servicesAdapter);

}
</code>```

Hope it helps!

Body:
I trying to create a ListView in AndroidStudio with value "nome". I created a list and a adapter for this, but my application not recognize variable "services".

This is my activity code

public class MainActivity extends AppCompatActivity {
    private String service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.list_item1);

        ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services); <-- in this line
        listView.setAdapter(servicesAdapter);

    }

    private List<Services> gerarServices(){
        List<Services> services  = new ArrayList<Services>();
        services.add(criarServices("Home"));
        services.add(criarServices("Delivery"));

        return services;
    }

    private Services criarServices(String nome){
        Services service = new Services(nome);
        return service;
    }
}

Any suggestion? Thank's in advance!

Body:
The services variable is not in the scope of your onCreate method. As mentioned by @Code-Apprentice, you might want to find out more about scope of local variables.

So, what you might want to do is to invoke the gerarServices() method in the onCreate method and assign it to a local variable which will then be passed to the ArrayAdapter. Like so:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.list_item1);

    List<Services> services = gerarServices();

    ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services);
    listView.setAdapter(servicesAdapter);

}

or

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.list_item1);

    ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, gerarServices());
    listView.setAdapter(servicesAdapter);

}

Hope it helps!


问:
Native XML Web Services for SQL Server 2008
I want to share a few small tables from my SQL Server 2008 database. Client is html/javascript based. I started with Native XML Web Services for SQL Server, but it's deprecated in SQL Server 2008.

Is there any other quick and cheap solution, rather then building data service from scratch?

答:
WCF Data Services (REST-based HTTP services) are the way to go and basically replace the "native" SQL Server XML web services.

Read all about WCF Data Services and see lots of white papers, tutorials, intro videos and more. The WCF Data Services are Microsoft's concrete implementation of the OData protocol.


问:
AWS API Gateway Method Authorization
I have domain with aws example.com, currently I have record set so that when user goes to example.com, it serves static website from S3 (done with angular) and backend api (Lambda and API gate way). And I don't have sign in process, as the purpose of site is public facing.

I can use apikey on method to authorize the http call, but I still have to save it in js code somewhere, which I don;t want to do. And I am not sure how IAM role can help me in this scenario.

Is there any way I can let api allow calls from specific domain ?

答:
There are a few ways to skin this cat. </p>

<p>The least painful way is likely to be using AWS Signature V4-- unfortunately, there's no great answer for a site that doesn't have an auth system built in already. Someday they'll let us park API Gateways inside of VPCs, but that day isn't today. </p>

Title: AWS API Gateway Method Authorization

Body:
There are a few ways to skin this cat.

The least painful way is likely to be using AWS Signature V4-- unfortunately, there's no great answer for a site that doesn't have an auth system built in already. Someday they'll let us park API Gateways inside of VPCs, but that day isn't today.


问:
Having a struct variable represent the label
I'm really new to c and was using a struct to return an array, I managed to generate the struct just fine and use the struct as well, but I made a really ugly way of importing my array into my struct. Is there some way that I can do this with a for loop?

Here's my code that I currently use to transfer the array into the struct:

```<code>result.a = input3[0];
result.b = input3[1];
result.c = input3[2];
result.d = input3[3];
result.e = input3[4];
result.f = input3[5];
result.g = input3[6];
result.h = input3[7];
result.i = input3[8];
</code>```

I tried to have it work like this:

```<code>for (char j = 'a'; j <= 'i'; j++)
{
    result.j = input[j - 97];
}
</code>```

But, as makes sense, the error I get is 'j': is not a member of values and it refuses to compile. What formatting would it take to make the program realize that I'm trying to refrence a variable, and not the index of the struct?
Thanks!

答:
struct and array are two different animals and you should use the one which is most appropriate for the job. An array is meant to store a list of elements all of the same type. The elements of an array are accessed by a numeric index, so there is an ordering to the elements. On the other hand, a struct is intended to hold related data which may be of different types. You access the members of a struct by name. This allows us to ignore the order of the elements.

Granted, you can have an array inside a struct, but unless there are other data elements in the struct as well, you should just use a bare array instead of a struct with an array member.

Body:
I'm really new to c and was using a struct to return an array, I managed to generate the struct just fine and use the struct as well, but I made a really ugly way of importing my array into my struct. Is there some way that I can do this with a for loop?

Here's my code that I currently use to transfer the array into the struct:

result.a = input3[0];
result.b = input3[1];
result.c = input3[2];
result.d = input3[3];
result.e = input3[4];
result.f = input3[5];
result.g = input3[6];
result.h = input3[7];
result.i = input3[8];

I tried to have it work like this:

for (char j = 'a'; j <= 'i'; j++)
{
    result.j = input[j - 97];
}

But, as makes sense, the error I get is 'j': is not a member of values and it refuses to compile. What formatting would it take to make the program realize that I'm trying to refrence a variable, and not the index of the struct?
Thanks!


问:
Adding numbers forth column of first file to second file using awk.
Hoping somebody can help me with this task. I have two infiles,

File1

```<code># name                  length  av.qual #-reads mx.cov. av.cov  GC% CnIUPAC CnFunny CnN CnX CnGap   CnNoCov
10-1_rep_c1             1406    80  8017    4637    1641.26 31.98   1   0   4   0   7   0
10-1_rep_c2             832 80  1641    1462    557.34  32.13   1   0   0   0   5   0
10-1_rep_c3             1284    83  4674    2338    1040.80 24.75   7   0   0   0   8   0
10-1_rep_c4             750 83  2335    2017    886.31  24.73   2   0   0   0   3   0
10-1_rep_c5             1180    78  2326    1486    572.51  19.76   1   0   0   0   7   0
</code>```

File2

```<code>>10-1_rep_c1
ttttttttttttttacaataaaatgcrccattattcctttcgtactaaacaatgccttat
ggccaccagatagaaaccaatctgactcacgtcgattttaactcaaatcatgtaaaattc
>10-1_rep_c2
aacagcagaattaatattgttcacaggtttttataaaacgacctattaatgaatttccat
cccctaaaaatggtcggcttacttgatgtaaccaccccctctagttaataataattgtat
>10-1_rep_c3
aattataaaaagaatttttaaagcataaattattagtaattttaagagaaattaaaggta
ttataaaagagtaatagtactgacaaggaaaaacttttatataaaaaaaagaaaatttaa
</code>```

The outfile I would like to have is,

```<code>>10-1_rep_c1_8017
ttttttttttttttacaataaaatgcrccattattcctttcgtactaaacaatgccttat
ggccaccagatagaaaccaatctgactcacgtcgattttaactcaaatcatgtaaaattc
>10-1_rep_c2_1641
aacagcagaattaatattgttcacaggtttttataaaacgacctattaatgaatttccat
cccctaaaaatggtcggcttacttgatgtaaccaccccctctagttaataataattgtat
>10-1_rep_c3_4674
aattataaaaagaatttttaaagcataaattattagtaattttaagagaaattaaaggta
ttataaaagagtaatagtactgacaaggaaaaacttttatataaaaaaaagaaaatttaa
</code>```

So the fourth column of the first file appended onto the second file header of each DNA sequence.

答:
try following and let me know if this helps you.

```<code>awk 'FNR==NR{a[$1]=$4;next} ($2 in a){print $2"_"a[$2];next} 1' file1 FS=">" file2
</code>```

Explanation: So checking here first condition FNR==NR(which will be only TRUE when first file named file1 is being read, because FNR and NR both represent the number of lines in a Input_file only difference between them is NR's value will be keep on increasing till all files being read and FNR's value will be RESET each time when a new Input_file start to get read.), so in first file reading time creating an array named a whose index is $1 and value is $4(as per your ask), now mentioning next keyword which will make sure cursor shouldn't go further and it will skip all further statements then.
Now checking condition where checking if $2 of file2(whose field separator I have set as > to remove it from mix, NOTE: we could set field separators differently for different Input_files).

So if it is present then print 2nd field of Input_file file2 and "_" then array a's value whose index is $2 of file2, then mentioning next to skip further statements. Now mentioning 1 will be printing the lines(apart from whose $2 comes in array a as index, so awk works on method like condition then action. If any condition is TRUE then some action should happen. Here condition is TRUE by mentioning 1 and action is Not defined so by default print will happen, print of current line of file2).

Then mentioning the Input_file1 name as file1. After that mentioning the FS(field separator's value) to ">"(explained above too). After that mentioning the second Input_file as file2 too then.

Body:
Hoping somebody can help me with this task. I have two infiles,

File1

# name                  length  av.qual #-reads mx.cov. av.cov  GC% CnIUPAC CnFunny CnN CnX CnGap   CnNoCov
10-1_rep_c1             1406    80  8017    4637    1641.26 31.98   1   0   4   0   7   0
10-1_rep_c2             832 80  1641    1462    557.34  32.13   1   0   0   0   5   0
10-1_rep_c3             1284    83  4674    2338    1040.80 24.75   7   0   0   0   8   0
10-1_rep_c4             750 83  2335    2017    886.31  24.73   2   0   0   0   3   0
10-1_rep_c5             1180    78  2326    1486    572.51  19.76   1   0   0   0   7   0

File2

>10-1_rep_c1
ttttttttttttttacaataaaatgcrccattattcctttcgtactaaacaatgccttat
ggccaccagatagaaaccaatctgactcacgtcgattttaactcaaatcatgtaaaattc
>10-1_rep_c2
aacagcagaattaatattgttcacaggtttttataaaacgacctattaatgaatttccat
cccctaaaaatggtcggcttacttgatgtaaccaccccctctagttaataataattgtat
>10-1_rep_c3
aattataaaaagaatttttaaagcataaattattagtaattttaagagaaattaaaggta
ttataaaagagtaatagtactgacaaggaaaaacttttatataaaaaaaagaaaatttaa

The outfile I would like to have is,

>10-1_rep_c1_8017
ttttttttttttttacaataaaatgcrccattattcctttcgtactaaacaatgccttat
ggccaccagatagaaaccaatctgactcacgtcgattttaactcaaatcatgtaaaattc
>10-1_rep_c2_1641
aacagcagaattaatattgttcacaggtttttataaaacgacctattaatgaatttccat
cccctaaaaatggtcggcttacttgatgtaaccaccccctctagttaataataattgtat
>10-1_rep_c3_4674
aattataaaaagaatttttaaagcataaattattagtaattttaagagaaattaaaggta
ttataaaagagtaatagtactgacaaggaaaaacttttatataaaaaaaagaaaatttaa

So the fourth column of the first file appended onto the second file header of each DNA sequence.

Body:
try following and let me know if this helps you.

awk 'FNR==NR{a[$1]=$4;next} ($2 in a){print $2"_"a[$2];next} 1' file1 FS=">" file2

Explanation: So checking here first condition FNR==NR(which will be only TRUE when first file named file1 is being read, because FNR and NR both represent the number of lines in a Input_file only difference between them is NR's value will be keep on increasing till all files being read and FNR's value will be RESET each time when a new Input_file start to get read.), so in first file reading time creating an array named a whose index is $1 and value is $4(as per your ask), now mentioning next keyword which will make sure cursor shouldn't go further and it will skip all further statements then.
Now checking condition where checking if $2 of file2(whose field separator I have set as > to remove it from mix, NOTE: we could set field separators differently for different Input_files).

So if it is present then print 2nd field of Input_file file2 and "_" then array a's value whose index is $2 of file2, then mentioning next to skip further statements. Now mentioning 1 will be printing the lines(apart from whose $2 comes in array a as index, so awk works on method like condition then action. If any condition is TRUE then some action should happen. Here condition is TRUE by mentioning 1 and action is Not defined so by default print will happen, print of current line of file2).

Then mentioning the Input_file1 name as file1. After that mentioning the FS(field separator's value) to ">"(explained above too). After that mentioning the second Input_file as file2 too then.


问:
Paypal IOS SDK acceptCreditCards crashing
There is a very niche question, I have implemented the PayPal ios SDK as they have it in the sample project however when I change the acceptCreditCards variable to true. The pay with credit card button shows up however if you click it the app crashes. What other code do I have to add to make this work?

答: After doing some testing I realized that the problem was camera permissions. Paypal needs to use your camera a so you have to put camera permissions in your info.plist. TO do this simply add $(PRODUCT_NAME) camera use under the key Privacy - Camera Usage Description.


问:
Access EJB from different WAR in JBoss AS via injection
My Project structure is as follows

JBoss AS 7.1.3.Final-redhat-4

A war VWeb.war which contains an EJB , when VWeb is deployed I get the following

```<code> java:global/VWeb/QServiceImpl!com.vi.qciapi.QService
java:app/VWeb/QServiceImpl!com.vi.qciapi.QService
java:module/QServiceImpl!com.vi.qciapi.QService
java:global/VWeb/QServiceImpl
java:app/VWeb/QServiceImpl
java:module/QServiceImpl
</code>```

I have got another war (ControlWeb-portlet.war) which is a liferay project and I am trying to access the above EJB within a bean from ControlWeb-portlet . The bean is @ViewScoped This has been done based on a link found here

I have tried all these combinations but nothing seems to work

```<code>@Inject
QService qService;

@EJB
QService qService;

@EJB(mappedName="java:global/VWeb/QServiceImpl!com.vi.qciapi.QService")
QService qService;

@EJB(beanInterface=QService.class)
QService qService;

@EJB(mappedName="java:global/VWeb/QServiceImpl!com.vi.qciapi.QService")
QService qService;
</code>```

I kept an EJB in the same project ControlWeb-portlet which is deployed as follows

```<code>java:global/ControlWeb-portlet/CdiServiceImpl!com.clink.cdi.CdiServiceImpl
    java:app/ControlWeb-portlet/CdiServiceImpl!com.clink.cdi.CdiServiceImpl
    java:module/CdiServiceImpl!com.clink.cdi.CdiServiceImpl
    java:global/ControlWeb-portlet/CdiServiceImpl
    java:app/ControlWeb-portlet/CdiServiceImpl
    java:module/CdiServiceImpl
</code>```

and I am able to inject the EJB with

```<code>@EJB
CdiServiceImpl cdiServiceImpl;
</code>```

Is there anything specific that I have to while accessing an EJB from a different WAR

Thanks in advance

Charlie

答:
Apparently I answered this question on the JBoss forums a while ago. Since it was marked as the correct answer there, I thought I'd reproduce it here as well.

I got it to work using the following approach:

First, define EJBs as resources using the @Produces annotation:

```<code>public class Resources {
          @Produces
          @EJB(lookup = "java:global/.../WhateverService")
          private WhateverService whateverService;
}
</code>```

Then, inject the EJB resources in your bean using the @Inject annotation:

```<code>// ...
@Inject
private WhateverService whateverService;
// ...
</code>```

Works like a charm. I'm also using a similar CDI view scope approach.

Body:
My Project structure is as follows

JBoss AS 7.1.3.Final-redhat-4

A war VWeb.war which contains an EJB , when VWeb is deployed I get the following

 java:global/VWeb/QServiceImpl!com.vi.qciapi.QService
java:app/VWeb/QServiceImpl!com.vi.qciapi.QService
java:module/QServiceImpl!com.vi.qciapi.QService
java:global/VWeb/QServiceImpl
java:app/VWeb/QServiceImpl
java:module/QServiceImpl

I have got another war (ControlWeb-portlet.war) which is a liferay project and I am trying to access the above EJB within a bean from ControlWeb-portlet . The bean is @ViewScoped This has been done based on a link found here

I have tried all these combinations but nothing seems to work

@Inject
QService qService;

@EJB
QService qService;

@EJB(mappedName="java:global/VWeb/QServiceImpl!com.vi.qciapi.QService")
QService qService;

@EJB(beanInterface=QService.class)
QService qService;

@EJB(mappedName="java:global/VWeb/QServiceImpl!com.vi.qciapi.QService")
QService qService;

I kept an EJB in the same project ControlWeb-portlet which is deployed as follows

java:global/ControlWeb-portlet/CdiServiceImpl!com.clink.cdi.CdiServiceImpl
    java:app/ControlWeb-portlet/CdiServiceImpl!com.clink.cdi.CdiServiceImpl
    java:module/CdiServiceImpl!com.clink.cdi.CdiServiceImpl
    java:global/ControlWeb-portlet/CdiServiceImpl
    java:app/ControlWeb-portlet/CdiServiceImpl
    java:module/CdiServiceImpl

and I am able to inject the EJB with

@EJB
CdiServiceImpl cdiServiceImpl;

Is there anything specific that I have to while accessing an EJB from a different WAR

Thanks in advance

Charlie

Body:
Apparently I answered this question on the JBoss forums a while ago. Since it was marked as the correct answer there, I thought I'd reproduce it here as well.

I got it to work using the following approach:

First, define EJBs as resources using the @Produces annotation:

public class Resources {
          @Produces
          @EJB(lookup = "java:global/.../WhateverService")
          private WhateverService whateverService;
}

Then, inject the EJB resources in your bean using the @Inject annotation:

// ...
@Inject
private WhateverService whateverService;
// ...

Works like a charm. I'm also using a similar CDI view scope approach.


问:
Webpack using bootstrap - jquery is not defined
```<code>import $ from 'jquery';
require("./node_modules/bootstrap/dist/css/bootstrap.min.css")
require("./node_modules/bootstrap/js/dropdown.js")
import React from 'react';
import ReactDOM from 'react-dom';
var _ = require('lodash');
</code>```

Please refer above my setting . Some reason I've got error saying "Uncaught ReferenceError: jQuery is not defined() from dropdown.js

I also included the following lines at webpack.config.js

```<code>   plugins: [
    new webpack.NoErrorsPlugin({
        $: "jquery",
        jQuery: "jquery"
    })
]
</code>```

But, No luck - Still having jQuery undefined error.
Any idea ? Can someone help this issue please?

Many thanks

答:
In order for this code to work you must RESTART Node after the change:

```<code>// webpack.config.js
module.exports = {
    ...
    plugins: [
        new webpack.ProvidePlugin({
           $: "jquery",
           jQuery: "jquery"
       })
    ]
};
</code>```

Body:
import $ from 'jquery';
require("./node_modules/bootstrap/dist/css/bootstrap.min.css")
require("./node_modules/bootstrap/js/dropdown.js")
import React from 'react';
import ReactDOM from 'react-dom';
var _ = require('lodash');

Please refer above my setting . Some reason I've got error saying "Uncaught ReferenceError: jQuery is not defined() from dropdown.js

I also included the following lines at webpack.config.js

   plugins: [
    new webpack.NoErrorsPlugin({
        $: "jquery",
        jQuery: "jquery"
    })
]

But, No luck - Still having jQuery undefined error.
Any idea ? Can someone help this issue please?

Many thanks

Body:
In order for this code to work you must RESTART Node after the change:

// webpack.config.js
module.exports = {
    ...
    plugins: [
        new webpack.ProvidePlugin({
           $: "jquery",
           jQuery: "jquery"
       })
    ]
};


问:
Document create software using AngularJs?
I am currently developing a web application using Laravel and AngularJs. One of the requirement in document module is, that they want to create, update documents like Google Docs or Zoho Docs.

I googled but couldn't find a solution.

How can I implement it? It seems like that it is a big task.

答:
For goole docs you could use the following with angular js:
https://developers.google.com/drive/v3/web/examples/</p>


问:
Calculate the number of times to divide by two
Greetings.

I have a java method that I consider expensive, and I'm trying to replace some calls to it with a mathematical expression. Problem is, I suck at math. I mean really suck.

The following should explain the pattern that I'm trying to exploit.

```<code>f(x)   -> y
f(x*2) -> f(x)+1
</code>```

That is, whenever I double the value for x, the value for y will be 1 greater than for x/2.
Here are some example output:

```<code>f(5)   -> 6
f(10)  -> 7
f(20)  -> 8
f(40)  -> 9
f(80)  -> 10
f(160) -> 11
f(320) -> 12
</code>```

My current approach is brute force. I'm looping over the X and test how many times I can halve it before I reach 5, and finally I add 6. This works and is faster than the call to the original method. But I was looking for a more "elegant" or potentially cheaper solution.

Accepted answer goes to the one who manages to help me without pointing out how stupid I am :)

(the title probably sucks, because I don't know what I'm looking for)

Body:
Greetings.

I have a java method that I consider expensive, and I'm trying to replace some calls to it with a mathematical expression. Problem is, I suck at math. I mean really suck.

The following should explain the pattern that I'm trying to exploit.

f(x)   -> y
f(x*2) -> f(x)+1

That is, whenever I double the value for x, the value for y will be 1 greater than for x/2.
Here are some example output:

f(5)   -> 6
f(10)  -> 7
f(20)  -> 8
f(40)  -> 9
f(80)  -> 10
f(160) -> 11
f(320) -> 12

My current approach is brute force. I'm looping over the X and test how many times I can halve it before I reach 5, and finally I add 6. This works and is faster than the call to the original method. But I was looking for a more "elegant" or potentially cheaper solution.

Accepted answer goes to the one who manages to help me without pointing out how stupid I am :)

(the title probably sucks, because I don't know what I'm looking for)

Body:
Try this:

f(x) = log<sub>2</sub>(x/5) + 6


问:
ES6 arrow function 'this' puzzle in vue.js official github example
Here is the my fork from github example fiddle of vue.js offcial site: vue.js github example fiddle

I console.log(this) in fetchData function expression, and it outputs vue component instance:

But when I use arrow function with fetchData (fiddle of arrow function this), it console.log(this) is window

I had learned arrow function concept, but I still confuse this. Why the second fiddle this bind to the global window object, and the first fiddle this bind to vue component instance?

What condition can't I use arrow function this?

答:
You should never use an arrow function to define a method with Vue, because with arrow functions, this is defined lexically.

An arrow function does not create its own this, the this value of the
  enclosing execution context is used.

That means that, with Vue methods, this will point to the global object, or the window.

When a Vue is instantiated, Vue binds the methods defined in methods to the Vue object. An arrow function cannot be bound. It's this will always be the what it was originally.

That being the case, you should always use a normal function to write a Vue method.

This also applies to the data function, computed values, and lifecycle hooks. The only time you will generally use an arrow function is when you are defining a function inside one of your methods or computed values, as you might when defining a callback for an ajax call.

See VueJS: why is “this” undefined?.

Note: there is one exception to never using an arrow function to define a Vue method and that would be if you never referenced this at all in the method. Those cases are exceedingly rare. You almost always end up needing to reference other parts of the Vue inside a method using this. That being the case, it should quickly become a habit to simply never define a Vue method with an arrow function.


问:
How do I find the mean/median of the different values in a row?
I have a dataset in a csv file that looks like this:

```<code>teacher         student         student grade
Jon             marin           99
Jon             Rob             81
Jon             marly           90
Bon             martin          76
Bon             marie           56
Ton             Seri            43
Ton             Loku            99
</code>```

I need an output that has the average of each teacher based on the grades obtained by student. Which will look like this,

```<code>teacher         student         student grade       teacher Average
Jon             marin           99                  90
Jon             Rob             81                  90
Jon             marly           90                  90
Bon             martin          76                  66
Bon             marie           56                  66
Ton             Seri            43                  71
Ton             Loku            99                  71
</code>```

What is the shortest possible way to get this ?

This is my approach but it does not seem to work.

```<code>import pandas as pd
df = pd.read_csv('test.csv', names=['teacher', 'student', 'student grade','Average'])
df.groupby('Star Rating').mean()
</code>```

答:
Use groupby and transform to build a new column that is indexed the same as the one being grouped.

```<code>df['teacher average'] = df.groupby('teacher')['student grade'].transform('mean')
</code>```

Body:
I have a dataset in a csv file that looks like this:

teacher         student         student grade
Jon             marin           99
Jon             Rob             81
Jon             marly           90
Bon             martin          76
Bon             marie           56
Ton             Seri            43
Ton             Loku            99

I need an output that has the average of each teacher based on the grades obtained by student. Which will look like this,

teacher         student         student grade       teacher Average
Jon             marin           99                  90
Jon             Rob             81                  90
Jon             marly           90                  90
Bon             martin          76                  66
Bon             marie           56                  66
Ton             Seri            43                  71
Ton             Loku            99                  71

What is the shortest possible way to get this ?

This is my approach but it does not seem to work.

import pandas as pd
df = pd.read_csv('test.csv', names=['teacher', 'student', 'student grade','Average'])
df.groupby('Star Rating').mean()

Body:
Use groupby and transform to build a new column that is indexed the same as the one being grouped.

df['teacher average'] = df.groupby('teacher')['student grade'].transform('mean')


问:
FirebaseRecyclerAdapter still showing all items. Should not show any
I want FirebaseRecyclerAdapter to check if there invites ending with email address, and show uids. Somehow it output all data, as if there were no filtering and ordering.

Here is json data.

```<code>"invites" : {
  "4u60kmvvO9TwzBrLpP5SG4ICU9r1_test5%2E@test%2Etest" : {
    "cost" : "2",
  },
  "4u60kmvvO9TwzBrLpP5SG4ICU9r1_test4@test%2Etest" : {
    "costs" : "0"
  },
  "UQW5VEAojMOyB2WGTU9aTPUBepg1_test6%2E@test%2Etest" : {
    "costs" : "0"
  }
}
</code>```

I want to set FirebaseRecyclerAdapter. Here is adapter.

```<code> mAdapter = new FirebaseRecyclerAdapter<Event, UserHolder>(
      Event.class,
      R.layout.layout,
      UserHolder.class,
      ref.child("invites").orderByKey().endAt(encodeAsFirebaseKey(email))
 ) {}
</code>```

Why I'm getting all three items, when I test with test@test.test email? It seems that I've read documentation and it should work. Any ideas?

Update.

```<code> private String encodeAsFirebaseKey(String string) {
    return string.replace(".", "%2E");
}
</code>```

It returns test@test%2Etest.

```<code>     protected void populateViewHolder(final UserHolder viewHolder, Event model, final int position) {
     final String key = this.getRef(position).getKey().split("_")[0];
            viewHolder.setName(key);
            }
</code>```

答:
You seems to be confusing how endAt() works. It matches all strings, ending at the one that starts with the argument you pass. It does not match strings ending with the argument you pass.

So endAt("4u60kmvvO9TwzBrLpP5SG4ICU9r1_test4@test%2Etest") matches:

```<code>"4u60kmvvO9TwzBrLpP5SG4ICU9r1_test5%2E@test%2Etest" : {
  "cost" : "2",
},
"4u60kmvvO9TwzBrLpP5SG4ICU9r1_test4@test%2Etest" : {
  "costs" : "0"
},
</code>```

But endAt("test@test%2Etest") returns nothing, because no key starts with that.

Body:
I want FirebaseRecyclerAdapter to check if there invites ending with email address, and show uids. Somehow it output all data, as if there were no filtering and ordering.

Here is json data.

"invites" : {
  "4u60kmvvO9TwzBrLpP5SG4ICU9r1_test5%2E@test%2Etest" : {
    "cost" : "2",
  },
  "4u60kmvvO9TwzBrLpP5SG4ICU9r1_test4@test%2Etest" : {
    "costs" : "0"
  },
  "UQW5VEAojMOyB2WGTU9aTPUBepg1_test6%2E@test%2Etest" : {
    "costs" : "0"
  }
}

I want to set FirebaseRecyclerAdapter. Here is adapter.

 mAdapter = new FirebaseRecyclerAdapter<Event, UserHolder>(
      Event.class,
      R.layout.layout,
      UserHolder.class,
      ref.child("invites").orderByKey().endAt(encodeAsFirebaseKey(email))
 ) {}

Why I'm getting all three items, when I test with test@test.test email? It seems that I've read documentation and it should work. Any ideas?

Update.

 private String encodeAsFirebaseKey(String string) {
    return string.replace(".", "%2E");
}

It returns test@test%2Etest.

     protected void populateViewHolder(final UserHolder viewHolder, Event model, final int position) {
     final String key = this.getRef(position).getKey().split("_")[0];
            viewHolder.setName(key);
            }

Body:
You seems to be confusing how endAt() works. It matches all strings, ending at the one that starts with the argument you pass. It does not match strings ending with the argument you pass.

So endAt("4u60kmvvO9TwzBrLpP5SG4ICU9r1_test4@test%2Etest") matches:

"4u60kmvvO9TwzBrLpP5SG4ICU9r1_test5%2E@test%2Etest" : {
  "cost" : "2",
},
"4u60kmvvO9TwzBrLpP5SG4ICU9r1_test4@test%2Etest" : {
  "costs" : "0"
},

But endAt("test@test%2Etest") returns nothing, because no key starts with that.


问:
Html - Open a link to a file in browser instead of download
This might be a basic question but I have a link to a file

```<code><a href = "http://sitename.com/path/to/file.jpg">File Name</a>
</code>```

I want to leave it a link, but when I click it the image just downloads. I would like for it to open in the browser instead of downloading. How can I do this? I feel like this should be easy, but for some reason I can't find the solution.

答:
Your webserver isn't sending the right headers.

If you curl -I http://sitename.com/path/to/file.jpg you should see a header Content-Type.

The correct answer is:
Content-Type: image/jpeg

More specific answers are going to depend upon what webserver you're using.

Body:
This might be a basic question but I have a link to a file

File Name

I want to leave it a link, but when I click it the image just downloads. I would like for it to open in the browser instead of downloading. How can I do this? I feel like this should be easy, but for some reason I can't find the solution.


问:
Java Spring @Scheduled tasks executing twice
I have a simple test method here that is set to run every 5 seconds and it does, but looking at the System.out you can see it appears to be doing something odd.

```<code>@Scheduled(cron="*/5 * * * * ?")
public void testScheduledMethod() {
     System.out.println(new Date()+" > Running testScheduledMethod...");
}
</code>```

Output:

```<code>Wed Jan 09 16:49:15 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:15 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:20 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:20 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:25 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:25 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:30 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:30 GMT 2013 > Running testScheduledMethod...
</code>```

Why is it running TWICE (appear) each time?

答:
I had the same problem.  Spent hours trying to resolve.

Solution was the application was deploying twice on Tomcat.

When trying to clean Tomcat it gave an error.

Checking the server.xml Tomcat file I noticed the same was being deployed twice.  There was also an unclosed "host" tag.  Not sure which of these fixed it but relieved to have it working properly again.

Body:
I have a simple test method here that is set to run every 5 seconds and it does, but looking at the System.out you can see it appears to be doing something odd.

@Scheduled(cron="*/5 * * * * ?")
public void testScheduledMethod() {
     System.out.println(new Date()+" > Running testScheduledMethod...");
}

Output:

Wed Jan 09 16:49:15 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:15 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:20 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:20 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:25 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:25 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:30 GMT 2013 > Running testScheduledMethod...
Wed Jan 09 16:49:30 GMT 2013 > Running testScheduledMethod...

Why is it running TWICE (appear) each time?


问:
Problem in creating two identity columns in a single table
I am having a problem in creating two identity columns in a single table. This is my part of job... They need two identity columns in a single table at  any cost. Is there any way to do this.

Please provide any syntax for creating two identity columns in a single table at a time or later also.

Thanks in Advance,
Shashra

答:
In SQL Server, you can have a computed column which just holds the same value as an identity (or any other) column:</p>

```<code>CREATE TABLE [dbo].[test](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [idCopy]  AS ([id]),
    [whatever] [nvarchar](max) NOT NULL
)
</code>```

Body:
In SQL Server, you can have a computed column which just holds the same value as an identity (or any other) column:

CREATE TABLE [dbo].[test](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [idCopy]  AS ([id]),
    [whatever] [nvarchar](max) NOT NULL
)


答:
Assuming there is atleast one type=30 row preceding type=70 per id, you can do this using outer apply, getting the max time for type=30 before each type=70 row and using that value for division.

```<code>SELECT x.id,
       x.type,
       x.time,
       x.data*1.0/t.data as result
FROM
  (SELECT t.*,t1.maxtime_before
   FROM t
   OUTER APPLY
     (SELECT max(time) AS maxtime_before
      FROM t t1
      WHERE t1.id=t.id AND t1.type=30 AND t1.time<t.time) t1
   WHERE type = 70
  ) x
JOIN t ON t.id=x.id AND t.time=x.maxtime_before
</code>```

If there is no row with type=30 preceding a type=70 row, you can show a null value for that time in the result column using

```<code>WITH x AS
  (SELECT t.*,
          t1.maxtime_before
   FROM t
   OUTER APPLY
     (SELECT max(time) AS maxtime_before
      FROM t t1
      WHERE t1.id=t.id AND t1.type=30 AND t1.time<t.time) t1
   WHERE type = 70
  )
SELECT x.id,
       x.type,
       x.time,
       x.data*1.0/t.data as resullt
FROM t
JOIN x ON t.id=x.id AND t.time=x.maxtime_before
UNION ALL
SELECT id,
       type,
       time,
       NULL
FROM x
WHERE maxtime_before IS NULL
</code>```

Sample Demo

One more way to do it is using max window function to keep track of the running max time of type=30 row per id.

```<code>WITH x AS
  (SELECT t.*,
          MAX(CASE WHEN type=30 THEN time END) OVER(PARTITION BY id ORDER BY time) AS running_max
   FROM t
  )
SELECT x.id,
       x.type,
       x.time,
       x.data*1.0/t.data as result
FROM x
JOIN t ON t.id=x.id AND t.time=x.running_max
WHERE x.type=70
UNION ALL
SELECT id,
       type,
       time,
       NULL
FROM x
WHERE running_max IS NULL
</code>```

Title: SQL query to compute calculations from different rows of the same table in SQL server

Body:
I want a SQL query for the following. I am a novice in SQL. And below table is just an example of the kind of data I have. I have very big data of about 30 million rows and would like to write a query to get the below output table.

   Id        type        data          time
-----------------------------------------------------------
    1          30          3.9          15:50:10.660555
    1          30          4.0          15:50:10.660777
    1          70          11.5         15:50:10.797966
    1          30          4.1          15:50:10.834444
    1          70          12.6         15:50:10.853114
    1          70          16.7         15:50:10.955086
    1          30          5            15:50:10.99
    11         30          3.8          15:50:11.660555
    11         30          4.1          15:50:11.660777
    11         70          12.5         15:50:11.797966
    11         30          4.7          15:50:11.834444
    11         70          12.68        15:50:11.853114
    11         70          16.76        15:50:11.955086
    11         30          5.1          15:50:11.99

I have a table like the above. For each type 70, I need to calculate something with the last known type 30. For instance, for Id = 1, for the first type = 70 data at 15:50:10.797966, I need to get type = 30 data at 15:50:10.660777 so that I can calculate result = 11.5/4.0. Similarly, for type = 70 at 15:50:10.853114, I want data of type = 30 at 15:50:10.834444, so my result = 12.6/4.1.

I want the output to look like this:

Id          type           result             time
------------------------------------------------------
1            70             11.5/4.0        15:50:10.797966
1            70             12.6/4.1        15:50:10.853114
1            70             16.7/4.1        15:50:10.955086
11           70             12.5/4.1        15:50:11.797966
11           70             12.68/4.7       15:50:11.853114
11           70             16.76/4.7       15:50:11.955086

I would like to be able to execute these SQL queries in python using pyodbc.

Any help would be greatly appreciated! Thanks in advance!!

Body:
Assuming there is atleast one type=30 row preceding type=70 per id, you can do this using outer apply, getting the max time for type=30 before each type=70 row and using that value for division.

SELECT x.id,
       x.type,
       x.time,
       x.data*1.0/t.data as result
FROM
  (SELECT t.*,t1.maxtime_before
   FROM t
   OUTER APPLY
     (SELECT max(time) AS maxtime_before
      FROM t t1
      WHERE t1.id=t.id AND t1.type=30 AND t1.time<t.time) t1
   WHERE type = 70
  ) x
JOIN t ON t.id=x.id AND t.time=x.maxtime_before

If there is no row with type=30 preceding a type=70 row, you can show a null value for that time in the result column using

WITH x AS
  (SELECT t.*,
          t1.maxtime_before
   FROM t
   OUTER APPLY
     (SELECT max(time) AS maxtime_before
      FROM t t1
      WHERE t1.id=t.id AND t1.type=30 AND t1.time<t.time) t1
   WHERE type = 70
  )
SELECT x.id,
       x.type,
       x.time,
       x.data*1.0/t.data as resullt
FROM t
JOIN x ON t.id=x.id AND t.time=x.maxtime_before
UNION ALL
SELECT id,
       type,
       time,
       NULL
FROM x
WHERE maxtime_before IS NULL

Sample Demo

One more way to do it is using max window function to keep track of the running max time of type=30 row per id.

WITH x AS
  (SELECT t.*,
          MAX(CASE WHEN type=30 THEN time END) OVER(PARTITION BY id ORDER BY time) AS running_max
   FROM t
  )
SELECT x.id,
       x.type,
       x.time,
       x.data*1.0/t.data as result
FROM x
JOIN t ON t.id=x.id AND t.time=x.running_max
WHERE x.type=70
UNION ALL
SELECT id,
       type,
       time,
       NULL
FROM x
WHERE running_max IS NULL


问:
Bootstrap 4 responsive tables won't take up 100% width
I am building a web app using Bootstrap 4 and running into some weird issues.  I want to utilize Bootstrap's table-responsive class to allow horizontal scrolling of the tables on mobile devices.   On desktop devices the table should take up 100% of the containing DIV's width.

As soon as I apply the .table-responsive class to my table, the table shrinks horizontally and no longer takes up 100% of the width.   Any ideas?

Here is my markup:

```<code><!DOCTYPE html>
<html lang="en" class="mdl-js">
<head>
    <title></title>
    <meta charset="utf-8">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="application-name" content="">
    <meta name="theme-color" content="#000000">
    <link rel="stylesheet" href="/css/bundle.min.css">
</head>
<body>
    <div class="container-fluid no-padding">
        <div class="row">
            <div class="col-md-12">
                <table class="table table-responsive" id="Queue">
                    <thead>
                        <tr>
                            <th><span span="sr-only">Priority</span></th>
                            <th>Origin</th>
                            <th>Destination</th>
                            <th>Mode</th>
                            <th>Date</th>
                            <th><span span="sr-only">Action</span></th>
                         </tr>
                      </thead>
                      <tbody>
                          <tr class="trip-container" id="row-6681470c-91ce-eb96-c9be-8e89ca941e9d" data-id="6681470c-91ce-eb96-c9be-8e89ca941e9d">
                              <td>0</td>
                              <td>PHOENIX, AZ</td>
                              <td>SAN DIEGO, CA</td>
                              <td>DRIVING</td>
                              <td><time datetime="2017-01-15T13:59">2017-01-15 13:59:00</time></td>
                              <td><span class="trip-status-toggle fa fa-stop" data-id="6681470c-91ce-eb96-c9be-8e89ca941e9d" data-trip-status="1"></span></td>
                          </tr>
                          <tr class="steps-container" data-steps-for="6681470c-91ce-eb96-c9be-8e89ca941e9d" style="display: none;">
                              <td colspan="6" class="no-padding"></td>
                          </tr>
                      </tbody>
                  </table>
              </div>
           </div>
           <br>
        </div>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script type="text/javascript" src="/js/bundle.min.js"></script>
     </body>
</html>
</code>```

If I apply a 100% width to the .table-responsive class, it makes the table itself a 100% wide but the child elements (TBODY, TR, etc.) are still narrow.

答:
Taking in consideration the other answers I would do something like this, thanks!</p>

```<code>.table-responsive {
    @include media-breakpoint-up(md) {
        display: table;
    }
}
</code>```

Body:
I am building a web app using Bootstrap 4 and running into some weird issues.  I want to utilize Bootstrap's table-responsive class to allow horizontal scrolling of the tables on mobile devices.   On desktop devices the table should take up 100% of the containing DIV's width.

As soon as I apply the .table-responsive class to my table, the table shrinks horizontally and no longer takes up 100% of the width.   Any ideas?

Here is my markup:

<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="application-name" content="">
    <meta name="theme-color" content="#000000">
    <link rel="stylesheet" href="/css/bundle.min.css">

                            Priority
                            Origin
                            Destination
                            Mode
                            Date
                            Action

                              0
                              PHOENIX, AZ
                              SAN DIEGO, CA
                              DRIVING
                              <time datetime="2017-01-15T13:59">2017-01-15 13:59:00</time>

If I apply a 100% width to the .table-responsive class, it makes the table itself a 100% wide but the child elements (TBODY, TR, etc.) are still narrow.

Body:
Taking in consideration the other answers I would do something like this, thanks!

.table-responsive {
    @include media-breakpoint-up(md) {
        display: table;
    }
}


问:
How is android.R.id.text1 being used in this tutorial without a widget in the layout with the same ID?
I'm following along with this tutorial to build a sample android app using Retrofit and the StackOverflow API. In their MainActivity code on the onClick(View v) method they are referencing the view android.R.id.text1 but I do not see anything in their layout files with the ID of "text1". How can this be?

Also, I'm used to using OnClickListener as an anonymous inner-class. In this example the entire MainActivity implements OnClickListener and onClick(View) is overridden in the class itself. Is there any benefit to doing it this way? They're using a switch statement to determine which layout item is being clicked and putting all the actions in the single onClick(View) method.

Thanks!

答:
Citing from here, android.R.id.text1 is an identifier for a TextView.

As for your second question, this post seems to have the answer.

Bonus: Checkout ButterKnife to handle user interactions. Give it a try!