问:
Need help improving this GIF appearance while it runs inside shiny
I'm trying to run a GIF inside my shiny App. I'm technically using this code to generate a GIF and upload it manually from my computer inside the APP. Part of my dataset is shown below, what I'm trying to do is run a GIF that shows the top 10 movies from 1960 - 2015.

this is the link to my GIF.
https://media.giphy.com/media/U4eSLRaDbGpjqU0V42/giphy.gif

This is my a picture of my App - (https://imgur.com/3Ddao5S)
I need to address 4 problems.

1 - First when I run this on my Shiny tab the movie names some of them are well cut out, you can't few them fully. How do I fix its orientation?

2 - I want the revenue at the end shown like 1M or 3M or 300M NOT 2554489 and definitely NOT like 1e+ 554 etc
Is there a way to set the X axis like that?

3 - The gridlines are ugly AF how do I remove them?

4 - Slow it down, HOW?

Yes, I know my App is not directly rendering the GIF, I spent weeks couldn't do it GIF created inside just doesn't work.

```<code>ui <- fluidPage(theme = shinytheme("cerulean"),
                titlePanel(p(strong("Movie browser, 1960 - 2014", windowTitle = "Movies"))),

                # Sidebar layout with a input and output definitions
                sidebarLayout(
mainPanel(
                    tabsetPanel(
                     tabPanel(h4(p(strong("GIF"))), tags$img(src = "outfile.GIF"))
                  )
                )
)

</code>```

```<code>structure(list(id = c(135397L, 135397L, 76341L, 76341L, 262500L,
140607L, 140607L, 140607L, 168259L, 168259L), budget = c(150000000L,
150000000L, 150000000L, 150000000L, 110000000L, 200000000L, 200000000L,
200000000L, 190000000L, 190000000L), revenue = c(1513528810,
1513528810, 378436354, 378436354, 295238201, 2068178225, 2068178225,
2068178225, 1506249360, 1506249360), title = structure(c(3L,
3L, 4L, 4L, 2L, 5L, 5L, 5L, 1L, 1L), .Label = c("Furious 7",
"Insurgent", "Jurassic World", "Mad Max: Fury Road", "Star Wars: The Force Awakens"
), class = "factor"), homepage = structure(c(2L, 2L, 3L, 3L,
5L, 4L, 4L, 4L, 1L, 1L), .Label = c("http://www.furious7.com/",
"http://www.jurassicworld.com/", "http://www.madmaxmovie.com/",
"http://www.starwars.com/films/star-wars-episode-vii", "http://www.thedivergentseries.movie/#insurgent"
), class = "factor"), director = structure(c(1L, 1L, 2L, 2L,
5L, 3L, 3L, 3L, 4L, 4L), .Label = c("Colin Trevorrow", "George Miller",
"J.J. Abrams", "James Wan", "Robert Schwentke"), class = "factor"),
    runtime = c(124L, 124L, 120L, 120L, 119L, 136L, 136L, 136L,
    137L, 137L), vote_average = c(6.5, 6.5, 7.1, 7.1, 6.3, 7.5,
    7.5, 7.5, 7.3, 7.3), release_year = c(2015L, 2015L, 2015L,
    2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L), genre = structure(c(1L,
    2L, 1L, 2L, 2L, 1L, 2L, 4L, 1L, 3L), .Label = c("Action",
    "Adventure", "Crime", "Fantasy"), class = "factor"), breakeven = c(1363528810,
    1363528810, 228436354, 228436354, 185238201, 1868178225,
    1868178225, 1868178225, 1316249360, 1316249360), AerageVotesCat = structure(c(2L,
    2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("Excellent",
    "Good"), class = "factor")), row.names = c(NA, 10L), class = "data.frame")
</code>```

```<code>UI:
# library(gifski)
library(ggplot2)
library(gganimate)
library(dplyr)
library(scales)
library(shiny)

  output$plot2 <- renderImage({
    df2 <- df1 %>%
      group_by(release_year) %>%
      # The * 1 makes it possible to have non-integer ranks while sliding
      mutate(rank = rank(-revenue),
             Value_rel = revenue/revenue[rank==1],
             Value_lbl = paste0(" ",round(revenue))) %>%
      group_by(title) %>%
      filter(rank <=10) %>%
      ungroup()
    staticplot = ggplot(df2, aes(rank, group = title,
                                           fill = as.factor(title), color = as.factor(title))) +
      geom_tile(aes(y = revenue/2,
                    height = revenue,
                    width = 0.9), alpha = 0.8, color = NA) +
      geom_text(aes(y = 0, label = paste(title, " ")), vjust = 0.2, hjust = 1) +
      geom_text(aes(y=revenue,label = Value_lbl, hjust=0)) +
      coord_flip(clip = "off", expand = FALSE) +
      scale_y_continuous(labels = scales::comma) +
      scale_x_reverse() +
      guides(color = FALSE, fill = FALSE) +
      theme(axis.line=element_blank(),
            axis.text.x=element_blank(),
            axis.text.y=element_blank(),
            axis.ticks=element_blank(),
            axis.title.x=element_blank(),
            axis.title.y=element_blank(),
            legend.position="none",
            panel.background=element_blank(),
            panel.border=element_blank(),
            panel.grid.major=element_blank(),
            panel.grid.minor=element_blank(),
            panel.grid.major.x = element_line( size=.1, color="grey" ),
            panel.grid.minor.x = element_line( size=.1, color="grey" ),
            plot.title=element_text(size=25, hjust=0.5, face="bold", colour="grey", vjust=-1),
            plot.subtitle=element_text(size=18, hjust=0.5, face="italic", color="grey"),
            plot.caption =element_text(size=8, hjust=0.5, face="italic", color="grey"),
            plot.background=element_blank(),
            plot.margin = margin(2,2, 2, 4, "cm"))

    anim = staticplot + transition_states(release_year, transition_length = 4, state_length = 1) +
      view_follow(fixed_x = TRUE)  +
      labs(title = 'Revenue ($) per Year for the top 10 movies : {closest_state}',
           subtitle  =  "Top 10 Movies",
           caption  = "Revenue in USD | Data Source: Kaggle")
    anim_save("outfile.gif",animate(anim, 200, fps = 4,  width = 800, height = 900))
  })

    }
  )

}

# Create the Shiny app object
shinyApp(ui = ui, server = server)
</code>```

答:
I do not know answers to all of your questions, but please have a look at the self-sustainable code below:

```<code>library(ggplot2)
library(reshape2)
library(scales)

example_df <- data.frame(movie=c("A", "B", "C", "D"),
                         revenue=c(3354823, 1284690, 8513581, 4699102))
x_cols <- scales::hue_pal()(length(levels(example_df$movie)))
names(x_cols) <- levels(example_df$movie)

ggplot(data=example_df) + geom_bar(aes(x=movie, y=revenue, fill=movie), stat="identity") +
  scale_y_continuous(labels = dollar_format(scale=10^-6, suffix="M")) +
  theme_bw() +
  theme(axis.text.x = element_text(angle=45,
                                   colour=x_cols[substr(levels(example_df$movie),1,1)]),
        panel.grid = element_blank())
</code>```

I would start with the statement that you may be over-complicating things not using geom_bar. It was designed precisely to handle the kind of data you want to show. Thus it would be profitable to stick with it. If you want to colour the labels of a bar plot with the same colours as bars themselves you could follow the trick shown here: Color axis labels by group, which I shamelessly applied to my example.

Ad. 1.
This is the most tricky part to reproduce, and the reasons can be plenty. One sure way to circumvent that is to rotate names slightly, using angle parameter of the element_text function. This will work as long as you resort back to a bar plot.

Ad. 2.
Use the great scales library. dollar_format is the function you look for (although the name is pretty confusing).

Ad. 3.
panel.grid in the theme function.

Body:
I'm trying to run a GIF inside my shiny App. I'm technically using this code to generate a GIF and upload it manually from my computer inside the APP. Part of my dataset is shown below, what I'm trying to do is run a GIF that shows the top 10 movies from 1960 - 2015.

this is the link to my GIF.
https://media.giphy.com/media/U4eSLRaDbGpjqU0V42/giphy.gif

This is my a picture of my App - (https://imgur.com/3Ddao5S)
I need to address 4 problems.

1 - First when I run this on my Shiny tab the movie names some of them are well cut out, you can't few them fully. How do I fix its orientation?

2 - I want the revenue at the end shown like 1M or 3M or 300M NOT 2554489 and definitely NOT like 1e+ 554 etc
Is there a way to set the X axis like that?

3 - The gridlines are ugly AF how do I remove them?

4 - Slow it down, HOW?

Yes, I know my App is not directly rendering the GIF, I spent weeks couldn't do it GIF created inside just doesn't work.

ui <- fluidPage(theme = shinytheme("cerulean"),
                titlePanel(p(strong("Movie browser, 1960 - 2014", windowTitle = "Movies"))),

                # Sidebar layout with a input and output definitions
                sidebarLayout(
mainPanel(
                    tabsetPanel(
                     tabPanel(h4(p(strong("GIF"))), tags$img(src = "outfile.GIF"))
                  )
                )
)

structure(list(id = c(135397L, 135397L, 76341L, 76341L, 262500L,
140607L, 140607L, 140607L, 168259L, 168259L), budget = c(150000000L,
150000000L, 150000000L, 150000000L, 110000000L, 200000000L, 200000000L,
200000000L, 190000000L, 190000000L), revenue = c(1513528810,
1513528810, 378436354, 378436354, 295238201, 2068178225, 2068178225,
2068178225, 1506249360, 1506249360), title = structure(c(3L,
3L, 4L, 4L, 2L, 5L, 5L, 5L, 1L, 1L), .Label = c("Furious 7",
"Insurgent", "Jurassic World", "Mad Max: Fury Road", "Star Wars: The Force Awakens"
), class = "factor"), homepage = structure(c(2L, 2L, 3L, 3L,
5L, 4L, 4L, 4L, 1L, 1L), .Label = c("http://www.furious7.com/",
"http://www.jurassicworld.com/", "http://www.madmaxmovie.com/",
"http://www.starwars.com/films/star-wars-episode-vii", "http://www.thedivergentseries.movie/#insurgent"
), class = "factor"), director = structure(c(1L, 1L, 2L, 2L,
5L, 3L, 3L, 3L, 4L, 4L), .Label = c("Colin Trevorrow", "George Miller",
"J.J. Abrams", "James Wan", "Robert Schwentke"), class = "factor"),
    runtime = c(124L, 124L, 120L, 120L, 119L, 136L, 136L, 136L,
    137L, 137L), vote_average = c(6.5, 6.5, 7.1, 7.1, 6.3, 7.5,
    7.5, 7.5, 7.3, 7.3), release_year = c(2015L, 2015L, 2015L,
    2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L), genre = structure(c(1L,
    2L, 1L, 2L, 2L, 1L, 2L, 4L, 1L, 3L), .Label = c("Action",
    "Adventure", "Crime", "Fantasy"), class = "factor"), breakeven = c(1363528810,
    1363528810, 228436354, 228436354, 185238201, 1868178225,
    1868178225, 1868178225, 1316249360, 1316249360), AerageVotesCat = structure(c(2L,
    2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("Excellent",
    "Good"), class = "factor")), row.names = c(NA, 10L), class = "data.frame")

UI:
# library(gifski)
library(ggplot2)
library(gganimate)
library(dplyr)
library(scales)
library(shiny)

  output$plot2 <- renderImage({
    df2 <- df1 %>%
      group_by(release_year) %>%
      # The * 1 makes it possible to have non-integer ranks while sliding
      mutate(rank = rank(-revenue),
             Value_rel = revenue/revenue[rank==1],
             Value_lbl = paste0(" ",round(revenue))) %>%
      group_by(title) %>%
      filter(rank <=10) %>%
      ungroup()
    staticplot = ggplot(df2, aes(rank, group = title,
                                           fill = as.factor(title), color = as.factor(title))) +
      geom_tile(aes(y = revenue/2,
                    height = revenue,
                    width = 0.9), alpha = 0.8, color = NA) +
      geom_text(aes(y = 0, label = paste(title, " ")), vjust = 0.2, hjust = 1) +
      geom_text(aes(y=revenue,label = Value_lbl, hjust=0)) +
      coord_flip(clip = "off", expand = FALSE) +
      scale_y_continuous(labels = scales::comma) +
      scale_x_reverse() +
      guides(color = FALSE, fill = FALSE) +
      theme(axis.line=element_blank(),
            axis.text.x=element_blank(),
            axis.text.y=element_blank(),
            axis.ticks=element_blank(),
            axis.title.x=element_blank(),
            axis.title.y=element_blank(),
            legend.position="none",
            panel.background=element_blank(),
            panel.border=element_blank(),
            panel.grid.major=element_blank(),
            panel.grid.minor=element_blank(),
            panel.grid.major.x = element_line( size=.1, color="grey" ),
            panel.grid.minor.x = element_line( size=.1, color="grey" ),
            plot.title=element_text(size=25, hjust=0.5, face="bold", colour="grey", vjust=-1),
            plot.subtitle=element_text(size=18, hjust=0.5, face="italic", color="grey"),
            plot.caption =element_text(size=8, hjust=0.5, face="italic", color="grey"),
            plot.background=element_blank(),
            plot.margin = margin(2,2, 2, 4, "cm"))

    anim = staticplot + transition_states(release_year, transition_length = 4, state_length = 1) +
      view_follow(fixed_x = TRUE)  +
      labs(title = 'Revenue ($) per Year for the top 10 movies : {closest_state}',
           subtitle  =  "Top 10 Movies",
           caption  = "Revenue in USD | Data Source: Kaggle")
    anim_save("outfile.gif",animate(anim, 200, fps = 4,  width = 800, height = 900))
  })

    }
  )

}

# Create the Shiny app object
shinyApp(ui = ui, server = server)

Body:
I do not know answers to all of your questions, but please have a look at the self-sustainable code below:

library(ggplot2)
library(reshape2)
library(scales)

example_df <- data.frame(movie=c("A", "B", "C", "D"),
                         revenue=c(3354823, 1284690, 8513581, 4699102))
x_cols <- scales::hue_pal()(length(levels(example_df$movie)))
names(x_cols) <- levels(example_df$movie)

ggplot(data=example_df) + geom_bar(aes(x=movie, y=revenue, fill=movie), stat="identity") +
  scale_y_continuous(labels = dollar_format(scale=10^-6, suffix="M")) +
  theme_bw() +
  theme(axis.text.x = element_text(angle=45,
                                   colour=x_cols[substr(levels(example_df$movie),1,1)]),
        panel.grid = element_blank())

I would start with the statement that you may be over-complicating things not using geom_bar. It was designed precisely to handle the kind of data you want to show. Thus it would be profitable to stick with it. If you want to colour the labels of a bar plot with the same colours as bars themselves you could follow the trick shown here: Color axis labels by group, which I shamelessly applied to my example.

Ad. 1.
This is the most tricky part to reproduce, and the reasons can be plenty. One sure way to circumvent that is to rotate names slightly, using angle parameter of the element_text function. This will work as long as you resort back to a bar plot.

Ad. 2.
Use the great scales library. dollar_format is the function you look for (although the name is pretty confusing).

Ad. 3.
panel.grid in the theme function.


来源: stackexchange

问:
Chrome Autofill wrong fields when saved password
I have 2 form in my website.
If I saved the email and password and other form have input password,
It will autofill email on last one input box (type=text)

I try to add autocomplete=off autocomplete=contact_no name=contact_no
but It doesn't work.

```<code>    <form>
      login form
      <br>
      <label> email<input type="text" /> </label>
      <label> password <input type="password"/> </label>

      <button type="submit"> submit</button>
    </form>

    <form>
      member update form
      <br>
      <label> readonly email <input type="text"readonly value="abc@google.com"/> </label>
      <label> contact_no <input type="text" name="contact_no" autocomplete="off"/> </label>
      <label> password <input type="password" name="password"/> </label>
      <button type="submit"> submit</button>
    </form>
</code>```

CodePen

https://upload.cc/i1/2019/05/26/jbBSxa.gif

https://upload.cc/i1/2019/05/26/lQmksB.png

答:
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete

In most modern browsers, setting autocomplete to "off" will not prevent a password manager >from asking the user if they would like to save username and password information, or from >automatically filling in those values in a site's login form.

To help chrome understand the form input better, you can try using autocomplete="tel" instead for the contact no

ContentLicense: CC BY-SA 4.0

Body:
I have 2 form in my website.
If I saved the email and password and other form have input password,
It will autofill email on last one input box (type=text)

I try to add autocomplete=off autocomplete=contact_no name=contact_no
but It doesn't work.

    <form>
      login form

       email<input type="text" />
       password <input type="password"/>

      <button type="submit"> submit</button>
    </form>

    <form>
      member update form

       readonly email <input type="text"readonly value="abc@google.com"/>
       contact_no <input type="text" name="contact_no" autocomplete="off"/>
       password <input type="password" name="password"/>
      <button type="submit"> submit</button>
    </form>

CodePen

https://upload.cc/i1/2019/05/26/jbBSxa.gif

https://upload.cc/i1/2019/05/26/lQmksB.png


问:
How to delete duplicate from this result
How to delete duplicate from this result

```<code>select *,
       row_number() over (order by (select null)) as seqnum
from [elo].[dbo].[objkeys]
where parentid in (select parentid
                   from [elo].[dbo].[objekte]
                   inner join [elo].[dbo].[objkeys] on objid = parentid
                   where objmask like 26 and okeydata like 'yes'
                   )
</code>```

output is

```<code>parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1        yes_no   yes
  2          name   a
  2      number     1
  2        yes_no   yes
  3          name   a
  3      number     1
  3        yes_no   no
  4          name   a
  4      number     2
  4          yes_no no
  5          name   b
  5      number     3
  5          yes_no yes
  6          name   b
  6      number     3
  6          yes_no yes
  7          name   b
  7      number     3
  7          yes_no no
  8          name   b
  8      number     3
  8          yes_no no

</code>```

need to be like this

```<code>parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1          yes_no yes

  3          name   a
  3      number     1
  3          yes_no no

  5          name   b
  5      number     3
  5          yes_no yes

  7          name   b
  7      number     3
  7          yes_no no
</code>```

答:
I am thinking that pivoting the data is a better format and let's you do what you want easily.  First to pivot:

```<code>select parentid,
       max(case when okeyname = 'name' then okeydata end) as name,
       max(case when okeyname = 'number' then okeydata end) as number,
       max(case when okeyname = 'yes_no' then okeydata end) as name
from [elo].[dbo].[objkeys]
group by parentid ;
</code>```

Then to get the first parentid, use a subquery:

```<code>select min(parentid) as parentid, name, number, yes_no
from (select parentid,
             max(case when okeyname = 'name' then okeydata end) as name,
             max(case when okeyname = 'number' then okeydata end) as number,
             max(case when okeyname = 'yes_no' then okeydata end) as yes_no
      from [elo].[dbo].[objkeys]
      group by parentid
     ) p
group by name, number, yes_no;
</code>```

And if you want the original format, then unpivot:

```<code>select nny.parentid, v.*
from (select min(parentid) as parentid, name, number, yes_no
      from (select parentid,
                   max(case when okeyname = 'name' then okeydata end) as name,
                   max(case when okeyname = 'number' then okeydata end) as number,
                   max(case when okeyname = 'yes_no' then okeydata end) as yes_no
            from [elo].[dbo].[objkeys]
            group by parentid
           ) p
      group by name, number, yes_no
     ) nny cross apply
     (values ('name', name),
             ('number', number),
             ('yes_no', yes_no)
     ) v(okeyname, okeydata)
</code>```

Body:
How to delete duplicate from this result

select *,
       row_number() over (order by (select null)) as seqnum
from [elo].[dbo].[objkeys]
where parentid in (select parentid
                   from [elo].[dbo].[objekte]
                   inner join [elo].[dbo].[objkeys] on objid = parentid
                   where objmask like 26 and okeydata like 'yes'
                   )

output is

parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1        yes_no   yes
  2          name   a
  2      number     1
  2        yes_no   yes
  3          name   a
  3      number     1
  3        yes_no   no
  4          name   a
  4      number     2
  4          yes_no no
  5          name   b
  5      number     3
  5          yes_no yes
  6          name   b
  6      number     3
  6          yes_no yes
  7          name   b
  7      number     3
  7          yes_no no
  8          name   b
  8      number     3
  8          yes_no no

need to be like this

parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1          yes_no yes

  3          name   a
  3      number     1
  3          yes_no no

  5          name   b
  5      number     3
  5          yes_no yes

  7          name   b
  7      number     3
  7          yes_no no

Body:
I am thinking that pivoting the data is a better format and let's you do what you want easily.  First to pivot:

select parentid,
       max(case when okeyname = 'name' then okeydata end) as name,
       max(case when okeyname = 'number' then okeydata end) as number,
       max(case when okeyname = 'yes_no' then okeydata end) as name
from [elo].[dbo].[objkeys]
group by parentid ;

Then to get the first parentid, use a subquery:

select min(parentid) as parentid, name, number, yes_no
from (select parentid,
             max(case when okeyname = 'name' then okeydata end) as name,
             max(case when okeyname = 'number' then okeydata end) as number,
             max(case when okeyname = 'yes_no' then okeydata end) as yes_no
      from [elo].[dbo].[objkeys]
      group by parentid
     ) p
group by name, number, yes_no;

And if you want the original format, then unpivot:

select nny.parentid, v.*
from (select min(parentid) as parentid, name, number, yes_no
      from (select parentid,
                   max(case when okeyname = 'name' then okeydata end) as name,
                   max(case when okeyname = 'number' then okeydata end) as number,
                   max(case when okeyname = 'yes_no' then okeydata end) as yes_no
            from [elo].[dbo].[objkeys]
            group by parentid
           ) p
      group by name, number, yes_no
     ) nny cross apply
     (values ('name', name),
             ('number', number),
             ('yes_no', yes_no)
     ) v(okeyname, okeydata)


问:
C# database update
I'm stuck on a little problem concerning database.

Once a month I get a XML file with customer information (Name, address, city,etc.). My primary key is a customer number which is provided in the XML file.

I have no trouble inserting the information in the database;

```<code>var cmd = new SqlCommand("insert into [customer_info]
   (customer_nr, firstname, lastname, address_1, address_2, address_3.......)");
//some code
cmd.ExecuteNonQuery();
</code>```

Now, I would like to update my table or just fill it with new information. How can I achieve this?

I've tried using TableAdapter but it does not work.

And I'm only permitted to add one XML because I can only have one customer_nr as primary key.

So basically how do I update or fill my table with new information?

Thanks.

答:
AdaTheDev has indeed given the good suggestion.

But in case, you must insert/update from .NET code then you can

Create a stored procedure that will handle insert/update i.e. instead of using a direct insert query as command text, you make a call to stored proc. The SP will check if row exists or not and then update (or insert).

User TableAdapter - but this would be tedious. First you have to setup both insert & update commands. Then you have to query the database to get the existing customer numbers and then update the corresponding rows in the datatable making the Rowstate as Updated. I would rather not go this way.

ContentLicense: CC BY-SA 3.0

Title: C# database update

Body:
I'm stuck on a little problem concerning database.

Once a month I get a XML file with customer information (Name, address, city,etc.). My primary key is a customer number which is provided in the XML file.

I have no trouble inserting the information in the database;

var cmd = new SqlCommand("insert into [customer_info]
   (customer_nr, firstname, lastname, address_1, address_2, address_3.......)");
//some code
cmd.ExecuteNonQuery();

Now, I would like to update my table or just fill it with new information. How can I achieve this?

I've tried using TableAdapter but it does not work.

And I'm only permitted to add one XML because I can only have one customer_nr as primary key.

So basically how do I update or fill my table with new information?

Thanks.


问:
Write a function ASTERISK in C++ Programming
I did a coding that accepts an integer from the user, and output the corresponding number of asterisks. For example:

```<code>Please enter a number: 10
* * * * * * * * * *
</code>```

I must use function concept to complete the coding only. I managed to get the correct number of asterisks but the '0' at the back just won't disappear.

```<code>#include<iostream>
using namespace std;

int NUMBER, i;
int ASTERISK (int NUMBER);
int main ()

{
    cout << "Enter a number: " ;
    cin >> i ;
    cout << ASTERISK (i);
    return 0;
}

int ASTERISK (int NUMBER){
    int ANSWER;
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        cout << "* " ;
    }
    return ANSWER;
}
</code>```

答:
That zero is coming from cout << ASTERISK (i);

Replace that with ASTERISK (i);

Body:
I did a coding that accepts an integer from the user, and output the corresponding number of asterisks. For example:

Please enter a number: 10
* * * * * * * * * *

I must use function concept to complete the coding only. I managed to get the correct number of asterisks but the '0' at the back just won't disappear.

#include<iostream>
using namespace std;

int NUMBER, i;
int ASTERISK (int NUMBER);
int main ()

{
    cout << "Enter a number: " ;
    cin >> i ;
    cout << ASTERISK (i);
    return 0;
}

int ASTERISK (int NUMBER){
    int ANSWER;
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        cout << "* " ;
    }
    return ANSWER;
}


问:
Setting up a Flask app that uses headed Selenium on a Ubuntu 18.04 LTS Server
I have a flask app that uses selenium under the hood to do certain things. I intend to deploy the Flask application to an Ubuntu server. However, I was wondering if a selenium web browser was run, would it be headed or headless?

I SSH into the Ubuntu server and then install python pip. Once I install python pip, I install virtualenv and git clone my code into the sourve venv/bin/activate. I install all my requirements (including selenium)

I then install chrome like this:

sudo curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add
sudo echo "deb [arch=amd64]  http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
sudo apt-get -y update
sudo apt-get -y install google-chrome-stable

and then I install chromedriver like this:

wget https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
sudo mv chromedriver /usr/bin/chromedriver
sudo chown root:root /usr/bin/chromedriver
sudo chmod +x /usr/bin/chromedriver

My Flask application looks like this:

```<code>from flask_socketio import SocketIO
from flask_cors import CORS
import logging, time, sys
from flask import Flask, request, jsonify, render_template, redirect
messages = {}
lo = {}
task_log = {}
app = Flask(__name__,template_folder='template')
socketio = SocketIO(app)
@app.route('/activity',methods=["GET"])
def run():
    browser.get("https://store.nike.com/us/en_us/pw/just-in")
    for x in range (0,1):
        try:
            link = browser.find_element_by_xpath('''//*[@id="NavigationMenu-0"]/div/div[''' + str(random.randint(1,3)) + ''']/a[''' + str(random.randint(1,3)) + ''']''')
            href = link.get_attribute("href")
            browser.get(href)
            print(f'{Fore.GREEN}{str(datetime.datetime.now())}  - [INFO] Went to a random section')
        except:
            print(f'{Fore.RED}{str(datetime.datetime.now())}  - [ERROR] Failed to navigate to a random section')
            return "Pre Activity Error Code 0"
        try:
            if activity == "basic":
                for x in range (0,random.randint(1,10)):
                    browser.execute_script(f"window.scrollTo(0, {random.randint(1,1900)})")
                    try:
                        browser.find_element_by_class_name("bx-button").click()
                        print(f'{Fore.GREEN}{str(datetime.datetime.now())}  - [INFO] Clicked close button')
                    except:
                        print(f'{Fore.RED}{str(datetime.datetime.now())}  - [ERROR] Failed to click close button or button was not present')

                    time.sleep(random.randint(1,10))
        except:
            return "Pre Activity Error Code 1"

</code>```

So after I installed selenium + chromedriver and the rest of the things, will selenium be run as headed or headless? Is there any way to force it to be headed?

Thanks

P.S (Is my installation process of selenium + chromedriver correct? I used a tutorial for it, so just want to make sure)

答:
You did not post the part of code that defines the actual browser instance.

In order to run Selenium on a server you will need to create a virtual display.
You can do that using PyVirtualDisplay, with either Xvfb, Xephyr or Xvnc.

After setting up your virtual display you can run Selenium with Chromedriver in headless mode like this:

```<code>from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('headless')
browser = webdriver.Chrome(chrome_options=options)
browser.get('http://www.google.com')
</code>```

or if you want to run it without headless:

```<code>from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://www.google.com')
</code>```

You can read more about Chromedriver capabilities here.

Body:
I have a flask app that uses selenium under the hood to do certain things. I intend to deploy the Flask application to an Ubuntu server. However, I was wondering if a selenium web browser was run, would it be headed or headless?

I SSH into the Ubuntu server and then install python pip. Once I install python pip, I install virtualenv and git clone my code into the sourve venv/bin/activate. I install all my requirements (including selenium)

I then install chrome like this:

sudo curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add
sudo echo "deb [arch=amd64]  http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
sudo apt-get -y update
sudo apt-get -y install google-chrome-stable

and then I install chromedriver like this:

wget https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
sudo mv chromedriver /usr/bin/chromedriver
sudo chown root:root /usr/bin/chromedriver
sudo chmod +x /usr/bin/chromedriver

My Flask application looks like this:

from flask_socketio import SocketIO
from flask_cors import CORS
import logging, time, sys
from flask import Flask, request, jsonify, render_template, redirect
messages = {}
lo = {}
task_log = {}
app = Flask(__name__,template_folder='template')
socketio = SocketIO(app)
@app.route('/activity',methods=["GET"])
def run():
    browser.get("https://store.nike.com/us/en_us/pw/just-in")
    for x in range (0,1):
        try:
            link = browser.find_element_by_xpath('''//*[@id="NavigationMenu-0"]/div/div[''' + str(random.randint(1,3)) + ''']/a[''' + str(random.randint(1,3)) + ''']''')
            href = link.get_attribute("href")
            browser.get(href)
            print(f'{Fore.GREEN}{str(datetime.datetime.now())}  - [INFO] Went to a random section')
        except:
            print(f'{Fore.RED}{str(datetime.datetime.now())}  - [ERROR] Failed to navigate to a random section')
            return "Pre Activity Error Code 0"
        try:
            if activity == "basic":
                for x in range (0,random.randint(1,10)):
                    browser.execute_script(f"window.scrollTo(0, {random.randint(1,1900)})")
                    try:
                        browser.find_element_by_class_name("bx-button").click()
                        print(f'{Fore.GREEN}{str(datetime.datetime.now())}  - [INFO] Clicked close button')
                    except:
                        print(f'{Fore.RED}{str(datetime.datetime.now())}  - [ERROR] Failed to click close button or button was not present')

                    time.sleep(random.randint(1,10))
        except:
            return "Pre Activity Error Code 1"

So after I installed selenium + chromedriver and the rest of the things, will selenium be run as headed or headless? Is there any way to force it to be headed?

Thanks

P.S (Is my installation process of selenium + chromedriver correct? I used a tutorial for it, so just want to make sure)

Body:
You did not post the part of code that defines the actual browser instance.

In order to run Selenium on a server you will need to create a virtual display.
You can do that using PyVirtualDisplay, with either Xvfb, Xephyr or Xvnc.

After setting up your virtual display you can run Selenium with Chromedriver in headless mode like this:

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('headless')
browser = webdriver.Chrome(chrome_options=options)
browser.get('http://www.google.com')

or if you want to run it without headless:

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://www.google.com')

You can read more about Chromedriver capabilities here.


问:
(1 2) reported an error of invalid function
Upon reading Cons-Cell-types

```<code>ELISP> '(1 2)
(1 2)

ELISP> (1 2)
*** Eval error ***  Invalid function: 1
</code>```

The reported error confused me,

How could an integer of 1 be interred as  a function which is invalid.

答:
Note that the paragraph is about reading and printing lisp forms:

The read syntax and printed representation for lists are identical, and consist of a left parenthesis, an arbitrary number of elements, and a right parenthesis.

When encoutering (1 2), the interpreter builds a list of two elements, which, when printed, is also printed as (1 2). In a Read-Eval-Print-Loop, however, the form being read is immediately evaluated, and the evaluation rules says that:

If the first element of a list being evaluated is a Lisp function object, byte-code object or primitive function object, then that list is a function call.

The result is different when you write the list quoted:

```<code>'(1 2)
</code>```

Here above, the quote syntax translates the form into the following one (at read-time):

```<code>(quote (1 2))
</code>```

And the quote operator is special in that when evaluated, it does not evaluate its subexpression, but returns it as-is. That's why '(1 2) in the REPL evaluates as the literal list enclosed under the quote, namely (1 2).

Body:
Upon reading Cons-Cell-types

ELISP> '(1 2)
(1 2)

ELISP> (1 2)
*** Eval error ***  Invalid function: 1

The reported error confused me,

How could an integer of 1 be interred as  a function which is invalid.

Body:
Note that the paragraph is about reading and printing lisp forms:

The read syntax and printed representation for lists are identical, and consist of a left parenthesis, an arbitrary number of elements, and a right parenthesis.

When encoutering (1 2), the interpreter builds a list of two elements, which, when printed, is also printed as (1 2). In a Read-Eval-Print-Loop, however, the form being read is immediately evaluated, and the evaluation rules says that:

If the first element of a list being evaluated is a Lisp function object, byte-code object or primitive function object, then that list is a function call.

The result is different when you write the list quoted:

'(1 2)

Here above, the quote syntax translates the form into the following one (at read-time):

(quote (1 2))

And the quote operator is special in that when evaluated, it does not evaluate its subexpression, but returns it as-is. That's why '(1 2) in the REPL evaluates as the literal list enclosed under the quote, namely (1 2).


问:
How to merge two rectangles given arrays of their coordinates?
Say I have two arrays of coordinates (x,y) of two rectangles, for example [(0, 0), (0, 1), (2, 1), (2, 0)] and [(1, 0), (1, 2), (3, 2), (3, 0)], how would I merge these two coordinate arrays into one array that represents the resulting polygon?

It might look like this, graphically:

```<code>   _ _
 _|_  |
|_|_|_|
</code>```

to

```<code>   _ _
 _|   |
|_ _ _|
</code>```

with resulting array [(0, 0), (0, 1), (1, 1), (1, 2), (3, 2), (3, 0)].

I'm trying to design some sort of merge algorithm but I'm not sure where to get started.

For input, there will be two arrays, and this method will return one merged array.

I'm just totally lost on where to start.

答:
As a pointer maybe consider the following:

I am assuming that each array (r1 and r2) is constructed the same way as in:
[(bottom left) (top left) (top right) (top left)]

If there is any overlap of the rectangles (bodies and not just corners) then the result could be between four to twelve different coordinates inside your new array.

We first check which pair is the furthest left, if there is one we add it to the new array. Comparing r1's bottom left's X coordinate to r2's bottom left's X coordinate should be enough. If NOT and both rectangle's left side is on the same X coordinate we add the bottom left one with the lower Y value and the top left one with the bigger Y value. This logic can be applied to all four sides.

In the case we have e.g. a furthest left side we still need to check whether the lesser left side overlaps to the top or bottom. We do this by by simply subtracting top left r1's Y from top left r2's Y value. If there is a difference (aka the lesser left side is higher, we add the R2 top left coordinates to the array together with (r2 X's, r1 Y's). A similar logic needs to be applied for all sides in case there is a more extreme side.

So a general flow for this would be to

Check for the most outer edges. These can be added without any changes. A simple one-coordinate comparison should be enough for that. If there is an outer edge follow see (2) else see (3)

Check whether the NOT most outer edge is longer into the other direction. So for example in case for the left check, assume r1 is further left. Check whether the r2's top left is higher than r1's top left. If this is the case add r2's top left together with a new coordinate that is (r2 top left x | r1 top left Y). Keep in mind that for example in this situation r2's leftist edge could be both: overarching to the top and overarching to the bottom!

Since both edges are on the same level (e.g. same X value) we need to see which is e.g. bottom left is further down, take it and add it together with the top left that is further up.

Body:
Say I have two arrays of coordinates (x,y) of two rectangles, for example [(0, 0), (0, 1), (2, 1), (2, 0)] and [(1, 0), (1, 2), (3, 2), (3, 0)], how would I merge these two coordinate arrays into one array that represents the resulting polygon?

It might look like this, graphically:

   _ _
 _|_  |
|_|_|_|

to

   _ _
 _|   |
|_ _ _|

with resulting array [(0, 0), (0, 1), (1, 1), (1, 2), (3, 2), (3, 0)].

I'm trying to design some sort of merge algorithm but I'm not sure where to get started.

For input, there will be two arrays, and this method will return one merged array.

I'm just totally lost on where to start.


问:
how to get only the second index of a data frame with a certain condition
first of all, I am pretty new to python so please go easy on me.

I need to get a certain value from a data frame.

I got this code:

data frame for the first input:

```
symbol   date          bmo amc             company name<br>
AAP    2019-05-22  Before The Open         Advance Auto
ADI    2019-05-22  Before The Open       Analog Devices
CM     2019-05-22  Before The Open                 CIBC
CSWI   2019-05-22  Before The Open      CSW Industrials
KLXE   2019-05-22  Before The Open  KLX Energy Services
```

```<code>for stock_symbol in mystocks:
    print(stock_symbol)
</code>```

input:

```<code>#get the date from the date column
ddate = df_earning_calander.loc[
    df_earning_calander.index == stock_symbol, 'date'][stock_symbol]
print(ddate)
</code>```

output:

```<code>AAP
2019-05-22 00:00:00
</code>```

data frame for the second input:

```
symbol         Stock name         date               ...
AAP     Advance Auto Parts Inc 2018-11-13            ...
AAP     Advance Auto Parts Inc 2019-02-15            ...
AAP     Advance Auto Parts Inc 2019-02-19            ...
AAP     Advance Auto Parts Inc 2019-05-21            ...
AAP     Advance Auto Parts Inc 2019-05-22            ...
```
input:

```<code>#get all the dates from the date column
ddate_12 = df_earnings_12.loc[
    df_earnings_12.index == stock_symbol, 'date'][stock_symbol]
print(ddate_12)
</code>```

output:

```<code>AAP   2018-11-13
AAP   2019-02-15
AAP   2019-02-19
AAP   2019-05-21
AAP   2019-05-22
Name: date, dtype: datetime64[ns]
if ddate in ddate_12:
    continue
</code>```

well, I am trying to check if the date from the first data frame is in the second data frame and (while the stock name is the same).

this code does not go to the next iterable. I think it is because the second output gives me the stock name and date and not only the date.

答:
You can select only date column, create 2 columns DataFrame by Series.reset_index and if possible duplicated pairs add DataFrame.drop_duplicates:

```<code>df1 = df_earning_calander['date'].reset_index().drop_duplicates()
print (df1)
  symbol        date
0    AAP  2019-05-22
1    ADI  2019-05-22
2     CM  2019-05-22
3   CSWI  2019-05-22
4   KLXE  2019-05-22

df2 = df_earnings_12['date'].reset_index().drop_duplicates()
print (df2)
  symbol        date
0    AAP  2018-11-13
1    AAP  2019-02-15
2    AAP  2019-02-19
3    AAP  2019-05-21
4    AAP  2019-05-22
</code>```

Then for intersection between both DatFrames with same columns names use DataFrame.merge with default inner join - get all symbols matching with all datetimes between both:

```<code>df = df1.merge(df2)
print (df)
  symbol        date
0    AAP  2019-05-22
</code>```

Last if need test list of symbols compare column df['symbol'] for boolean mask and test if at least one True by Series.any:

```<code>mystocks = ['ADI','AAP']
for stock_symbol in mystocks:
    if ((df['symbol'] == stock_symbol).any()):
        print (f'Matched {stock_symbol}')
        #Matched AAP
</code>```

Body:
first of all, I am pretty new to python so please go easy on me.

I need to get a certain value from a data frame.

I got this code:

data frame for the first input:

symbol   date          bmo amc             company name

AAP    2019-05-22  Before The Open         Advance Auto
ADI    2019-05-22  Before The Open       Analog Devices
CM     2019-05-22  Before The Open                 CIBC
CSWI   2019-05-22  Before The Open      CSW Industrials
KLXE   2019-05-22  Before The Open  KLX Energy Services

for stock_symbol in mystocks:
    print(stock_symbol)

input:

#get the date from the date column
ddate = df_earning_calander.loc[
    df_earning_calander.index == stock_symbol, 'date'][stock_symbol]
print(ddate)

output:

AAP
2019-05-22 00:00:00

data frame for the second input:

symbol         Stock name         date               ...
AAP     Advance Auto Parts Inc 2018-11-13            ...
AAP     Advance Auto Parts Inc 2019-02-15            ...
AAP     Advance Auto Parts Inc 2019-02-19            ...
AAP     Advance Auto Parts Inc 2019-05-21            ...
AAP     Advance Auto Parts Inc 2019-05-22            ...

input:

#get all the dates from the date column
ddate_12 = df_earnings_12.loc[
    df_earnings_12.index == stock_symbol, 'date'][stock_symbol]
print(ddate_12)

output:

AAP   2018-11-13
AAP   2019-02-15
AAP   2019-02-19
AAP   2019-05-21
AAP   2019-05-22
Name: date, dtype: datetime64[ns]
if ddate in ddate_12:
    continue

well, I am trying to check if the date from the first data frame is in the second data frame and (while the stock name is the same).

this code does not go to the next iterable. I think it is because the second output gives me the stock name and date and not only the date.

Body:
You can select only date column, create 2 columns DataFrame by Series.reset_index and if possible duplicated pairs add DataFrame.drop_duplicates:

df1 = df_earning_calander['date'].reset_index().drop_duplicates()
print (df1)
  symbol        date
0    AAP  2019-05-22
1    ADI  2019-05-22
2     CM  2019-05-22
3   CSWI  2019-05-22
4   KLXE  2019-05-22

df2 = df_earnings_12['date'].reset_index().drop_duplicates()
print (df2)
  symbol        date
0    AAP  2018-11-13
1    AAP  2019-02-15
2    AAP  2019-02-19
3    AAP  2019-05-21
4    AAP  2019-05-22

Then for intersection between both DatFrames with same columns names use DataFrame.merge with default inner join - get all symbols matching with all datetimes between both:

df = df1.merge(df2)
print (df)
  symbol        date
0    AAP  2019-05-22

Last if need test list of symbols compare column df['symbol'] for boolean mask and test if at least one True by Series.any:

mystocks = ['ADI','AAP']
for stock_symbol in mystocks:
    if ((df['symbol'] == stock_symbol).any()):
        print (f'Matched {stock_symbol}')
        #Matched AAP


问:
Selection animation doesn't work for Angular (7) Material Tabs
I tried to implement Angular Material Tabs with routing, everything works fine just that the underline animation doesn't work. It just remains stuck on first tab and disappears after.
I have the animations and default theme installed as suggested here:

Angular material tab animation doesn't work

and used the code as in the Documentation:

```<code><nav mat-tab-nav-bar>
  <a mat-tab-link
      routerLink="home"
      routerLinkActive #rla="routerLinkActive"
      [active]="rla.isActive">
      home
  </a>
  <a mat-tab-link
      routerLink="about"
      routerLinkActive #rla="routerLinkActive"
      [active]="rla.isActive">
      about
  </a>
</nav>

<router-outlet></router-outlet>
</code>```

答:
Try this:

```<code><a mat-tab-link
      routerLink="about"
      routerLinkActive #rla="routerLinkActive"
      routerLinkActive="active"
      [active]="rla.isActive">
      about
</a>
</code>```

CSS:

```<code>.active{
}
</code>```

Body:
I tried to implement Angular Material Tabs with routing, everything works fine just that the underline animation doesn't work. It just remains stuck on first tab and disappears after.
I have the animations and default theme installed as suggested here:

Angular material tab animation doesn't work

and used the code as in the Documentation:

      home

      about

<router-outlet></router-outlet>

Body:
Try this:

<a mat-tab-link
      routerLink="about"
      routerLinkActive #rla="routerLinkActive"
      routerLinkActive="active"
      [active]="rla.isActive">
      about
</a>

CSS:

.active{
}


问:
Is it possible to select only columns where at least one value is present?
I need to select all coulmns where at least one value is present. For example if this is my table:

```<code>----------------------------
name   |  keyword  |  zip
----------------------------
User1  |  test     |  ""
User2  |  test     |  ""
User3  |  ""       |  ""
</code>```

Should output something like this:

```<code>-----------------
name   |  keyword
-----------------
User1  |  test
User2  |  test
User3  |  ""
</code>```

The thing is that zip might not be empty and in this case the output should also include the zip column. The actual table I need this functionality for has many more columns that can potentially be empty.

I tried using SELECT * FROM myTable HAVING COUNT(*) > 0 but that did not work (empty columns were still showing).

Also tried solving it with php using loops but didn't get far that way either.

Is something like this even possible using SQL or should it be done using php for example?

SOLUTION

Here's the solution I came up with in PHP using the suggestions I got for this question.

```<code>$stack = array("keyword", "zip");
$id = $_POST["id"];
$sql = "SELECT name";
foreach($stack as $i){
    $q = "SELECT ".$i." FROM myTable WHERE ".$i." != '' AND id = '".$id."'";
    $result = mysqli_query($link, $q);
    if(mysqli_num_rows($result) > 0){
        $sql = $sql.", ".$i;
    }
}
$sql = $sql." FROM myTable WHERE id = '".$id."'";
</code>```

This will output the following sql query:
SELECT name, keyword FROM myTable WHERE id = 'postedId'

Notice the zip is missing from select, this is because for that particular query there were no values in zip. In the $stack array you can put whatever columns you want to check.

Also make note of how I used != '' to check for empty values but if your table has empty values as NULL make sure to use IS NOT NULL instead.

答:
This is not a the real answer.

Just an example of how it could be done in Oracle (I got very little experience with MySQL):

```<code>DECLARE
  has_keyword INTEGER;
  has_zip     INTEGER;
  sql         VARCHAR2(1024);
BEGIN

  -- Determine the columns having at least 1 row with a not null value
  SELECT CASE WHEN MAX(keyword) IS NULL THEN 0 ELSE 1 END,
         CASE WHEN MAX(zip)     IS NULL THEN 0 ELSE 1 END
    INTO has_keyword,
         has_zip
    FROM my_table;

  -- Compose query
  sql := 'SELECT name';
  IF (has_keyword > 0) THEN
    sql := sql || ', keyword';
  END IF;
  IF (zip > 0) THEN
    sql := sql || ', zip';
  END IF;
  sql := sql || ' FROM my_table';

  -- Execute query
  EXECUTE IMMEDIATE sql;

END;
</code>```

Body:
I need to select all coulmns where at least one value is present. For example if this is my table:

----------------------------
name   |  keyword  |  zip
----------------------------
User1  |  test     |  ""
User2  |  test     |  ""
User3  |  ""       |  ""

Should output something like this:

-----------------
name   |  keyword
-----------------
User1  |  test
User2  |  test
User3  |  ""

The thing is that zip might not be empty and in this case the output should also include the zip column. The actual table I need this functionality for has many more columns that can potentially be empty.

I tried using SELECT * FROM myTable HAVING COUNT(*) > 0 but that did not work (empty columns were still showing).

Also tried solving it with php using loops but didn't get far that way either.

Is something like this even possible using SQL or should it be done using php for example?

SOLUTION

Here's the solution I came up with in PHP using the suggestions I got for this question.

$stack = array("keyword", "zip");
$id = $_POST["id"];
$sql = "SELECT name";
foreach($stack as $i){
    $q = "SELECT ".$i." FROM myTable WHERE ".$i." != '' AND id = '".$id."'";
    $result = mysqli_query($link, $q);
    if(mysqli_num_rows($result) > 0){
        $sql = $sql.", ".$i;
    }
}
$sql = $sql." FROM myTable WHERE id = '".$id."'";

This will output the following sql query:
SELECT name, keyword FROM myTable WHERE id = 'postedId'

Notice the zip is missing from select, this is because for that particular query there were no values in zip. In the $stack array you can put whatever columns you want to check.

Also make note of how I used != '' to check for empty values but if your table has empty values as NULL make sure to use IS NOT NULL instead.

Body:
This is not a the real answer.

Just an example of how it could be done in Oracle (I got very little experience with MySQL):

DECLARE
  has_keyword INTEGER;
  has_zip     INTEGER;
  sql         VARCHAR2(1024);
BEGIN

  -- Determine the columns having at least 1 row with a not null value
  SELECT CASE WHEN MAX(keyword) IS NULL THEN 0 ELSE 1 END,
         CASE WHEN MAX(zip)     IS NULL THEN 0 ELSE 1 END
    INTO has_keyword,
         has_zip
    FROM my_table;

  -- Compose query
  sql := 'SELECT name';
  IF (has_keyword > 0) THEN
    sql := sql || ', keyword';
  END IF;
  IF (zip > 0) THEN
    sql := sql || ', zip';
  END IF;
  sql := sql || ' FROM my_table';

  -- Execute query
  EXECUTE IMMEDIATE sql;

END;


问:
in ASP.NET MVC3 how can I see the request?
I'm using a simple route as

```<code>routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);
</code>```

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

```<code>//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}
</code>```

The thing is that, when I insert this in the browser:

```<code>http://localhost:14951/client_name/hashed_id
</code>```

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.

答:
I know others have sort-of made a stab at this... they are correct:

Use the Request object to find out what is being requested. It's probably something incorrectly being handled by your controller. Shovel some output while debugging from Request in that method, such as the raw url. That will likely answer the question.

Body:
I'm using a simple route as

routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}

The thing is that, when I insert this in the browser:

http://localhost:14951/client_name/hashed_id

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.


问:
Android Studio Emulator Not Running. Codes are OK
I am writing an app for my company but I cannot see my work since my emulator is not running.

Here is my code below. There are no errors. I am running this in android studio.

It runs on some apps but I tried inputting my code then it does not work.

Please Help

```<code> package com.example.tankoverfill;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

Button calc;

TextView tv_heightfills = findViewById(R.id.tv_heightfills);
TextView tv_timefills = findViewById(R.id.tv_timefills);

EditText flow, areas, heights, densities, heightones, cvs;
int x1,y1,w1,a1, x2,y2,w2,a2,g;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    flow = findViewById(R.id.flow);
    areas = findViewById(R.id.areas);
    heights =  findViewById(R.id.heights);
    densities =  findViewById(R.id.densities);
    heightones  =  findViewById(R.id.heightones);
    cvs  =  findViewById(R.id.cvs);
    calc = findViewById(R.id.calc);

    calc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        x1 = Integer.parseInt(flow.getText().toString());
        y1 = Integer.parseInt(cvs.getText().toString());
        w1 = Integer.parseInt(densities.getText().toString());
         g = (int) 9.8;

        a1 = (x1 / (y1*w1*g));

        tv_heightfills.setText(a1);

        }
    });

    calc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            x2 = Integer.parseInt(areas.getText().toString());
            y2 = Integer.parseInt(cvs.getText().toString());
           w2 = Integer.parseInt(densities.getText().toString());
             g = (int) 9.8;

    a2 = (x1 / (y1*w1*g));

    tv_timefills.setText(a2);

  }
 });

 }
 }
</code>```

D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION:
  main
      Process: com.example.tankoverfill, PID: 10137
      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.tankoverfill/com.example.tankoverfill.MainActivity}:
  java.lang.NullPointerException: Attempt to invoke virtual method
  'android.view.Window$Callback android.view.Window.getCallback()' on a
  null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
          at android.os.Handler.dispatchMessage(Handler.java:106)
          at android.os.Looper.loop(Looper.java:193)
          at android.app.ActivityThread.main(ActivityThread.java:6669)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback
  android.view.Window.getCallback()' on a null object reference
          at android.support.v7.app.AppCompatDelegateImpl.(AppCompatDelegateImpl.java:249)
          at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
          at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
          at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
          at com.example.tankoverfill.MainActivity.(MainActivity.java:15)
          at java.lang.Class.newInstance(Native Method)
          at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
          at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
          at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
          at android.os.Handler.dispatchMessage(Handler.java:106)
          at android.os.Looper.loop(Looper.java:193)
          at android.app.ActivityThread.main(ActivityThread.java:6669)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
  I/Process: Sending signal. PID: 10137 SIG: 9 Application terminated.

答:
Hello two of the errors you have in your code are:

first error that you must link the two textview to xml inside onCreate() method

error

```<code>TextView tv_heightfills = findViewById(R.id.tv_heightfills);
TextView tv_timefills = findViewById(R.id.tv_timefills);
</code>```

correct

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

    ....

}
</code>```

Second error is setting int value to the textview setText() method

so it should be:

```<code>tv_heightfills.setText(String.valueOf(a1));
</code>```

same for

```<code>tv_timefills.setText(String.valueOf(a2));
</code>```

Body:
I am writing an app for my company but I cannot see my work since my emulator is not running.

Here is my code below. There are no errors. I am running this in android studio.

It runs on some apps but I tried inputting my code then it does not work.

Please Help

 package com.example.tankoverfill;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

Button calc;

TextView tv_heightfills = findViewById(R.id.tv_heightfills);
TextView tv_timefills = findViewById(R.id.tv_timefills);

EditText flow, areas, heights, densities, heightones, cvs;
int x1,y1,w1,a1, x2,y2,w2,a2,g;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    flow = findViewById(R.id.flow);
    areas = findViewById(R.id.areas);
    heights =  findViewById(R.id.heights);
    densities =  findViewById(R.id.densities);
    heightones  =  findViewById(R.id.heightones);
    cvs  =  findViewById(R.id.cvs);
    calc = findViewById(R.id.calc);

    calc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        x1 = Integer.parseInt(flow.getText().toString());
        y1 = Integer.parseInt(cvs.getText().toString());
        w1 = Integer.parseInt(densities.getText().toString());
         g = (int) 9.8;

        a1 = (x1 / (y1*w1*g));

        tv_heightfills.setText(a1);

        }
    });

    calc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            x2 = Integer.parseInt(areas.getText().toString());
            y2 = Integer.parseInt(cvs.getText().toString());
           w2 = Integer.parseInt(densities.getText().toString());
             g = (int) 9.8;

    a2 = (x1 / (y1*w1*g));

    tv_timefills.setText(a2);

  }
 });

 }
 }

D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION:
  main
      Process: com.example.tankoverfill, PID: 10137
      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.tankoverfill/com.example.tankoverfill.MainActivity}:
  java.lang.NullPointerException: Attempt to invoke virtual method
  'android.view.Window$Callback android.view.Window.getCallback()' on a
  null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
          at android.os.Handler.dispatchMessage(Handler.java:106)
          at android.os.Looper.loop(Looper.java:193)
          at android.app.ActivityThread.main(ActivityThread.java:6669)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback
  android.view.Window.getCallback()' on a null object reference
          at android.support.v7.app.AppCompatDelegateImpl.(AppCompatDelegateImpl.java:249)
          at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
          at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
          at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
          at com.example.tankoverfill.MainActivity.(MainActivity.java:15)
          at java.lang.Class.newInstance(Native Method)
          at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
          at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
          at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
          at android.os.Handler.dispatchMessage(Handler.java:106)
          at android.os.Looper.loop(Looper.java:193)
          at android.app.ActivityThread.main(ActivityThread.java:6669)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
  I/Process: Sending signal. PID: 10137 SIG: 9 Application terminated.

Body:
Hello two of the errors you have in your code are:

first error that you must link the two textview to xml inside onCreate() method

error

TextView tv_heightfills = findViewById(R.id.tv_heightfills);
TextView tv_timefills = findViewById(R.id.tv_timefills);

correct

TextView tv_heightfills;
TextView tv_timefills;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv_heightfills = findViewById(R.id.tv_heightfills);
    tv_timefills = findViewById(R.id.tv_timefills);

    ....

}

Second error is setting int value to the textview setText() method

so it should be:

tv_heightfills.setText(String.valueOf(a1));

same for

tv_timefills.setText(String.valueOf(a2));


问:
Remove query param from url
I have the following URL:

```<code>http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860
</code>```

And I want to redirect to:

```<code>http://my.site#/homepage
</code>```

I do that with:

```<code>import { push } from 'react-router-redux'

...

dispatch(push('/homepage'))
</code>```

But react takes me to:

```<code>http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860#/homepage
</code>```

How can I tell React to drop the query param in the browser's address bar without reloading the application?

答:
Try this one (hardcode way)

```<code>import { push } from 'react-router-redux'

...
const url = `${window.location.origin}/homepage`;
dispatch(push(url));
</code>```

Or this one

```<code>history.location.pathname =`${window.location.origin}/homepage`;
</code>```

Those methods are not a good practice at all but those work (the second one for sure)

Read more

Title: Remove query param from url

Body:
I have the following URL:

http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860

And I want to redirect to:

http://my.site#/homepage

I do that with:

import { push } from 'react-router-redux'

...

dispatch(push('/homepage'))

But react takes me to:

http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860#/homepage

How can I tell React to drop the query param in the browser's address bar without reloading the application?

Body:
Try this one (hardcode way)

import { push } from 'react-router-redux'

...
const url = `${window.location.origin}/homepage`;
dispatch(push(url));

Or this one

history.location.pathname =`${window.location.origin}/homepage`;

Those methods are not a good practice at all but those work (the second one for sure)

Read more


问:
Polymorphism with cython extesion types
I have a cython extension type that I want to make more general. One of the attributes of this extension type is a double and I want it to be a memoryview (double[::1]) when needed.

Here is a simple example :

import numpy as np
cimport numpy as np
cimport cython

cdef class Test:

    cdef bint numeric
    cdef double du

    def __init__(self, bint numeric):

        self.numeric = numeric

        if self.numeric:
            self.du = 1

        else:
            self.du = np.ones(10)

    def disp(self)
        print(self.du)

Test(True).disp()   # returns 1
Test(False).disp()  # gives of course an error
```

I tried to subclass Test changing du type to double[::1] and implementing a new __init__ but it seems that we can't override class attributes of extension types. Even if it worked, it wouldn't be satisfactory because I don't really want to have one extension type for each case.

The best would be that my extension type directly handle both cases (scalar du and memoryview du).

Is there a way to do this with Cython ?

答:
Unfortunately, you cannot use fused_type as attributes type. You can have two options here:

You could try to use the memory adress of the variable you want to call, and cast it when needed (everything is explained here.) Unfortunately, I did not succeed at making it work with typed memory views.

Or you can use your defined attribute numeric to call the appropriate method:

```<code>import numpy as np
cimport numpy as np
cimport cython

cdef class Test:

    cdef bint numeric
    cdef double du_numeric
    cdef double[:] du_mem_view

    def __init__(self, bint numeric):

        self.numeric = numeric

        if self.numeric:
            self.du_numeric = 1

        else:
            self.du_mem_view = np.ones(10)

    def disp(self):
        if self.numeric:
            print(self.du_numeric)
        else:
            print(self.du_numeric_mem_view)

Test(True).disp()   # returns 1
Test(False).disp()  # Does not give an error anymore !
</code>```

Title: Polymorphism with cython extesion types

Body:
I have a cython extension type that I want to make more general. One of the attributes of this extension type is a double and I want it to be a memoryview (double[::1]) when needed.

Here is a simple example :

import numpy as np
cimport numpy as np
cimport cython

cdef class Test:

    cdef bint numeric
    cdef double du

    def __init__(self, bint numeric):

        self.numeric = numeric

        if self.numeric:
            self.du = 1

        else:
            self.du = np.ones(10)

    def disp(self)
        print(self.du)

Test(True).disp()   # returns 1
Test(False).disp()  # gives of course an error

I tried to subclass Test changing du type to double[::1] and implementing a new __init__ but it seems that we can't override class attributes of extension types. Even if it worked, it wouldn't be satisfactory because I don't really want to have one extension type for each case.

The best would be that my extension type directly handle both cases (scalar du and memoryview du).

Is there a way to do this with Cython ?

Body:
Unfortunately, you cannot use fused_type as attributes type. You can have two options here:

You could try to use the memory adress of the variable you want to call, and cast it when needed (everything is explained here.) Unfortunately, I did not succeed at making it work with typed memory views.

Or you can use your defined attribute numeric to call the appropriate method:

import numpy as np
cimport numpy as np
cimport cython

cdef class Test:

    cdef bint numeric
    cdef double du_numeric
    cdef double[:] du_mem_view

    def __init__(self, bint numeric):

        self.numeric = numeric

        if self.numeric:
            self.du_numeric = 1

        else:
            self.du_mem_view = np.ones(10)

    def disp(self):
        if self.numeric:
            print(self.du_numeric)
        else:
            print(self.du_numeric_mem_view)

Test(True).disp()   # returns 1
Test(False).disp()  # Does not give an error anymore !


问:
How can I access a local hug API using JavaScript?
I have an Apache2 web server as well as a Python hug server running. Both run on different ports. I now want to sent a request to the hug server using jQuery. As this is cross domain, I think I have to use something similar to this: How do I send an AJAX request on a different port with jQuery?
jsonp with callback parameter.

My questions is:
 - is my approach reasonable?
 - does hug support jsonp with callback?
 - could there be a better solution to communicate between javascript and the Python hug API?

答:
If you just need to send a GET request on your API you can use the jQuery method:

```<code>$.getJSON(your_url, function(json_received){
      console.log(json_received);
    });
</code>```

If you need to send data trough a POST request you need to add more parameters in ajax method :

```<code>    $.ajax({
          type: 'POST',
          contentType: 'application/json; charset=utf-8',
          url: your_url,
          dataType: 'json',
          data: JSON.stringify({'message':'your_message}),
          success: function(data_received) {
            console.log(data_received);
          },
          error: function(error) {
            console.log(error);
          }
      });
</code>```

In the API response you need to add the parameter {'Access-Control-Allow-Origin': '*'} to allow cross domain.

Body:
If you just need to send a GET request on your API you can use the jQuery method:

$.getJSON(your_url, function(json_received){
      console.log(json_received);
    });

If you need to send data trough a POST request you need to add more parameters in ajax method :

    $.ajax({
          type: 'POST',
          contentType: 'application/json; charset=utf-8',
          url: your_url,
          dataType: 'json',
          data: JSON.stringify({'message':'your_message}),
          success: function(data_received) {
            console.log(data_received);
          },
          error: function(error) {
            console.log(error);
          }
      });

In the API response you need to add the parameter {'Access-Control-Allow-Origin': '*'} to allow cross domain.


问:
How to build every project in a solution by using msbuild.exe
Is there a possibility to build every project within a solution by using msbuild in the command line? I'm using Visual Studio 2008</p>

答:
This will not answer your exact question, but may be the solution that works for you:

You can use the CLI of Visual Studio itself to have a very comfortable interface to build your solutions and projects. For example

```<code>C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe \
[path to sln-file] /rebuild release
</code>```

or to build just one project:

```<code>C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe \
[path to sln-file] /rebuild release /project [project name]
</code>```

Body:
This will not answer your exact question, but may be the solution that works for you:

You can use the CLI of Visual Studio itself to have a very comfortable interface to build your solutions and projects. For example

C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe \
[path to sln-file] /rebuild release

or to build just one project:

C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe \
[path to sln-file] /rebuild release /project [project name]


问:
parse int to date (tmap ) Talend PostgreSQL
My job Talend is about mapping between a csv file and a postregresql table.
I need to insert a column date which can be with normal format yyyyMMdd or(0/99999999) in the csv file. So if the date is equal to 0 or 99999999 it's will be mapping as a null variable in the database, else the  data must be loaded as a date type timestamp yyyy-mm-dd HH:mm:ss.

In the csv file I declared the date as an int, so I must parse int to a datetime in the tmap and loaded the 0/99999999 as a null variable.
Any help please.

答:
if I understand the problem correctly, its solution is as follows:

// correspondent expression to convert string with special "0/99999999" values is:
(row1.dateAsString.equals("0")||row1.dateAsString.equals("99999999"))?null:routines.TalendDate.parseDate("yyyyMMdd", row1.dateAsString)


问:
After installing Tensorflow-gpu i got error Failed to load the native TensorFlow runtime
I have installed redhat 6.6, cuda 9.0, cudnn 7.3.1 and tesnorflow-gpu. but after installation getting following error. My graphics card is nvidia titan v
Traceback (most recent call last):</p>

```<code>  File "<ipython-input-1-88d96843a926>", line 1, in <module>
    import keras

  File "/root/anaconda3/lib/python3.7/site-packages/keras/__init__.py", line 3, in <module>
    from . import utils

  File "/root/anaconda3/lib/python3.7/site-packages/keras/utils/__init__.py", line 6, in <module>
    from . import conv_utils

  File "/root/anaconda3/lib/python3.7/site-packages/keras/utils/conv_utils.py", line 9, in <module>
    from .. import backend as K

  File "/root/anaconda3/lib/python3.7/site-packages/keras/backend/__init__.py", line 89, in <module>
    from .tensorflow_backend import *

  File "/root/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py", line 5, in <module>
    import tensorflow as tf

  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import

  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow

  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)

ImportError: Traceback (most recent call last):
  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/root/anaconda3/lib/python3.7/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/root/anaconda3/lib/python3.7/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: libcuda.so.1: cannot open shared object file: No such file or directory
</code>```

答:
Did you tested your installations of cuda and cudnn:

Nvidia drivers:

```<code>$ nvidia-smi
</code>```

This should display you an overview of the metrics of your GPU

Test cuda:

Check first if:

```<code>$ nvcc -V
</code>```

display the right version of your cuda toolkit

Then you can test it with the following process:
First:

```<code> $ cd ~/NVIDIA_CUDA-9.0_Samples
 $ make
</code>```

And then:

```<code>$ cd ~/NVIDIA_CUDA-10.0_Samples/bin/x86_64/linux/release
$./deviceQuery
</code>```

if you have a 'Result: pass' at the end, you're all good!

To test cudnn:

```<code>$ cp -r /usr/src/cudnn_samples_v7/ $HOME
$ cd $HOME/cudnn_samples_v7/mnistCUDNN
$ make clean && make
$ ./mnistCUDNN
</code>```

You should have as result: 'Test passed!'

Tensorflow:

If cuda and cudnn are working, i advice you to install tensorflow in a conda environment using:

```<code>conda create --name tf_gpu tensorflow-gpu
</code>```

For me (and after a lot of problems) it was working very well.

To test it:

```<code>from tensorflow.python.client import device_lib
device_lib.list_local_devices()
</code>```

main sources:
install tensorflow GPU
tensorflow for GPU made easy

Body:
I have installed redhat 6.6, cuda 9.0, cudnn 7.3.1 and tesnorflow-gpu. but after installation getting following error. My graphics card is nvidia titan v
Traceback (most recent call last):

  File "<ipython-input-1-88d96843a926>", line 1, in <module>
    import keras

  File "/root/anaconda3/lib/python3.7/site-packages/keras/__init__.py", line 3, in <module>
    from . import utils

  File "/root/anaconda3/lib/python3.7/site-packages/keras/utils/__init__.py", line 6, in <module>
    from . import conv_utils

  File "/root/anaconda3/lib/python3.7/site-packages/keras/utils/conv_utils.py", line 9, in <module>
    from .. import backend as K

  File "/root/anaconda3/lib/python3.7/site-packages/keras/backend/__init__.py", line 89, in <module>
    from .tensorflow_backend import *

  File "/root/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py", line 5, in <module>
    import tensorflow as tf

  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import

  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow

  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)

ImportError: Traceback (most recent call last):
  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/root/anaconda3/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/root/anaconda3/lib/python3.7/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/root/anaconda3/lib/python3.7/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: libcuda.so.1: cannot open shared object file: No such file or directory

Body:
Did you tested your installations of cuda and cudnn:

Nvidia drivers:

$ nvidia-smi

This should display you an overview of the metrics of your GPU

Test cuda:

Check first if:

$ nvcc -V

display the right version of your cuda toolkit

Then you can test it with the following process:
First:

 $ cd ~/NVIDIA_CUDA-9.0_Samples
 $ make

And then:

$ cd ~/NVIDIA_CUDA-10.0_Samples/bin/x86_64/linux/release
$./deviceQuery

if you have a 'Result: pass' at the end, you're all good!

To test cudnn:

$ cp -r /usr/src/cudnn_samples_v7/ $HOME
$ cd $HOME/cudnn_samples_v7/mnistCUDNN
$ make clean && make
$ ./mnistCUDNN

You should have as result: 'Test passed!'

Tensorflow:

If cuda and cudnn are working, i advice you to install tensorflow in a conda environment using:

conda create --name tf_gpu tensorflow-gpu

For me (and after a lot of problems) it was working very well.

To test it:

from tensorflow.python.client import device_lib
device_lib.list_local_devices()

main sources:
install tensorflow GPU
tensorflow for GPU made easy


问:
Finding subdirectories of depth 1 that do _not_ include a file
I am working on an open-source project. In most, but not all, of the sub-directories of depth 1, a file called "test.c" can be found. How can I find out those directories that do not include "test.c"?  </p>

<p>For example, I have subdirectories dir1, dir2, dir3. Dir2 and dir3 have "test.c". I have to manually check them with "ls" to determine "dir1" does not have "test.c". Probably there is a simpler way (such as a bash command) to do so?  I am under Ubuntu 16. So a bash command would be preferred. </p>

答:
You may use this find command from base directory of all the sub-directories:

```<code>find . -type d -exec bash -c 'for d; do [[ -f "$d"/test.c ]] || echo "$d"; done' - {} +
</code>```

This command finds all sub directories from current directory and checks for presence of file test.c in each directory in the bash command. If file is not present then directory name is printed.

Body:
I am working on an open-source project. In most, but not all, of the sub-directories of depth 1, a file called "test.c" can be found. How can I find out those directories that do not include "test.c"?

For example, I have subdirectories dir1, dir2, dir3. Dir2 and dir3 have "test.c". I have to manually check them with "ls" to determine "dir1" does not have "test.c". Probably there is a simpler way (such as a bash command) to do so?  I am under Ubuntu 16. So a bash command would be preferred.

Body:
You may use this find command from base directory of all the sub-directories:

find . -type d -exec bash -c 'for d; do [[ -f "$d"/test.c ]] || echo "$d"; done' - {} +

This command finds all sub directories from current directory and checks for presence of file test.c in each directory in the bash command. If file is not present then directory name is printed.


问:
How to schedule node.js code to run at a specific time daily outside times given in scheduler?
So, I see that heroku provides the option to run a command at a specific time. Information on the scheduler here.

LINK: https://elements.heroku.com/addons/scheduler

However, if you go through the steps when setting it up, they do not provide a lot of flexibility on when you can run your code daily. For example, you can only run code at 4:00pm or 4:30pm, not 4:10pm.

How can I make it so that a node.js file would run on heroku at a specific time (like 4:10pm or 2:15pm, some time outside the options given on heroku) on a daily basis?

There appears to be no support for node.js explaining this either on their website.

答:
We've added a simple Heroku add-on called Cron To Go that does exactly that - you can use Cron expressions for accuracy and schedule one-off Dynos, just like with Heroku Scheduler.

There's also a simple Node example here.


问:
Order by several columns
I want to regularly update the rows in a database but also want more popular rows (rows that are requested more) to be updated more often. I thought I could base this on two parameters: popularity and time since the last update.

```<code>id | title | popularity | last_updated
---+-------+------------+-------------
1  | A     | 148        | 20190501
2  | B     | 3874       | 20190201
3  | C     | 29         | 20190104
4  | D     | 242        | 20190314
5  | E     | 398        | 20190325
6  | F     | 3          | 20190128
</code>```

The last_updated column is formated as YYYYMMDD.

I first thought I could simply use ORDER BY:

SELECT * FROM results ORDER BY last_updated, popularity;
```

However, this query will only care about the last_updated column if the value of two or more rows' popularity is the same.

Would it be possible to e.g. turn popularity and last_updated into another value that can be used for this kind of sorting?

答:
There are of course many ways to select a formula for bringing popularity and last_update together into a single value to order by. So this is more of a template than a ready answer

To just use popularity we can make use of the random() function to add a factor to the popularity

```<code>SELECT *
FROM results
ORDER BY popularity * random() DESC
</code>```

For the date it makes sense to subtract it from today and then use random() on that result so if we add that

```<code>SELECT *
FROM results
ORDER BY popularity * random() - (current_date - last_updated) * random() DESC
</code>```

As pointed out in a comment I might have misunderstood the priority of last_update so if older updates should be more likely to be updated then switch the sign

```<code>SELECT *
FROM results
ORDER BY popularity * random() + (current_date - last_updated) * random()
</code>```

so now we subtract the days from the last update so that newly updated gets a higher value but again we use random() so that the order isn't given. This could serve as a start but I am not sure if the balance between the two parts is good or if perhaps one of them needs to be multiplied by some factor depending on how popularrity vs last_updated should affect the result.

Then one could also add a LIMIT to the SELECT and perhaps even let that value to be multiplied by random()

Title: Order by several columns

Body:
I want to regularly update the rows in a database but also want more popular rows (rows that are requested more) to be updated more often. I thought I could base this on two parameters: popularity and time since the last update.

id | title | popularity | last_updated
---+-------+------------+-------------
1  | A     | 148        | 20190501
2  | B     | 3874       | 20190201
3  | C     | 29         | 20190104
4  | D     | 242        | 20190314
5  | E     | 398        | 20190325
6  | F     | 3          | 20190128

The last_updated column is formated as YYYYMMDD.

I first thought I could simply use ORDER BY:

SELECT * FROM results ORDER BY last_updated, popularity;

However, this query will only care about the last_updated column if the value of two or more rows' popularity is the same.

Would it be possible to e.g. turn popularity and last_updated into another value that can be used for this kind of sorting?

Body:
There are of course many ways to select a formula for bringing popularity and last_update together into a single value to order by. So this is more of a template than a ready answer

To just use popularity we can make use of the random() function to add a factor to the popularity

SELECT *
FROM results
ORDER BY popularity * random() DESC

For the date it makes sense to subtract it from today and then use random() on that result so if we add that

SELECT *
FROM results
ORDER BY popularity * random() - (current_date - last_updated) * random() DESC

As pointed out in a comment I might have misunderstood the priority of last_update so if older updates should be more likely to be updated then switch the sign

SELECT *
FROM results
ORDER BY popularity * random() + (current_date - last_updated) * random()

so now we subtract the days from the last update so that newly updated gets a higher value but again we use random() so that the order isn't given. This could serve as a start but I am not sure if the balance between the two parts is good or if perhaps one of them needs to be multiplied by some factor depending on how popularrity vs last_updated should affect the result.

Then one could also add a LIMIT to the SELECT and perhaps even let that value to be multiplied by random()


问:
How to fix syntax in UNPIVOT command? Parenthesis as Unexpected syntax error
I am trying to unpivot this table as I need the days in rows not in columns. I am relatively new, but I thing the Unpivot should work. However, it says Syntax Error, unexpected (, when from everywhere I have seen there is a parenthesis after the UNPIVOT command.

I have tried other clauses to encapsulate it, or not using at all, but always appears the same mistake. It should be in Standard SQL.

standardSQL

```<code>SELECT service_id, day, service
FROM calendar
UNPIVOT
(
    service
    FOR day in ( monday, tuesday, wednesday, thursday, friday, saturday, sunday )
) AS unpvt;
</code>```

Should get a list whose column titles should be: service_id, day, service

答:
There is no unpivot in standard SQL.  My preferred method is lateral joins, but that differs by database.

A generic method is to just use union all:

```<code>select service_id, 'monday' as day, monday as service
from calendar
union all
select service_id, 'tuesday' as day, tuesday as service
from calendar
union all
select service_id, 'wednesday' as day, wednesday as service
from calendar
union all
select service_id, 'thursday' as day, thursday as service
from calendar
union all
select service_id, 'friday' as day, friday as service
from calendar
union all
select service_id, 'saturday' as day, saturday as service
from calendar
union all
select service_id, 'sunday' as day, sunday as service
from calendar;
</code>```

Body:
I am trying to unpivot this table as I need the days in rows not in columns. I am relatively new, but I thing the Unpivot should work. However, it says Syntax Error, unexpected (, when from everywhere I have seen there is a parenthesis after the UNPIVOT command.

I have tried other clauses to encapsulate it, or not using at all, but always appears the same mistake. It should be in Standard SQL.

standardSQL

SELECT service_id, day, service
FROM calendar
UNPIVOT
(
    service
    FOR day in ( monday, tuesday, wednesday, thursday, friday, saturday, sunday )
) AS unpvt;

Should get a list whose column titles should be: service_id, day, service

Body:
There is no unpivot in standard SQL.  My preferred method is lateral joins, but that differs by database.

A generic method is to just use union all:

select service_id, 'monday' as day, monday as service
from calendar
union all
select service_id, 'tuesday' as day, tuesday as service
from calendar
union all
select service_id, 'wednesday' as day, wednesday as service
from calendar
union all
select service_id, 'thursday' as day, thursday as service
from calendar
union all
select service_id, 'friday' as day, friday as service
from calendar
union all
select service_id, 'saturday' as day, saturday as service
from calendar
union all
select service_id, 'sunday' as day, sunday as service
from calendar;


问:
Django i cannot add button in modal for each field with ajax
I m trying to put a button in my table but i cannot succeed

i receive an error
"Reverse for 'editare-agenda' with keyword arguments '{'pk': '+field.id+'}' not found. 1 pattern(s) tried: ['dashboard/editare\-agenda/(?P[0-9]+)$']"

if i put an number  instead +field.id+ is working . if i test alert(field.id) i receive the id. is something wrong writing {% url 'dasboard:editare-agenda' pk=field.id %} but i cannot find the solution.

this is my urls.py:

path('editare-agenda/<"int":pk>', editare_agenda, name="editare-agenda"),

** "int" = int  -> i cannot write int in url path because he disappear

```<code> $.ajax({
    data: values,
    method:"POST",
    url: destinatie,
    contenttType: 'application/json',
    success: function(data){
        var content ="";
        $.each(data.agenda, function(i, field){
            content += '<tr class="text-center">';
            content += '<td>'+field.denumire_unitate+'</td>';
            content += '<td>'+field.sectia+'</td>';
            content += '<td>'+field.telefon+'</td>';
            content += '<td>'+field.pers_contact+'</td>';
            content += '<td>'+field.adresa+'</td>';
            content += '<td><a href="{% url "dashboard:editare-agenda" pk='+field.id+'%}"><button type="button" class="btn btn-sm" style="border-radius: 5px;margin: 1px;"><i class="fas fa-edit fa-lg" style="color: blue"></i></button></a></td>';
            content += '</tr>';
    });
    $('#tabela_agenda').html(content);
}
</code>```

});

答:
```<code>content += '<td><a href="{% url "dashboard:editare-agenda" pk=field.id %}"><button type="button" tclass="btn btn-sm" style="border-radius: 5px;margin: 1px;"><i class="fas fa-edit fa-lg" style="color: blue"></i></button></a></td>';

path('editare-agenda/<int:pk>', editare_agenda, name="editare-agenda"),
</code>```

Body:
I m trying to put a button in my table but i cannot succeed

i receive an error
"Reverse for 'editare-agenda' with keyword arguments '{'pk': '+field.id+'}' not found. 1 pattern(s) tried: ['dashboard/editare\-agenda/(?P[0-9]+)$']"

if i put an number  instead +field.id+ is working . if i test alert(field.id) i receive the id. is something wrong writing {% url 'dasboard:editare-agenda' pk=field.id %} but i cannot find the solution.

this is my urls.py:

path('editare-agenda/<"int":pk>', editare_agenda, name="editare-agenda"),

** "int" = int  -> i cannot write int in url path because he disappear

 $.ajax({
    data: values,
    method:"POST",
    url: destinatie,
    contenttType: 'application/json',
    success: function(data){
        var content ="";
        $.each(data.agenda, function(i, field){
            content += '
';
            content += ''+field.denumire_unitate+'	';
            content += ''+field.sectia+'	';
            content += ''+field.telefon+'	';
            content += ''+field.pers_contact+'	';
            content += ''+field.adresa+'	';
            content += '<button type="button" class="btn btn-sm" style="border-radius: 5px;margin: 1px;"></button>	';
            content += '
';
    });
    $('#tabela_agenda').html(content);
}

});