问:
React with StepZilla: type is invalid
I tried to use the StepZilla Component from: https://github.com/newbreedofgeek/react-stepzilla but I have a problem.

I tried the following like explained in the StepZilla homepage:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

var StepZilla = require('react-stepzilla');
const steps =
    [
      {name: 'Step 1', component: <App />}
    ];

ReactDOM.render(<div className='step-progress'>
    <StepZilla step={steps}/>
</div>,document.getElementById('stepDemo'));
</code>```

I always get the following error for the line <StepZilla step={steps}/>:
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

But I think this is correct, because in the example from the StepZilla page it's the same step variable.

答:
I had the same problem, I solved it with a workaround, requiring it like this:

```<code>var StepZilla = require('react-stepzilla').default;
</code>```

See the answers of a similar question:

https://stackoverflow.com/a/34130767/6890793

Title: React with StepZilla: type is invalid

Body:
I tried to use the StepZilla Component from: https://github.com/newbreedofgeek/react-stepzilla but I have a problem.

I tried the following like explained in the StepZilla homepage:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

var StepZilla = require('react-stepzilla');
const steps =
    [
      {name: 'Step 1', component: <App />}
    ];

ReactDOM.render(

    <StepZilla step={steps}/>

,document.getElementById('stepDemo'));

I always get the following error for the line <StepZilla step={steps}/>:
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

But I think this is correct, because in the example from the StepZilla page it's the same step variable.

Body:
I had the same problem, I solved it with a workaround, requiring it like this:

var StepZilla = require('react-stepzilla').default;

See the answers of a similar question:

https://stackoverflow.com/a/34130767/6890793


来源: stackexchange

问:
Migrations in Rails Engine?
I have multiple rails applications talking to the same backend and I'd like them to share some migrations.

I setup a rails engine (with enginex), I can share anything (controllers, views, models,...) but no migrations. I can't make it work !

I tried to create a file db/migrate/my_migration.rb but in my main application if I do :

```<code>  rake db:migrate
</code>```

It doesn't load them.

After some googling it appears there was some recent work on this and it seems this has been merge to rails master.
I'm with rails 3.0.3 do you see any way to make this work ?

Thanks !

答:
What i do, is add an InstallGenerator that will add the migrations to the Rails site itself. It has not quite the same behavior as the one you mentioned, but for now, for me, it is good enough.

A small how-to:

First, create the folder lib\generators\<your-gem-name>\install and inside that folder create a file called install_generator.rb with the following code:

```<code>require 'rails/generators/migration'

module YourGemName
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      include Rails::Generators::Migration
      source_root File.expand_path('../templates', __FILE__)
      desc "add the migrations"

      def self.next_migration_number(path)
        unless @prev_migration_nr
          @prev_migration_nr = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
        else
          @prev_migration_nr += 1
        end
        @prev_migration_nr.to_s
      end

      def copy_migrations
        migration_template "create_something.rb", "db/migrate/create_something.rb"
        migration_template "create_something_else.rb", "db/migrate/create_something_else.rb"
      end
    end
  end
end
</code>```

and inside the lib/generators/<your-gem-name>/install/templates add your two files containing the migrations, e.g. take the one named create_something.rb :

```<code>class CreateAbilities < ActiveRecord::Migration
  def self.up
    create_table :abilities do |t|
      t.string  :name
      t.string  :description
      t.boolean :needs_extent
      t.timestamps
    end
  end

  def self.down
    drop_table :abilities
  end
end
</code>```

Then, when your gem is added to some app, you can just do

```<code>rails g <your_gem_name>:install
</code>```

and that will add the migrations, and then you can just do rake db:migrate.

Hope this helps.

ContentLicense: CC BY-SA 2.5

Title: Migrations in Rails Engine?

Body:
I have multiple rails applications talking to the same backend and I'd like them to share some migrations.

I setup a rails engine (with enginex), I can share anything (controllers, views, models,...) but no migrations. I can't make it work !

I tried to create a file db/migrate/my_migration.rb but in my main application if I do :

  rake db:migrate

It doesn't load them.

After some googling it appears there was some recent work on this and it seems this has been merge to rails master.
I'm with rails 3.0.3 do you see any way to make this work ?

Thanks !

Body:
What i do, is add an InstallGenerator that will add the migrations to the Rails site itself. It has not quite the same behavior as the one you mentioned, but for now, for me, it is good enough.

A small how-to:

First, create the folder lib\generators\<your-gem-name>\install and inside that folder create a file called install_generator.rb with the following code:

require 'rails/generators/migration'

module YourGemName
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      include Rails::Generators::Migration
      source_root File.expand_path('../templates', __FILE__)
      desc "add the migrations"

      def self.next_migration_number(path)
        unless @prev_migration_nr
          @prev_migration_nr = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
        else
          @prev_migration_nr += 1
        end
        @prev_migration_nr.to_s
      end

      def copy_migrations
        migration_template "create_something.rb", "db/migrate/create_something.rb"
        migration_template "create_something_else.rb", "db/migrate/create_something_else.rb"
      end
    end
  end
end

and inside the lib/generators/<your-gem-name>/install/templates add your two files containing the migrations, e.g. take the one named create_something.rb :

class CreateAbilities < ActiveRecord::Migration
  def self.up
    create_table :abilities do |t|
      t.string  :name
      t.string  :description
      t.boolean :needs_extent
      t.timestamps
    end
  end

  def self.down
    drop_table :abilities
  end
end

Then, when your gem is added to some app, you can just do

rails g <your_gem_name>:install

and that will add the migrations, and then you can just do rake db:migrate.

Hope this helps.


问:
Using diff command in unix to find the difference
I have two text files (new.txt and old.txt) which contains the recursively navigated directories.

new.txt

```<code>338465485   16 drwxr-x---  26 encqa2   encqa2      16384 Nov 13 06:04 ./
338465486    4 drwxr-x---   4 encqa2   encqa2       4096 Sep 19 08:38 ./excalibur
338465487    8 drwxr-x---   3 encqa2   encqa2       8192 Nov 11 14:33 ./excalibur/data_in
338465488    4 drwxr-x---   2 encqa2   encqa2       4096 Nov  9 23:16 ./excalibur/data_in/archive
</code>```

old.txt

```<code>338101011   40 drwxr-x---  26 encqa2   encqa2      36864 Nov 13 06:05 ./
338101012    4 drwxr-x---   4 encqa2   encqa2       4096 Dec 14  2016 ./manual
338101013    4 drwxr-x---   2 encqa2   encqa2       4096 Aug 25  2016 ./manual/sorted
338101014    4 drwxr-x---   2 encqa2   encqa2       4096 Aug 25  2016 ./manual/archive
338101015    4 drwxr-x---   4 encqa2   encqa2       4096 Aug 25  2016 ./adp
</code>```

338101016    4 drwxr-x---   6 encqa2   encqa2       4096 Aug 25  2016 ./adp/0235

what I need is the only it provides me the directories , i.e

expected output after diff should be

```<code>./
./excalibur
./excalibur/data_in
./excalibur/data_in/archive
./excalibur/archive
./shares
./shares/data_in
./shares/data_in/archive
./shares/sorted
</code>```

please provide me the command

答:
If I understand correctly, you want to do get those lines from the two text files which are different, but from these lines you want to output only the directory names, not the full information.

If you do a

```<code>diff {old,new}.txt
</code>```

the differing lines are marked in the output with either a '>' or a '<' in the first column, so you get the desired lines  by grepping for these characters:

```<code>diff {old,new}.txt | grep '^[<>]' | ....
</code>```

Now you need only the file names. This is easiest if you know for sure that your pathes won't contain any space. In this case, you can, for instance, pipe your data into:

```<code>... | grep -oE ' [^ ]+$' | cut -d ' ' -f 2 | ...
</code>```

If however the file names can contain spaces, you need to follow a different strategy. For instance, if you know that the number of characters in each line up to the file name is always the same, you can use cut -c .... to select the last portion of the line. Otherwise, you would need to process each line using a regular expression which describes the portion you want to throw away. I would use in this case Perl or Ruby, because I'm most familiar with this, but it can also be done with other tools - Zsh, awk, sed.

After this, you need to remove duplicates. These may occur for instance if a line differs between new.txt and old.txt not in the filename part, but in the file information part. This can be done by finally piping everything into

```<code>.... | sort -u
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two text files (new.txt and old.txt) which contains the recursively navigated directories.

new.txt

338465485   16 drwxr-x---  26 encqa2   encqa2      16384 Nov 13 06:04 ./
338465486    4 drwxr-x---   4 encqa2   encqa2       4096 Sep 19 08:38 ./excalibur
338465487    8 drwxr-x---   3 encqa2   encqa2       8192 Nov 11 14:33 ./excalibur/data_in
338465488    4 drwxr-x---   2 encqa2   encqa2       4096 Nov  9 23:16 ./excalibur/data_in/archive

old.txt

338101011   40 drwxr-x---  26 encqa2   encqa2      36864 Nov 13 06:05 ./
338101012    4 drwxr-x---   4 encqa2   encqa2       4096 Dec 14  2016 ./manual
338101013    4 drwxr-x---   2 encqa2   encqa2       4096 Aug 25  2016 ./manual/sorted
338101014    4 drwxr-x---   2 encqa2   encqa2       4096 Aug 25  2016 ./manual/archive
338101015    4 drwxr-x---   4 encqa2   encqa2       4096 Aug 25  2016 ./adp

338101016    4 drwxr-x---   6 encqa2   encqa2       4096 Aug 25  2016 ./adp/0235

what I need is the only it provides me the directories , i.e

expected output after diff should be

./
./excalibur
./excalibur/data_in
./excalibur/data_in/archive
./excalibur/archive
./shares
./shares/data_in
./shares/data_in/archive
./shares/sorted

please provide me the command

Body:
If I understand correctly, you want to do get those lines from the two text files which are different, but from these lines you want to output only the directory names, not the full information.

If you do a

diff {old,new}.txt

the differing lines are marked in the output with either a '>' or a '<' in the first column, so you get the desired lines  by grepping for these characters:

diff {old,new}.txt | grep '^[<>]' | ....

Now you need only the file names. This is easiest if you know for sure that your pathes won't contain any space. In this case, you can, for instance, pipe your data into:

... | grep -oE ' [^ ]+$' | cut -d ' ' -f 2 | ...

If however the file names can contain spaces, you need to follow a different strategy. For instance, if you know that the number of characters in each line up to the file name is always the same, you can use cut -c .... to select the last portion of the line. Otherwise, you would need to process each line using a regular expression which describes the portion you want to throw away. I would use in this case Perl or Ruby, because I'm most familiar with this, but it can also be done with other tools - Zsh, awk, sed.

After this, you need to remove duplicates. These may occur for instance if a line differs between new.txt and old.txt not in the filename part, but in the file information part. This can be done by finally piping everything into

.... | sort -u


问:
Validating the data with colors in RShiny
I am developing a shiny app. I need to validate the values displayed in textOutput with 2 colors. For instance if the value displayed in textOutput in 100, then pink color should be highlighted. It works for me. But if the value is less than 100 or greater than 100 is displayed, red color should be highlighted. It does not work for me.

In addition to it, I need to center align the text entered and displayed.

```<code>require(shiny)
require(shinyjs)
#install.packages("shinyjs")

ui = fluidPage( useShinyjs(),
                inlineCSS(list(.lightpink   = "background-color: lightpink"), (.red   = "background-color: red")),

                fluidRow(
                  column(3,numericInput("count", "No. of boxes",value = 3, min = 2, max = 10),actionButton("View","view")
                  )
                ),
                fluidRow(uiOutput("inputGroup")),
                fluidRow(column(3,wellPanel(textOutput("text3"))))
)

# takes in two arguments
sumN <- function(a, x){
  a <- sum(a, as.numeric(x),na.rm=T)
  return(a)
}

server <- function(input, output, session) {

  Widgets <- eventReactive(input$View,{ input_list <- lapply(1:(input$count),
                                                             function(i) {
                                                               inputName <- paste("id", i, sep = "")
                                                               textInputRow <- function (inputId,value) {
                                                                 textAreaInput(inputName,"", width = "200px", height = "43px", resize = "horizontal" )
                                                                 #numericInput(inputName,"",1,0,100)
                                                               }
                                                               column(4,textInputRow(inputName, "")) })
  do.call(tagList, input_list)},ignoreInit = T)

  output$inputGroup = renderUI({Widgets()})

  getvalues <- reactive({
    val <- 0
    for(lim in 1:input$count){
      observeEvent(input[[paste0("id",lim)]], {
        updateTextAreaInput(session,paste0("id",lim), value = ({
          x =  as.numeric(input[[paste0("id",lim)]])
          if(!(is.numeric(x))){0}
          else if(!(is.null(x) || is.na(x))){
            if(x < 0){
              0
            }else if(x > 100){
              100
            } else{
              return (isolate(input[[paste0("id",lim)]]))
            }
          }
          #else{0}
          else if((is.null(x) || is.na(x))){
            0
          }
        })
        )
      })
      req(as.numeric(input[[paste0("id",lim)]]) >= 0 & as.numeric(input[[paste0("id",lim)]]) <= 100)
      val <- sumN(val,as.numeric(input[[paste0("id",lim)]]))
    }
    val
  })

  output$text3 <- renderText({
    #getvalues()
    # if(getvalues() > 100){
    #    0

    # }
    #else(getvalues())

    getvalues()

  })

  observeEvent(getvalues(), {
    nn <- getvalues()
    if(is.numeric(as.numeric(nn)) & !is.na(as.numeric(nn)) & nn == 100) {

      addClass("text3", 'lightpink')

    } else  { addClass('text3','red')}
  })

}

shinyApp(ui=ui, server = server)
</code>```

This is the code used..

The screenshot of the output. If value exceeds 100, it should turn red.

Can anyone help me with this code?

答:
Added removeClass to fix the pink and apply red:

```<code>    require(shiny)
require(shinyjs)
#install.packages("shinyjs")

ui = fluidPage( useShinyjs(),
                inlineCSS(list('.lightpink' = "background-color: lightpink",'.red'   = "background-color: red", "textarea" = 'text-align: center', '#text3 ' = 'text-align: center')),

                fluidRow(
                  column(3,numericInput("count", "No. of boxes",value = 3, min = 2, max = 10),actionButton("View","view")
                  )
                ),
                fluidRow(uiOutput("inputGroup")),
                fluidRow(column(3,wellPanel(textOutput("text3"))))
)

# takes in two arguments
sumN <- function(a, x){
  a <- sum(a, as.numeric(x),na.rm=T)
  return(a)
}

server <- function(input, output, session) {

  Widgets <- eventReactive(input$View,{ input_list <- lapply(1:(input$count),
                                                             function(i) {
                                                               inputName <- paste("id", i, sep = "")
                                                               textInputRow <- function (inputId,value) {
                                                                 textAreaInput(inputName,"", width = "200px", height = "43px", resize = "horizontal" )
                                                                 #numericInput(inputName,"",1,0,100)
                                                               }
                                                               column(4,textInputRow(inputName, "")) })
  do.call(tagList, input_list)},ignoreInit = T)

  output$inputGroup = renderUI({Widgets()})

  getvalues <- reactive({
    val <- 0
    for(lim in 1:input$count){
      observeEvent(input[[paste0("id",lim)]], {
        updateTextAreaInput(session,paste0("id",lim), value = ({
          x =  as.numeric(input[[paste0("id",lim)]])
          if(!(is.numeric(x))){0}
          else if(!(is.null(x) || is.na(x))){
            if(x < 0){
              0
            }else if(x > 100){
              100
            } else{
              return (isolate(input[[paste0("id",lim)]]))
            }
          }
          #else{0}
          else if((is.null(x) || is.na(x))){
            0
          }
        })
        )
      })
      req(as.numeric(input[[paste0("id",lim)]]) >= 0 & as.numeric(input[[paste0("id",lim)]]) <= 100)
      val <- sumN(val,as.numeric(input[[paste0("id",lim)]]))
    }
    val
  })

  output$text3 <- renderText({
    #getvalues()
    # if(getvalues() > 100){
    #    0

    # }
    #else(getvalues())

    getvalues()

  })

  observeEvent(getvalues(), {
    nn <- getvalues()
    if(is.numeric(as.numeric(nn)) & !is.na(as.numeric(nn)) & nn == 100) {

      removeClass("text3", 'red')
      addClass('text3','lightpink')

    } else  { addClass('text3','red')}
  })

}

shinyApp(ui=ui, server = server)
</code>```

Body:
I am developing a shiny app. I need to validate the values displayed in textOutput with 2 colors. For instance if the value displayed in textOutput in 100, then pink color should be highlighted. It works for me. But if the value is less than 100 or greater than 100 is displayed, red color should be highlighted. It does not work for me.

In addition to it, I need to center align the text entered and displayed.

require(shiny)
require(shinyjs)
#install.packages("shinyjs")

ui = fluidPage( useShinyjs(),
                inlineCSS(list(.lightpink   = "background-color: lightpink"), (.red   = "background-color: red")),

                fluidRow(
                  column(3,numericInput("count", "No. of boxes",value = 3, min = 2, max = 10),actionButton("View","view")
                  )
                ),
                fluidRow(uiOutput("inputGroup")),
                fluidRow(column(3,wellPanel(textOutput("text3"))))
)

# takes in two arguments
sumN <- function(a, x){
  a <- sum(a, as.numeric(x),na.rm=T)
  return(a)
}

server <- function(input, output, session) {

  Widgets <- eventReactive(input$View,{ input_list <- lapply(1:(input$count),
                                                             function(i) {
                                                               inputName <- paste("id", i, sep = "")
                                                               textInputRow <- function (inputId,value) {
                                                                 textAreaInput(inputName,"", width = "200px", height = "43px", resize = "horizontal" )
                                                                 #numericInput(inputName,"",1,0,100)
                                                               }
                                                               column(4,textInputRow(inputName, "")) })
  do.call(tagList, input_list)},ignoreInit = T)

  output$inputGroup = renderUI({Widgets()})

  getvalues <- reactive({
    val <- 0
    for(lim in 1:input$count){
      observeEvent(input[[paste0("id",lim)]], {
        updateTextAreaInput(session,paste0("id",lim), value = ({
          x =  as.numeric(input[[paste0("id",lim)]])
          if(!(is.numeric(x))){0}
          else if(!(is.null(x) || is.na(x))){
            if(x < 0){
              0
            }else if(x > 100){
              100
            } else{
              return (isolate(input[[paste0("id",lim)]]))
            }
          }
          #else{0}
          else if((is.null(x) || is.na(x))){
            0
          }
        })
        )
      })
      req(as.numeric(input[[paste0("id",lim)]]) >= 0 & as.numeric(input[[paste0("id",lim)]]) <= 100)
      val <- sumN(val,as.numeric(input[[paste0("id",lim)]]))
    }
    val
  })

  output$text3 <- renderText({
    #getvalues()
    # if(getvalues() > 100){
    #    0

    # }
    #else(getvalues())

    getvalues()

  })

  observeEvent(getvalues(), {
    nn <- getvalues()
    if(is.numeric(as.numeric(nn)) & !is.na(as.numeric(nn)) & nn == 100) {

      addClass("text3", 'lightpink')

    } else  { addClass('text3','red')}
  })

}

shinyApp(ui=ui, server = server)

This is the code used..

The screenshot of the output. If value exceeds 100, it should turn red.

Can anyone help me with this code?

Body:
Added removeClass to fix the pink and apply red:

    require(shiny)
require(shinyjs)
#install.packages("shinyjs")

ui = fluidPage( useShinyjs(),
                inlineCSS(list('.lightpink' = "background-color: lightpink",'.red'   = "background-color: red", "textarea" = 'text-align: center', '#text3 ' = 'text-align: center')),

                fluidRow(
                  column(3,numericInput("count", "No. of boxes",value = 3, min = 2, max = 10),actionButton("View","view")
                  )
                ),
                fluidRow(uiOutput("inputGroup")),
                fluidRow(column(3,wellPanel(textOutput("text3"))))
)

# takes in two arguments
sumN <- function(a, x){
  a <- sum(a, as.numeric(x),na.rm=T)
  return(a)
}

server <- function(input, output, session) {

  Widgets <- eventReactive(input$View,{ input_list <- lapply(1:(input$count),
                                                             function(i) {
                                                               inputName <- paste("id", i, sep = "")
                                                               textInputRow <- function (inputId,value) {
                                                                 textAreaInput(inputName,"", width = "200px", height = "43px", resize = "horizontal" )
                                                                 #numericInput(inputName,"",1,0,100)
                                                               }
                                                               column(4,textInputRow(inputName, "")) })
  do.call(tagList, input_list)},ignoreInit = T)

  output$inputGroup = renderUI({Widgets()})

  getvalues <- reactive({
    val <- 0
    for(lim in 1:input$count){
      observeEvent(input[[paste0("id",lim)]], {
        updateTextAreaInput(session,paste0("id",lim), value = ({
          x =  as.numeric(input[[paste0("id",lim)]])
          if(!(is.numeric(x))){0}
          else if(!(is.null(x) || is.na(x))){
            if(x < 0){
              0
            }else if(x > 100){
              100
            } else{
              return (isolate(input[[paste0("id",lim)]]))
            }
          }
          #else{0}
          else if((is.null(x) || is.na(x))){
            0
          }
        })
        )
      })
      req(as.numeric(input[[paste0("id",lim)]]) >= 0 & as.numeric(input[[paste0("id",lim)]]) <= 100)
      val <- sumN(val,as.numeric(input[[paste0("id",lim)]]))
    }
    val
  })

  output$text3 <- renderText({
    #getvalues()
    # if(getvalues() > 100){
    #    0

    # }
    #else(getvalues())

    getvalues()

  })

  observeEvent(getvalues(), {
    nn <- getvalues()
    if(is.numeric(as.numeric(nn)) & !is.na(as.numeric(nn)) & nn == 100) {

      removeClass("text3", 'red')
      addClass('text3','lightpink')

    } else  { addClass('text3','red')}
  })

}

shinyApp(ui=ui, server = server)


问:
How to avoid detecting uninitialized variables when using the impact analysis of Frama-C
I find that if there is an uninitialized left-value (variable X for example) in the program, Frama-C asserts that X has been initialized, but then the assertion gets the final status invalid. It seems that Frama-C stops the analysis after detecting the invalid final status, so that the actual result of the impact analysis (the impacted statements) is just a part of the ideal result. I want Frama-C to proceed the impact analysis regardless of those uninitialized variables, but I haven't found any related options yet. How to deal with this problem?</p>

答:
You're invoking an undefined behavior as indicated in annex J.2 of ISO C standard "The value of an object with automatic storage duration is used while it is indeterminate" (Note to language lawyers: said annex is informative, and I've been unable to trace that claim back to the normative sections of the standard, at least for C11). The EVA plug-in, which is used internally by Impact analysis, restricts itself to execution paths that have a well-defined meaning according to the standard (the proverbial nasal demons are not part of the abstract domains of EVA). If there are no such paths, abstract execution will indeed stop. The appropriate way to deal with this problem is to ensure the local variables of the program under analysis are properly initialized before being accessed.

Update

I forgot to mention that in the next version (16 - Sulfur), whose beta version is available at https://github.com/Frama-C/Frama-C-snapshot/wiki/downloads/frama-c-Sulfur-20171101-beta.tar.gz, EVA has an option -val-initialized-locals, whose help specifies:

Local variables enter in scope fully initialized. Only useful for the analysis of programs buggy w.r.t. initialization.


问:
Column Store Indexes in SQL Server
Are column store indexes in SQL Server useful only when the query uses aggregate functions?

答:
Columnstore Indexes, stores data in columnar format, therefore they are quite helpful when you are using aggregate functions. One of the reason is, because homogeneous data compression is much faster when you are trying to aggregate columns.

But this is not the only use of columnstore indexes. It is really helpful when you are processing millions of rows (in multidimensional data models).
Check out the official documentation   and this as well for better understanding.

Title: Column Store Indexes in SQL Server


问:
Why isn't my for loop adding more than one random value to my list?
I'm trying to create a bubble sort algorithm in java and I'm trying to create a list with random integers in it with a for loop, however it only ever has one value. This is the code:</p>

```<code>public class bubbleSort {

public static void main(String[] args)
{

    int length = getLength();

    System.out.println(length);

    List<Integer> randomList = createArray(length);

    System.out.println(randomList);

}

public static int getLength()
{
    System.out.println("Please enter how long you want the array to be");

    Scanner reader = new Scanner(System.in);

    int length = Integer.parseInt(reader.nextLine());

    return length;
}

public static List<Integer> createArray(int length)
{
    Random rand = new Random();

    List<Integer> randomList = new ArrayList<Integer>();

    for(int x = 0 ; x < (length + 1) ; x++);
    {
        int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
        randomList.add(randomnumber);
    }

    return randomList;
}

}
</code>```

答:
There should be no semicolon (;) after your for loop declaration .That is why the loop keeps exiting after the first loop,
It should be

```<code>for(int x = 0 ; x < (length + 1) ; x++)
{
    int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
    randomList.add(randomnumber);
}
</code>```

And why do you have a (length +1)..if you want the size of the random list to be the size of the length ,you should remove the +1.

Body:
I'm trying to create a bubble sort algorithm in java and I'm trying to create a list with random integers in it with a for loop, however it only ever has one value. This is the code:

public class bubbleSort {

public static void main(String[] args)
{

    int length = getLength();

    System.out.println(length);

    List<Integer> randomList = createArray(length);

    System.out.println(randomList);

}

public static int getLength()
{
    System.out.println("Please enter how long you want the array to be");

    Scanner reader = new Scanner(System.in);

    int length = Integer.parseInt(reader.nextLine());

    return length;
}

public static List<Integer> createArray(int length)
{
    Random rand = new Random();

    List<Integer> randomList = new ArrayList<Integer>();

    for(int x = 0 ; x < (length + 1) ; x++);
    {
        int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
        randomList.add(randomnumber);
    }

    return randomList;
}

}

Body:
There should be no semicolon (;) after your for loop declaration .That is why the loop keeps exiting after the first loop,
It should be

for(int x = 0 ; x < (length + 1) ; x++)
{
    int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
    randomList.add(randomnumber);
}

And why do you have a (length +1)..if you want the size of the random list to be the size of the length ,you should remove the +1.


问:
How to get div values that are dynamically generated by a php script?
I want to alert the name of the item whose place bid button I will click but my code seems to alert only laptop. Can anyone tell me how to get div values that are dynamically generated through a php script. Below is the code for the page.I want to alert name of that item whose place bid I click on. Since the page is dynamically generated which gets item details from a database containing item details.

<?php
 $con = mysqli_connect("localhost","root","*****","bidding") or
 die(mysqli_error($con));
 $select_query = "select * from items";
 $select_query_result = mysqli_query($con, $select_query) or
 die("Query Mistake");
?>
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Bid</title>
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="materialize/css/materialize.css"/>
        <link rel="stylesheet" type="text/css" href="seperate2.css">

Bid

   <?php while($row = mysqli_fetch_array($select_query_result)) { ?>

<?php echo"$row[item_name]"?>

<?php echo"$row[starting_price]"?

<?php echo"$row[description]"?>

    <button class="btn waves-effect waves-teal"
                 onclick="post_data()">Place Bid</button>

      <?php } ?>

```

答:
ID of element in HTML must be unique. Use class.
In loop you declare static name of ID, that are not unique.</p>


问:
Google spreadsheet editor: reorder script files
In a google spreadsheet script editor I have several files. I need to reorder the files but can't find a way. Tried to move them with mouse and no luck, and there is no other option to move them up or down.

Is there any way or trick to move the script files up or down?

Here is a sample screenshot, which I would like to move util.gs to the bottom:

答:
Do you still look for the method for reordering scripts in a project using GAS? I have commented about this. But the application I did is a CLI tool made of Golang. So I created the GUI application using GAS. I post the detail method as my answer.

Recently, I found the workaround for rearranging scripts in a project. The flow is as follows.

Flow for rearranging scripts :

Download all scripts in a project.

Overwrite the project by one script with the filename which is difference from the filenames of downloaded scripts.

Rearrange the downloaded scripts.

Overwrite the project by the rearranged scripts. At this time, remove the script ID of each script.

When existing project is overwritten by a script with an unique filename, all scripts in the project are removed and only the file with the unique name is remained. I thought that this can be applied for rearranging scripts.

Key factor for creating this application using GAS :

When the project is updated, a special scope of https://www.googleapis.com/auth/drive.scripts is required. This was required to be retrieved by OAuth2 process. But by recent Google update, the Manifests was added. Manifests made users easily use the script which needs such special scopes.

When above flow is reflected to GAS script, the application is as follows.

IMPORTANT!

For rearranging scripts, there is one important point. When scripts in a project is rearranged, version history of scripts is reset once. So if you don't want to reset the version history, before rearranging, please copy the project. By copying project, the project before rearranging is saved.

Scripts and how to use this are this repo at GitHub.

Is this useful for you?


问:
Intel Pin call a function in the application program
I am using the Intel Pin tool to do some analysis on my application program. I have an instrumentation routine and a signal handler that does some analysis in the application program and then based on some condition makes a call to a function in the application program to update some value.

My application program is written in C which is as follows-

```<code>int pin_flag; //global variable in the C program

void access_from_pin()
{
    pin_flag = 1;
}

void Check() //empty function in C
{
}

int main()
{
    while(!pin_flag)
    {
        Check();
    }
    printf("Pin has changed the flag");
}
</code>```

My Pintool in C++ is as follows-

```<code>VOID check_routine(THREADID tid, ADDRINT ret)
{
    ADDRINT *addr = ; //hardcode address of the function access_from_pin
    ((void(*)(void))addr)();
}

VOID Image(IMG img, VOID *v)
{
    RTN check_call = RTN_FindByName(img, "Check");
    if (RTN_Valid(check_call))
    {
        RTN_Open(check_call);

        RTN_InsertCall(check_call, IPOINT_AFTER, (AFUNPTR)check_routine,IARG_THREAD_ID,IARG_END);

        RTN_Close(check_call);
    }

}

int main(int argc, char *argv[])
{
    PIN_InitSymbols();

    if (PIN_Init(argc, argv))
            return Usage();

    /* Image Instrumentation function*/
    IMG_AddInstrumentFunction(Image, 0);

    PIN_StartProgram();
    return 0;
}
</code>```

When I run my pintool with the application program as the C program, I get a segmentation fault. Is the Image routine the correct way to check a call for a particular function? Also can I directly access a function from the application program using its address? I get the address of the function through some other means, and it is valid so that is not the problem. Since Pin modifies the code at runtime and this pintool simply modifies the flow of the instructions and on a certain condition I should be able to jump to a valid address. Any ideas where I am going wrong?

答: You must use PIN_CallApplicationFunction API to call a function in the application in a way that would actually work.</p>

Body:
I am using the Intel Pin tool to do some analysis on my application program. I have an instrumentation routine and a signal handler that does some analysis in the application program and then based on some condition makes a call to a function in the application program to update some value.

My application program is written in C which is as follows-

int pin_flag; //global variable in the C program

void access_from_pin()
{
    pin_flag = 1;
}

void Check() //empty function in C
{
}

int main()
{
    while(!pin_flag)
    {
        Check();
    }
    printf("Pin has changed the flag");
}

My Pintool in C++ is as follows-

VOID check_routine(THREADID tid, ADDRINT ret)
{
    ADDRINT *addr = ; //hardcode address of the function access_from_pin
    ((void(*)(void))addr)();
}

VOID Image(IMG img, VOID *v)
{
    RTN check_call = RTN_FindByName(img, "Check");
    if (RTN_Valid(check_call))
    {
        RTN_Open(check_call);

        RTN_InsertCall(check_call, IPOINT_AFTER, (AFUNPTR)check_routine,IARG_THREAD_ID,IARG_END);

        RTN_Close(check_call);
    }

}

int main(int argc, char *argv[])
{
    PIN_InitSymbols();

    if (PIN_Init(argc, argv))
            return Usage();

    /* Image Instrumentation function*/
    IMG_AddInstrumentFunction(Image, 0);

    PIN_StartProgram();
    return 0;
}

When I run my pintool with the application program as the C program, I get a segmentation fault. Is the Image routine the correct way to check a call for a particular function? Also can I directly access a function from the application program using its address? I get the address of the function through some other means, and it is valid so that is not the problem. Since Pin modifies the code at runtime and this pintool simply modifies the flow of the instructions and on a certain condition I should be able to jump to a valid address. Any ideas where I am going wrong?


问:
what is the difference between ` ` and ' '?
Hey guys i want to know that what is the difference between these two type of single quotes` and '

i tried to execute the below command with ` then it worked

```<code>axios.get(`https://api.github.com/users/${this.state.userName}`)
      .then(resp => {
        console.log(resp);
      });
</code>```

but when i tried to run the same command using '' it doesnt work

```<code>axios.get('https://api.github.com/users/${this.state.userName}')
          .then(resp => {
            console.log(resp);
          });
</code>```

答:
Backticks (`) are used to define Template Literals strings in JavaScript since ES6. These are used to use inline variables as well as declare multiline strings, previously not possible without concatenation (+).

Eg:

```<code>var name = 'John';
var string1 = 'My name is ' + name;   //ES5
var string2 = `My name is ${name}`;   //ES6
</code>```

also can be used to declare multiline strings:

```<code>var longString = `this is a
                  really
                  long
                  multiline
                  string`;
</code>```

EDIT Regarding my multiline example, template literals preserve whitespace. So the example won't be stored as you think it would. This link http://2ality.com/2016/05/template-literal-whitespace.html would be useful on that end.

Body:
Hey guys i want to know that what is the difference between these two type of single quotes` and '

i tried to execute the below command with ` then it worked

axios.get(`https://api.github.com/users/${this.state.userName}`)
      .then(resp => {
        console.log(resp);
      });

but when i tried to run the same command using '' it doesnt work

axios.get('https://api.github.com/users/${this.state.userName}')
          .then(resp => {
            console.log(resp);
          });

Body:
Backticks (`) are used to define Template Literals strings in JavaScript since ES6. These are used to use inline variables as well as declare multiline strings, previously not possible without concatenation (+).

Eg:

var name = 'John';
var string1 = 'My name is ' + name;   //ES5
var string2 = `My name is ${name}`;   //ES6

also can be used to declare multiline strings:

var longString = `this is a
                  really
                  long
                  multiline
                  string`;

EDIT Regarding my multiline example, template literals preserve whitespace. So the example won't be stored as you think it would. This link http://2ality.com/2016/05/template-literal-whitespace.html would be useful on that end.


问:
How does exponent work in complex data structure in python?
I was exploring complex data structure in python. I have done addition, subtraction, multiplication and division between two complex value in python IDLE. All of them makes sense but when I tried to exponent a complex value something strange came up. I have no idea how that happened! Can anyone explain to me what's going under the hood?

I was trying to understand the following code:

```<code>>>> w = complex(2, -3)
>>> v = complex(5)
>>> w ** v
(122+597j)
</code>```

So, I was wondering how w ** v evaluates to (122+597j). Thanks in advance.

Body:
I was exploring complex data structure in python. I have done addition, subtraction, multiplication and division between two complex value in python IDLE. All of them makes sense but when I tried to exponent a complex value something strange came up. I have no idea how that happened! Can anyone explain to me what's going under the hood?

I was trying to understand the following code:

>>> w = complex(2, -3)
>>> v = complex(5)
>>> w ** v
(122+597j)

So, I was wondering how w ** v evaluates to (122+597j). Thanks in advance.

Body:
Recall that complex(2,-3) = 2 - 3j. With Newton's formula you get

 (a + b)**5 = a**5 + 5 a**4 b + 10 a**3 b**2 +
              10 a**2 b**3 + 5 a b**4 + b**5

Applying Newton's formula to our case you get

  (2 - 3j) ** 5 =
      2 ** 5 - 5 * 2**4 * 3j -
      10 * 2**3 * 3**2 +
      10 * 2**2 * 3**3 j +
      5 * 2 * 3**4 - 3**5 j =
      (2 ** 5 - 10 * 2**3 * 3**2 + 5 * 2 * 3**4) +
      (- 5 * 2**4 *3  + 10 * 2**2 * 3**3 - 3**5)j =
      122 + 597j


问:
Why does my UIVIew load offscreen?
When my application starts I execute this code:

```<code>LViewController *aLViewController = [[LViewController alloc] initWithNibName:@"LViewController" bundle:[NSBundle mainBundle]];
self.viewController = aLViewController;
[aLViewController release];
[window addSubview:[viewController view]];
</code>```

but the view always loads a little too high and is hidden behind the status bar. I've tried changing the simulated user elements in Interface Builder to include the status bar but it didn't help.

答:
You have to account for the height of the status bar when you add the view to the window:</p>

```<code>CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
CGSize statusBarSize = statusBarFrame.size;
CGFloat statusBarHeight = statusBarSize.height;

LViewController *aLViewController = [[LViewController alloc] initWithNibName:@"LViewController" bundle:[NSBundle mainBundle]];
self.viewController = aLViewController;
[aLViewController release];

viewController.view.frame = CGRectMake(0.0f,
                                       statusBarHeight,
                                       window.bounds.size.width,
                                       window.bounds.size.height - statusBarHeight);

[window addSubview:[viewController view]];
</code>```

Title: Why does my UIVIew load offscreen?

Body:
When my application starts I execute this code:

LViewController *aLViewController = [[LViewController alloc] initWithNibName:@"LViewController" bundle:[NSBundle mainBundle]];
self.viewController = aLViewController;
[aLViewController release];
[window addSubview:[viewController view]];

but the view always loads a little too high and is hidden behind the status bar. I've tried changing the simulated user elements in Interface Builder to include the status bar but it didn't help.

Body:
You have to account for the height of the status bar when you add the view to the window:

CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
CGSize statusBarSize = statusBarFrame.size;
CGFloat statusBarHeight = statusBarSize.height;

LViewController *aLViewController = [[LViewController alloc] initWithNibName:@"LViewController" bundle:[NSBundle mainBundle]];
self.viewController = aLViewController;
[aLViewController release];

viewController.view.frame = CGRectMake(0.0f,
                                       statusBarHeight,
                                       window.bounds.size.width,
                                       window.bounds.size.height - statusBarHeight);

[window addSubview:[viewController view]];


问:
Promise fulfilled inspite of rejection
I am using bluebird settle method to check results for promises regardless of any rejections. In the secondMethod  I have rejected the promise still I get    isFulfilled() true.

```<code>var Promise = require('bluebird');

Promise.settle([firstMethod, secondMethod]).then(function(results){
    console.log(results[0].isFulfilled());
    console.log(results[1].isFulfilled());
   // console.log(results[1].reason());
}).catch(function(error){
    console.log(error);
});

    var firstMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         resolve({data: '123'});
      }, 2000);
   });
   return promise;
};

var secondMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         reject((new Error('fail')));
      }, 2000);
   });
   return promise;
};
</code>```

答:
Pretty sure isFulfilled is referring to if it is complete or not, regardless of if it's resolved or rejected.

You can use something like isRejected to check to see if the promise has been rejected.

Title: Promise fulfilled inspite of rejection

Body:
I am using bluebird settle method to check results for promises regardless of any rejections. In the secondMethod  I have rejected the promise still I get    isFulfilled() true.

var Promise = require('bluebird');

Promise.settle([firstMethod, secondMethod]).then(function(results){
    console.log(results[0].isFulfilled());
    console.log(results[1].isFulfilled());
   // console.log(results[1].reason());
}).catch(function(error){
    console.log(error);
});

    var firstMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         resolve({data: '123'});
      }, 2000);
   });
   return promise;
};

var secondMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         reject((new Error('fail')));
      }, 2000);
   });
   return promise;
};


答:
The first one `` is template literal or back ticks, where the second '' is single quotes

Template literal can be used for multi line and may use "interpolation" to insert the content of variables along $

With quotes '' this will require a string concatenation.

In your case it is used as interpolation

console.log(`Hello I am

template literal `)

console.log("Hello I am" +

  " quotes")```

Title: what is the difference between ` ` and ' '?


问:
How to make gatsbyjs sites in Amazon S3 bucket using Amazon Lambda function?
I want to make AWS lambda function that will create new gatsbyjs sites in Amazon S3 bucket. I am familiar with aws lambda but So I need a help that anybody know the steps for that please let me.</p>

答:
You basically just create the site in Lambda and then upload the files to the S3 bucket.

The bucket needs to have all the uploaded files set as public, so the following bucket policy needs to be attached to the bucket.

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AddPerm",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::my-gatsby-files/*"
    }
  ]
}
</code>```

A Gatsby site is a Single-Page Application, so all the requests need to be directed through index.html. To enable this, select Static Website Hosting in the bucket Properties. Select Enable website hosting and set index.html to both Index Document and Error Document.

Body:
You basically just create the site in Lambda and then upload the files to the S3 bucket.

The bucket needs to have all the uploaded files set as public, so the following bucket policy needs to be attached to the bucket.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AddPerm",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::my-gatsby-files/*"
    }
  ]
}

A Gatsby site is a Single-Page Application, so all the requests need to be directed through index.html. To enable this, select Static Website Hosting in the bucket Properties. Select Enable website hosting and set index.html to both Index Document and Error Document.


问:
Change table row color depending on multiple selections/hide elements
I have a table. On each row I have a checkbox to "select it", two select boxes and an extra checkbox.

When I show my page, each row background color is the default one (white).

What I need is two things:

For each "Action" select box value, I want the row to change its color but only if the row checkbox is checked - Green for 'create' and Red for 'delete'

If the "Action" select box value is equal 'delete', I want the second select box and the extra checkbox to be disabled.

At the moment, I have the following code that changes the row background color depending only on the first select box choice, not taking into account the state of the checkbox.

How can I implement this? I don't know how to make these conditions work together.

Thanks.

NOTE: I'm using this code in Drupal but it's generic.
SECOND NOTE: This is used in drupal so I'm using a theme that has already css for the table. When I hover for example and for odd/even rows, some colors are already being applied. Don't know if this has impact on the code to implement what I need.

HTML:

```<code><table class="containers_table sticky-enabled table-select-processed tableheader-processed sticky-table">
 <thead><tr><th class="select-all"><input type="checkbox" class="form-checkbox" title="Select all rows in this table"></th><th>Container</th><th></th><th></th><th></th><th>Action</th><th>Configuration</th><th>scripts</th> </tr></thead>
<tbody>
 <tr class="odd"><td style="background-color: rgb(215, 234, 217);"><div class="form-item form-type-checkbox form-item-containers-table-VT-1">
  <input class="containers_table form-checkbox" type="checkbox" id="edit-containers-table-vt-1" name="containers_table[VT_1]" value="VT_1">
</div>
</td><td style="background-color: rgb(215, 234, 217);">container 1</td><td style="background-color: rgb(215, 234, 217);">a</td><td style="background-color: rgb(215, 234, 217);">b</td><td style="background-color: rgb(215, 234, 217);">c</td><td style="background-color: rgb(215, 234, 217);"><div class="form-item form-type-select form-item-action-VT-1">
  <label class="element-invisible">Action for VT_1 </label>
 <select class="update-action form-select chosen-processed" name="action[VT_1]" style="display: none;"><option value="create">create</option><option value="delete">delete</option></select><div class="chosen-container chosen-container-single update-action form-select chosen-processed" title="" style="width: 300px;"><a class="chosen-single">
  <span>create</span>
  <div><b></b></div>
</a>
<div class="chosen-drop">
  <div class="chosen-search">
    <input class="chosen-search-input" type="text" autocomplete="off">
  </div>
  <ul class="chosen-results"></ul>
</div></div>
</div>
</td><td style="background-color: rgb(215, 234, 217);"><div class="form-item form-type-select form-item-card-configuration-VT-1">
  <label class="element-invisible">Card configuration for VT_1 </label>
 <select class="update-card_configuration form-select chosen-processed" name="card_configuration[VT_1]" style="display: none;"><option value="default">default</option><option value="HalSim_VT_1_OCC2">HalSim_VT_1_OCC2</option><option value="HalSim_VT_2_OCC2">HalSim_VT_2_OCC2</option><option value="HalSim_VT_3_OCC2">HalSim_VT_3_OCC2</option></select><div class="chosen-container chosen-container-single update-card_configuration form-select chosen-processed" title="" style="width: 300px;"><a class="chosen-single">
  <span>default</span>
  <div><b></b></div>
</a>
<div class="chosen-drop">
  <div class="chosen-search">
    <input class="chosen-search-input" type="text" autocomplete="off">
  </div>
  <ul class="chosen-results"></ul>
</div></div>
</div>
</td><td style="background-color: rgb(215, 234, 217);"><div class="form-item form-type-checkbox form-item-ne-configuration-VT-1">
  <label class="element-invisible">NE configuration for VT_1 </label>
 <input class="update-ne_configuration form-checkbox" type="checkbox" name="ne_configuration[VT_1]" value="1">
</div>
</td> </tr>
 <tr class="even"><td style="background-color: rgb(215, 234, 217);"><div class="form-item form-type-checkbox form-item-containers-table-VT-2">
  <input class="containers_table form-checkbox" type="checkbox" id="edit-containers-table-vt-2" name="containers_table[VT_2]" value="VT_2">
</div>
</td><td style="background-color: rgb(215, 234, 217);">container 2</td><td style="background-color: rgb(215, 234, 217);">d</td><td style="background-color: rgb(215, 234, 217);">e</td><td style="background-color: rgb(215, 234, 217);">f</td><td style="background-color: rgb(215, 234, 217);"><div class="form-item form-type-select form-item-action-VT-2">
  <label class="element-invisible">Action for VT_2 </label>
 <select class="update-action form-select chosen-processed" name="action[VT_2]" style="display: none;"><option value="create">create</option><option value="delete">delete</option></select><div class="chosen-container chosen-container-single update-action form-select chosen-processed" title="" style="width: 300px;"><a class="chosen-single">
  <span>create</span>
  <div><b></b></div>
</a>
<div class="chosen-drop">
  <div class="chosen-search">
    <input class="chosen-search-input" type="text" autocomplete="off">
  </div>
  <ul class="chosen-results"></ul>
</div></div>
</div>
</td><td style="background-color: rgb(215, 234, 217);"><div class="form-item form-type-select form-item-card-configuration-VT-2">
  <label class="element-invisible">Card configuration for VT_2 </label>
 <select class="update-card_configuration form-select chosen-processed" name="card_configuration[VT_2]" style="display: none;"><option value="default">default</option><option value="HalSim_VT_1_OCC2">HalSim_VT_1_OCC2</option><option value="HalSim_VT_2_OCC2">HalSim_VT_2_OCC2</option><option value="HalSim_VT_3_OCC2">HalSim_VT_3_OCC2</option></select><div class="chosen-container chosen-container-single update-card_configuration form-select chosen-processed" title="" style="width: 300px;"><a class="chosen-single">
  <span>default</span>
  <div><b></b></div>
</a>
<div class="chosen-drop">
  <div class="chosen-search">
    <input class="chosen-search-input" type="text" autocomplete="off">
  </div>
  <ul class="chosen-results"></ul>
</div></div>
</div>
</td><td style="background-color: rgb(215, 234, 217);"><div class="form-item form-type-checkbox form-item-ne-configuration-VT-2">
  <label class="element-invisible">NE configuration for VT_2 </label>
 <input class="update-ne_configuration form-checkbox" type="checkbox" name="ne_configuration[VT_2]" value="1">
</div>
</td> </tr>
 </tbody>
</table>
</code>```

JQUERY:

```<code>(function($) {
    Drupal.behaviors.mymoduleColorRows = {
        attach: function(context) {

            // Bind change event to select
            $('.update-action').change(function(){
                setColors();
            });

            $('.edit-containers-table-groove-vt-1').change(function(){
                setColors2();
            });

            // Call function on first page load
            setColors();

            function setColors() {
                // Loop rows
                $('.containers_table tr').each(function(){
                    // Get color from value of select
                    var color = $(this).find('.update-action').val() == 'create' ? '#D7EAD9' : '#F5BE8B';
                    // Set color
                    $(this).find('td').css({'background-color': color});

                });
            }

            function setColors2() {
                // Loop rows
                $('.containers_table tr').each(function(){
                    // Get color from value of select
                    var color = '#F5BE8B';
                    // Set color
                    $(this).find('td').css({'background-color': color});

                });
            }
        }
    };

})(jQuery);
</code>```

答:
The usage of a row template is suitable only if you do not intend to use hierarchy, grouping, and editing columns. the Grid does not support the simultaneous application of these features and row templates. The approach directly adds template expressions to the rowTemplate and altRowTemplate definitions and determines which custom CSS classes will be applied to a given row or cell.</p>

```<code><style>
  .k-grid {
    width: 500px;
  }

  .discontinued {
    font-weight: bold;
    color: #f00;
  }
  .critical {
    background-color: #fdd;
  }

  .warning {
    background-color: #fda;
  }

  .ok {
    background-color: #ced;
  }

</style>

<div id="grid-rowtemplate"></div>
<script>
  // sample datasource
  var products = [
    { ID: 1, ProductName: "Foo", UnitsInStock: 9, Discontinued: false },
    { ID: 2, ProductName: "Bar", UnitsInStock: 16, Discontinued: false },
    { ID: 3, ProductName: "Baz", UnitsInStock: 3, Discontinued: true }
  ];

  var rowTemplateString = '<tr class="#: Discontinued ? "discontinued" : "" #" data-uid="#: uid #">' +
      '<td>#: ProductName #</td>' +
      '<td class="#: getUnitsInStockClass(UnitsInStock) #">#: UnitsInStock #</td>' +
      '<td>#: Discontinued #</td>' +
      '</tr>';

  var altRowTemplateString = rowTemplateString.replace('tr class="', 'tr class="k-alt ');

  function getUnitsInStockClass(units) {
    if (units < 5) {
      return "critical";
    } else if (units < 10) {
      return "warning";
    } else {
      return "ok";
    }
  }

  $(document).ready(function () {
    $("#grid-rowtemplate").kendoGrid({
      dataSource: {
        data: products,
        schema: {
          model: {
            id: "ID",
            fields: {
              ID: { type: "number" },
              ProductName: { },
              UnitsInStock: { type: "number" },
              Discontinued: { type: "boolean" }
            }
          }
        }
      },
      sortable: true,
      columns: [
        { field: "ProductName", title: "Product Name" },
        { field: "UnitsInStock", title:"Units In Stock", width: "120px" },
        { field: "Discontinued", width: "120px" }
      ],
      rowTemplate: rowTemplateString,
      altRowTemplate: altRowTemplateString
    });
  });
</script>
</code>```

Body:
I have a table. On each row I have a checkbox to "select it", two select boxes and an extra checkbox.

When I show my page, each row background color is the default one (white).

What I need is two things:

For each "Action" select box value, I want the row to change its color but only if the row checkbox is checked - Green for 'create' and Red for 'delete'

If the "Action" select box value is equal 'delete', I want the second select box and the extra checkbox to be disabled.

At the moment, I have the following code that changes the row background color depending only on the first select box choice, not taking into account the state of the checkbox.

How can I implement this? I don't know how to make these conditions work together.

Thanks.

NOTE: I'm using this code in Drupal but it's generic.
SECOND NOTE: This is used in drupal so I'm using a theme that has already css for the table. When I hover for example and for odd/even rows, some colors are already being applied. Don't know if this has impact on the code to implement what I need.

HTML:

<input type="checkbox" class="form-checkbox" title="Select all rows in this table">	Container				Action	Configuration	scripts

  <input class="containers_table form-checkbox" type="checkbox" id="edit-containers-table-vt-1" name="containers_table[VT_1]" value="VT_1">

	container 1	a	b	c

  Action for VT_1
 <select class="update-action form-select chosen-processed" name="action[VT_1]" style="display: none;"><option value="create">create</option><option value="delete">delete</option></select>

  create

    <input class="chosen-search-input" type="text" autocomplete="off">

  Card configuration for VT_1
 <select class="update-card_configuration form-select chosen-processed" name="card_configuration[VT_1]" style="display: none;"><option value="default">default</option><option value="HalSim_VT_1_OCC2">HalSim_VT_1_OCC2</option><option value="HalSim_VT_2_OCC2">HalSim_VT_2_OCC2</option><option value="HalSim_VT_3_OCC2">HalSim_VT_3_OCC2</option></select>

  default

    <input class="chosen-search-input" type="text" autocomplete="off">

  NE configuration for VT_1
 <input class="update-ne_configuration form-checkbox" type="checkbox" name="ne_configuration[VT_1]" value="1">

  <input class="containers_table form-checkbox" type="checkbox" id="edit-containers-table-vt-2" name="containers_table[VT_2]" value="VT_2">

	container 2	d	e	f

  Action for VT_2
 <select class="update-action form-select chosen-processed" name="action[VT_2]" style="display: none;"><option value="create">create</option><option value="delete">delete</option></select>

  create

    <input class="chosen-search-input" type="text" autocomplete="off">

  Card configuration for VT_2
 <select class="update-card_configuration form-select chosen-processed" name="card_configuration[VT_2]" style="display: none;"><option value="default">default</option><option value="HalSim_VT_1_OCC2">HalSim_VT_1_OCC2</option><option value="HalSim_VT_2_OCC2">HalSim_VT_2_OCC2</option><option value="HalSim_VT_3_OCC2">HalSim_VT_3_OCC2</option></select>

  default

    <input class="chosen-search-input" type="text" autocomplete="off">

  NE configuration for VT_2
 <input class="update-ne_configuration form-checkbox" type="checkbox" name="ne_configuration[VT_2]" value="1">

JQUERY:

(function($) {
    Drupal.behaviors.mymoduleColorRows = {
        attach: function(context) {

            // Bind change event to select
            $('.update-action').change(function(){
                setColors();
            });

            $('.edit-containers-table-groove-vt-1').change(function(){
                setColors2();
            });

            // Call function on first page load
            setColors();

            function setColors() {
                // Loop rows
                $('.containers_table tr').each(function(){
                    // Get color from value of select
                    var color = $(this).find('.update-action').val() == 'create' ? '#D7EAD9' : '#F5BE8B';
                    // Set color
                    $(this).find('td').css({'background-color': color});

                });
            }

            function setColors2() {
                // Loop rows
                $('.containers_table tr').each(function(){
                    // Get color from value of select
                    var color = '#F5BE8B';
                    // Set color
                    $(this).find('td').css({'background-color': color});

                });
            }
        }
    };

})(jQuery);

Body:
The usage of a row template is suitable only if you do not intend to use hierarchy, grouping, and editing columns. the Grid does not support the simultaneous application of these features and row templates. The approach directly adds template expressions to the rowTemplate and altRowTemplate definitions and determines which custom CSS classes will be applied to a given row or cell.

<style>
  .k-grid {
    width: 500px;
  }

  .discontinued {
    font-weight: bold;
    color: #f00;
  }
  .critical {
    background-color: #fdd;
  }

  .warning {
    background-color: #fda;
  }

  .ok {
    background-color: #ced;
  }

</style>

<div id="grid-rowtemplate"></div>
<script>
  // sample datasource
  var products = [
    { ID: 1, ProductName: "Foo", UnitsInStock: 9, Discontinued: false },
    { ID: 2, ProductName: "Bar", UnitsInStock: 16, Discontinued: false },
    { ID: 3, ProductName: "Baz", UnitsInStock: 3, Discontinued: true }
  ];

  var rowTemplateString = '<tr class="#: Discontinued ? "discontinued" : "" #" data-uid="#: uid #">' +
      '<td>#: ProductName #</td>' +
      '<td class="#: getUnitsInStockClass(UnitsInStock) #">#: UnitsInStock #</td>' +
      '<td>#: Discontinued #</td>' +
      '</tr>';

  var altRowTemplateString = rowTemplateString.replace('tr class="', 'tr class="k-alt ');

  function getUnitsInStockClass(units) {
    if (units < 5) {
      return "critical";
    } else if (units < 10) {
      return "warning";
    } else {
      return "ok";
    }
  }

  $(document).ready(function () {
    $("#grid-rowtemplate").kendoGrid({
      dataSource: {
        data: products,
        schema: {
          model: {
            id: "ID",
            fields: {
              ID: { type: "number" },
              ProductName: { },
              UnitsInStock: { type: "number" },
              Discontinued: { type: "boolean" }
            }
          }
        }
      },
      sortable: true,
      columns: [
        { field: "ProductName", title: "Product Name" },
        { field: "UnitsInStock", title:"Units In Stock", width: "120px" },
        { field: "Discontinued", width: "120px" }
      ],
      rowTemplate: rowTemplateString,
      altRowTemplate: altRowTemplateString
    });
  });
</script>


问:
How can I have a sticky footer with my CSS Grid layout?
I found this CodePen solution for a sticky footer in a CSS Grid layout, but it has two problems for me:

It is kinda ugly with min-height: 100% and height: 100%

It only works with two elements in the body (a div and a footer)

I need something that works with this HTML structure:

```<code><body>
    <nav>Some navigation buttons</nav>
    <main>The content</main>
    <footer>Copyrights and stuff</footer>
</body>
</code>```

I don't really want to pack the  and the  into a
, and I would love to do this in pure CSS.

// Not required!
// This is just to demo functionality.

$("#add").on("click", function() {
  $("
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
").appendTo(".content");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  height: 100%;
}

body {
  min-height: 100%;
  display: grid;
  grid-template-rows: 1fr auto;
}

.content {
  padding: 20px;
}

.footer {
  grid-row-start: 2;
  grid-row-end: 3;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font: 16px Sans-Serif;
}

h1 {
  margin: 0 0 20px 0;
}

p {
  margin: 0 0 20px 0;
}

.footer {
  background: #42A5F5;
  color: white;
  padding: 20px;
}</code>```

Sticky Footer with Grid

<button id="add">Add Content</button>

  Footer
```

答:
Here is a CSS Grid solution, but it's far better using a class for the target.

Using grid-areas this will be very straight forward:

html, body {
    margin: 0;
    height: 100%;
}
body {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr;
    grid-template-areas: "nav" "main" "footer";
    grid-template-rows: 100px 1fr 80px;
}
nav {
    background-color: #7E57C2;
    grid-area: nav;
}
main {
    background-color: #F8BBD0;
    grid-area: main;
}
footer {
    background-color: #7E57C2;
    grid-area: footer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <nav>Some navigation buttons</nav>
    <main>The content</main>
    <footer>Copyrights and stuff</footer>
</body></code>```

Body:
I found this CodePen solution for a sticky footer in a CSS Grid layout, but it has two problems for me:

It is kinda ugly with min-height: 100% and height: 100%

It only works with two elements in the body (a div and a footer)

I need something that works with this HTML structure:

    Some navigation buttons
    The content
    Copyrights and stuff

I don't really want to pack the  and the  into a
, and I would love to do this in pure CSS.

// Not required!
// This is just to demo functionality.

$("#add").on("click", function() {
  $("
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
").appendTo(".content");
});

html {
  height: 100%;
}

body {
  min-height: 100%;
  display: grid;
  grid-template-rows: 1fr auto;
}

.content {
  padding: 20px;
}

.footer {
  grid-row-start: 2;
  grid-row-end: 3;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font: 16px Sans-Serif;
}

h1 {
  margin: 0 0 20px 0;
}

p {
  margin: 0 0 20px 0;
}

.footer {
  background: #42A5F5;
  color: white;
  padding: 20px;
}

Sticky Footer with Grid

<button id="add">Add Content</button>

  Footer

Body:
Here is a CSS Grid solution, but it's far better using a class for the target.

Using grid-areas this will be very straight forward:

html, body {
    margin: 0;
    height: 100%;
}
body {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr;
    grid-template-areas: "nav" "main" "footer";
    grid-template-rows: 100px 1fr 80px;
}
nav {
    background-color: #7E57C2;
    grid-area: nav;
}
main {
    background-color: #F8BBD0;
    grid-area: main;
}
footer {
    background-color: #7E57C2;
    grid-area: footer;
}

<body>
    <nav>Some navigation buttons</nav>
    <main>The content</main>
    <footer>Copyrights and stuff</footer>
</body>

ContentLicense: CC BY-SA 4.0


问:
How to whereHas when use belongsToMany relation
I got a problem, When try to use whereHas in this case

Table users.

```<code>----------------
| id | name    |
----------------
| 1  | AAA     |
| 2  | BBB     |
| 3  | CCC     |
----------------
</code>```

Table subjects.

```<code>------------------
| id | title     |
------------------
| 1  | Subject 1 |
| 2  | Subject 2 |
------------------
</code>```

Table subject_user.

```<code>------------------------
| user_id | subject_id |
------------------------
| 1       | 1          |
| 2       | 1          |
| 1       | 2          |
| 3       | 2          |
------------------------
</code>```

in Subject Model

```<code>...

public function User()
{
    return $this->belongsToMany(User::class, 'subject_user');
}

...
</code>```

When I want to find subject by user_id with this query.

In this case Auth::id() == 1 and $request->user_id == 3

```<code>$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->whereIn('user_id', [Auth::id(), $request->user_id]);
})->get();
</code>```

With this query, I got subjects 1 and 2. That was a wrong result. That must got only subject 2.

Then I try this.

```<code>$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->where('user_id', Auth::id())->where('user_id', $request->user_id);
})->get();
</code>```

It would not get any subjects.

What query do I use in this case to get only subject 2.

答:
Why not doing it backwards? You already have the logged in user, so if you define the relationship in the User model you can do

```<code>$subjects = auth()->user()->subjects;
</code>```

Anyway, you don't need to check double the Auth::id()and $request->user_id. In fact, I'm not sure you can do this last one.

Edit after comments

```<code>$subjects = Subject::whereBetween(auth()->user()->id, $request->user_id)->get();
</code>```

You will need to change the order from the inputs, in case $request->user_id is less than auth()->user()->idor it wouldn't work.

Body:
I got a problem, When try to use whereHas in this case

Table users.

----------------
| id | name    |
----------------
| 1  | AAA     |
| 2  | BBB     |
| 3  | CCC     |
----------------

Table subjects.

------------------
| id | title     |
------------------
| 1  | Subject 1 |
| 2  | Subject 2 |
------------------

Table subject_user.

------------------------
| user_id | subject_id |
------------------------
| 1       | 1          |
| 2       | 1          |
| 1       | 2          |
| 3       | 2          |
------------------------

in Subject Model

...

public function User()
{
    return $this->belongsToMany(User::class, 'subject_user');
}

...

When I want to find subject by user_id with this query.

In this case Auth::id() == 1 and $request->user_id == 3

$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->whereIn('user_id', [Auth::id(), $request->user_id]);
})->get();

With this query, I got subjects 1 and 2. That was a wrong result. That must got only subject 2.

Then I try this.

$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->where('user_id', Auth::id())->where('user_id', $request->user_id);
})->get();

It would not get any subjects.

What query do I use in this case to get only subject 2.

Body:
Why not doing it backwards? You already have the logged in user, so if you define the relationship in the User model you can do

$subjects = auth()->user()->subjects;

Anyway, you don't need to check double the Auth::id()and $request->user_id. In fact, I'm not sure you can do this last one.

Edit after comments

$subjects = Subject::whereBetween(auth()->user()->id, $request->user_id)->get();

You will need to change the order from the inputs, in case $request->user_id is less than auth()->user()->idor it wouldn't work.


问:
How to check visibility of software keyboard in Android?
I need to do a very simple thing - find out if the software keyboard is shown. Is this possible in Android?</p>

答:
After understanding some of the issues with different resolutions, I decided to use a relative size. As I noticed the difference between visible and hidden states is about 30%. So I decided to replace 128 PX with 0.3.

And I added this class listener to notify of any change.

Here is my version

```<code>import android.app.*;
import android.graphics.*;
import android.view.*;

public class SoftKeyboardState {
  public static final int HIDDEN = 0, VISIBLE = 1;
  private OnKeyboardStateChangedListener listener;
  private View decorView;

  public SoftKeyboardState(Activity activity) {
    this.decorView = activity.findViewById(android.R.id.content);
    initKeyboardListener();
  }

  private void initKeyboardListener() {
    decorView.getViewTreeObserver().addOnGlobalLayoutListener(
      new ViewTreeObserver.OnGlobalLayoutListener(){
        private final Rect windowVisibleDisplayFrame = new Rect();
        private int lastVisibleDecorViewHeight;

        @Override
        public void onGlobalLayout() {
          decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
          final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();

          if (lastVisibleDecorViewHeight != 0) {
            if ((lastVisibleDecorViewHeight > visibleDecorViewHeight) && (lastVisibleDecorViewHeight / visibleDecorViewHeight >= 0.3f)) {
              // visible
              if (listener != null)listener.onKeyboardStateChanged(VISIBLE);
            } else if ((lastVisibleDecorViewHeight < visibleDecorViewHeight) && (visibleDecorViewHeight / lastVisibleDecorViewHeight >= 0.3f)) {
              // hidden
              if (listener != null)listener.onKeyboardStateChanged(HIDDEN);
            }
          }
          lastVisibleDecorViewHeight = visibleDecorViewHeight;
        }
      });
  }

  public void setOnKeyboardStateChangedListener(OnKeyboardStateChangedListener listener) {
    this.listener = listener;
  }

  public interface OnKeyboardStateChangedListener {
    public void onKeyboardStateChanged(int state);
  }
}
</code>```

Body:
After understanding some of the issues with different resolutions, I decided to use a relative size. As I noticed the difference between visible and hidden states is about 30%. So I decided to replace 128 PX with 0.3.

And I added this class listener to notify of any change.

Here is my version

import android.app.*;
import android.graphics.*;
import android.view.*;

public class SoftKeyboardState {
  public static final int HIDDEN = 0, VISIBLE = 1;
  private OnKeyboardStateChangedListener listener;
  private View decorView;

  public SoftKeyboardState(Activity activity) {
    this.decorView = activity.findViewById(android.R.id.content);
    initKeyboardListener();
  }

  private void initKeyboardListener() {
    decorView.getViewTreeObserver().addOnGlobalLayoutListener(
      new ViewTreeObserver.OnGlobalLayoutListener(){
        private final Rect windowVisibleDisplayFrame = new Rect();
        private int lastVisibleDecorViewHeight;

        @Override
        public void onGlobalLayout() {
          decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
          final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();

          if (lastVisibleDecorViewHeight != 0) {
            if ((lastVisibleDecorViewHeight > visibleDecorViewHeight) && (lastVisibleDecorViewHeight / visibleDecorViewHeight >= 0.3f)) {
              // visible
              if (listener != null)listener.onKeyboardStateChanged(VISIBLE);
            } else if ((lastVisibleDecorViewHeight < visibleDecorViewHeight) && (visibleDecorViewHeight / lastVisibleDecorViewHeight >= 0.3f)) {
              // hidden
              if (listener != null)listener.onKeyboardStateChanged(HIDDEN);
            }
          }
          lastVisibleDecorViewHeight = visibleDecorViewHeight;
        }
      });
  }

  public void setOnKeyboardStateChangedListener(OnKeyboardStateChangedListener listener) {
    this.listener = listener;
  }

  public interface OnKeyboardStateChangedListener {
    public void onKeyboardStateChanged(int state);
  }
}


问:
Undefined offset error, but offset is not undefined
I'm getting:

```<code>Notice: Undefined offset: 0
</code>```

in my code, however I can print_r the element I am trying to get and its clearly defined.

```<code>function get_members($entries_found) {
   $members = $entries_found[0]['member'];
   ...
}
</code>```

If I print_r($members) I get the expected output, however I'm still getting the Notice.

Any clues?

答:
I don't really know what happens with your $entries_found before accessing it from get_members

But i had the same problem. print_r and var_dump showed me, that the index exists but when i tried to access it i got the offset error

In my case i decoded a json string with json_decode without setting the assoc flag.

```<code>// Not working
$assocArray = json_decode('{"207":"sdf","210":"sdf"}');
echo $assocArray[207];

// working witht the assoc flag set
$assocArray = json_decode('{"207":"sdf","210":"sdf"}', true);
echo $assocArray[207];
</code>```

Got my solution from here: Undefined offset while accessing array element which exists

Body:
I'm getting:

Notice: Undefined offset: 0

in my code, however I can print_r the element I am trying to get and its clearly defined.

function get_members($entries_found) {
   $members = $entries_found[0]['member'];
   ...
}

If I print_r($members) I get the expected output, however I'm still getting the Notice.

Any clues?

Body:
I don't really know what happens with your $entries_found before accessing it from get_members

But i had the same problem. print_r and var_dump showed me, that the index exists but when i tried to access it i got the offset error

In my case i decoded a json string with json_decode without setting the assoc flag.

// Not working
$assocArray = json_decode('{"207":"sdf","210":"sdf"}');
echo $assocArray[207];

// working witht the assoc flag set
$assocArray = json_decode('{"207":"sdf","210":"sdf"}', true);
echo $assocArray[207];

Got my solution from here: Undefined offset while accessing array element which exists


问:
How to find missing elements in a list?
I have a target list as

```<code>target_list = ['one', 'two', 'three','four', 'five']
</code>```

And a output list as

```<code>output_list = ['two','three','four', 'five']
</code>```

The target_list is fixed, while the output_list will change depending on the output of some function. I want to find which element will be missed in the target_list based on the observation from output_list.

As in the above example, the element one is missing. I also want to count the number of missing element. Could you help me to do it in python?

答:
You are going to have to compare if each item of a list is contained in the other one; probably the most efficient iway to do this is to use sets() and extract their difference.

```<code>target_list = ["one", "two", "three", "four", "five"]
output_list = ['two','three','four', 'five']

print(set(target_list).difference(set(output_list)))
</code>```

output:

```<code>set(['one'])
</code>```

Title: How to find missing elements in a list?

Body:
I have a target list as

target_list = ['one', 'two', 'three','four', 'five']

And a output list as

output_list = ['two','three','four', 'five']

The target_list is fixed, while the output_list will change depending on the output of some function. I want to find which element will be missed in the target_list based on the observation from output_list.

As in the above example, the element one is missing. I also want to count the number of missing element. Could you help me to do it in python?

Body:
You are going to have to compare if each item of a list is contained in the other one; probably the most efficient iway to do this is to use sets() and extract their difference.

target_list = ["one", "two", "three", "four", "five"]
output_list = ['two','three','four', 'five']

print(set(target_list).difference(set(output_list)))

output:

set(['one'])


问:
Alternative SOAP implementation besides those offered by Microsoft
The most useful thing I like about SOAP vs REST is the WSDL.  It makes my life much easier when creating applications for the iPhone as my classes can be generated for me without me doing much monkey work.

However, I'm trying to find a suitable alternative to ASMX/WCF.  I predominantly use a Mac so Java, PHP or Mono solutions are mainly of interest to me.

I understand PHP has a SOAP service offering but it can't automatically generate a WSDL?  Are there any tools which can facilitate this?

答:
The latest versions have pretty good support for WSDL.

http://php.net/manual/en/book.soap.php

Here's a quick guide for it:

http://www.phpbuilder.com/columns/adam_delves20060606.php3


问:
In PHP, what purpose does (unset) have?
No, I'm not referring to the unset() language construct, but the (unset) type caster. From the PHP manual:

The casts allowed are:

(int), (integer) - cast to integer

(bool), (boolean) - cast to boolean

(float), (double), (real) - cast to float

(string) - cast to string

(array) - cast to array

(object) - cast to object

(unset) - cast to NULL (PHP 5)

URL: http://php.net/manual/en/language.types.type-juggling.php

Does anyone have any idea about this (or even used it in an actual project)?

答:
According to php.net:

Example #2 Using (unset) casting

(unset) casting is often confused with the unset() function. (unset)
  casting serves only as a NULL-type cast, for completeness. It does not
  alter the variable it's casting.

So, the way I read it is "All types are castable, null is a type so just for consistency we added a cast to null"

Title: In PHP, what purpose does (unset) have?


问:
How to force refresh on ObjectListView visible items?
I have an ObjectListView with a RowFormatter that highlights rows with a property above a user threshold.  When the user changes the threshold, I need the control to redraw the items, calling RowFormatter again, so the new threshold will be visually applied.  Invalidating the control doesn't seem to do anything.  There are 45000 objects in the control, so calling SetObjects again results in a 3-5 second delay.  Is there some way to call RefreshObjects() on just the visible objects?</p>

答:
Sounds like you may want to use the FastObjectListView instead. Its an implementation of the VirtualObjectListView and MUCH faster that the ObjectListView. I am not sure about the implementation details, but I think at its core it does exactly what you want - just handling/updating objects when required/visible.

There are some minor limitations:
 - it cannot use Tile view
 - it cannot show animated GIFs
 - it cannot show groups on XP

Other that that, it should be a drop-in-replacement if you do nothing especially fancy.


问:
Xcode storyboard device and simulator needs to be same
So i'm about 75% done with my iOS app and have began testing it, apparently the story board device needs to be the same as the simulated device for some UI components which are calculated based on device width.

So when I have set the story board view as iPhone 5s and ran the app in an iPhone X device the components that are taking its width based on the screen width is looking messed up. Why is it taking the story board screen width instead of the actual device width.

Will this happen when I run it in the actual device as well? Also when i'm going to release the app to the app store I would face the same problem.

答: If you used auto layout then this is happening due to leading space constraint, if you set leading space constraint of any UI element from its super view then width will increase according to device width, and if you want fix width on all device then remove leading width constraint and set width constraint fix. </p>


问:
Graphs in .NET CF
I'm looking for a decent free control, library, or tutorial that allow graphing on .NET CF... I'm currently using v2.0 but can probably upgrade to 3.5.

I will also want to be able to save the graph as an image.

答:
How much functionality do you actually need?

For a CF project I did in the past, we just used a few bitmaps as the background grid and drew the plots on there. It was pretty simple and low-tech, but I was surprised at how well it served us.

Title: Graphs in .NET CF


问:
Matching Id from a file
I have a inputId file as

```<code>input_abc,input_xyz,input_def
input_def,input_qwe
input_ghf,input_tgf,input_xyz
</code>```

I have other matcherFile as

```<code>input_xyz
input_def
</code>```

I want to filter all ids in matcherFile from inputId file, So output is

```<code>input_abc
input_qwe
input_ghf,input_tgf
</code>```

Wat I have written as

```<code>inputFileName="$1"
matchFile="$2"
outputFile="$3"

matchFileIds=$(cat $matchFile);
echo "$matchFileIds"

for IDS in $(cat $inputFileName);
do
    for i in $(echo $IDS | sed "s/,/ /g")
    do
    # here we get each id in inputfile separately,
    # I want to check if $i belongs id in  matcherFile
    echo "$i"

    done
done
</code>```

答:
What I understand from your post is, you want to delete entries from inputId file those are matching in matcherFile file.

for that I hope this code will help you.

```<code>inputFileName="$1"
matchFile="$2"
outputFile="$3"

cp $inputFileName ${inputFileName}_bkp

matchFileIds=$(cat $matchFile);
echo "$matchFileIds"

for IDS in $(cat $matchFile);
do
 echo $IDS
 sed -i "s/$IDS,//g" $inputFileName
 sed -i "s/,$IDS//g" $inputFileName

done

mv $inputFileName $outputFile
mv ${inputFileName}_bkp $inputFileName
</code>```

Title: Matching Id from a file

Body:
I have a inputId file as

input_abc,input_xyz,input_def
input_def,input_qwe
input_ghf,input_tgf,input_xyz

I have other matcherFile as

input_xyz
input_def

I want to filter all ids in matcherFile from inputId file, So output is

input_abc
input_qwe
input_ghf,input_tgf

Wat I have written as

inputFileName="$1"
matchFile="$2"
outputFile="$3"

matchFileIds=$(cat $matchFile);
echo "$matchFileIds"

for IDS in $(cat $inputFileName);
do
    for i in $(echo $IDS | sed "s/,/ /g")
    do
    # here we get each id in inputfile separately,
    # I want to check if $i belongs id in  matcherFile
    echo "$i"

    done
done

Body:
What I understand from your post is, you want to delete entries from inputId file those are matching in matcherFile file.

for that I hope this code will help you.

inputFileName="$1"
matchFile="$2"
outputFile="$3"

cp $inputFileName ${inputFileName}_bkp

matchFileIds=$(cat $matchFile);
echo "$matchFileIds"

for IDS in $(cat $matchFile);
do
 echo $IDS
 sed -i "s/$IDS,//g" $inputFileName
 sed -i "s/,$IDS//g" $inputFileName

done

mv $inputFileName $outputFile
mv ${inputFileName}_bkp $inputFileName


问:
Eclipse: Programmatically manipulate class
I just came across the issue that I had 10 (or so) Java classes for all of which I wanted to:

Add a formal parameter "String newparam" to their constructor

Add this as an actual parameter to the super() call to the super class constructor (thus, the result should be super(..., newparam)).

The reason is, obviously, that the common super class of those classes now has one constructor parameter more and all extending classes had to adapt.

I just can't believe that I need to do this by hand for all classes. Eclipse must have all required concepts like "constructor", "parameter" etc. in its internals. Any way to create a script for this?

I apologize if this is trivial/well known, I have to confess that I really don't know and appreciate any hints.

答:
Thank you for comments and answers. It currently seems that there is no (widely) known Eclipse-built-in approach to do what I want.
Which is, in short:

Add a new constructor parameter to the super class and, at the same time,
    create
    the same parameter in the constructors of all extending classes and pass this
    parameter through to the super class constructor

It should be noted, however, that the function

Add a new constructor parameter to the super class and add a default value for this parameter to all extending classes

Does work via refactor -> Change method signature... (thanks @Zircon).

A rather obvious solution in case you really have a lot of classes would be to write a script. A Java class was proposed by brahimfes which would have the advantage of not requiring a new language or a new working environment since my question is Java-specific. I also think that maybe a sed script could do the trick. I did, however, not try to, first, recognize the correct lines (constructor and super class constructor call, even though the second one is trivial) and, second, identify the correct position to add the parameters and, third, actually add them. Might work, I didn't try, I just have doubts about how long you would work on such a script until it works with no errors.

Now the solution I finally went for.
I realized that I always have the same key strokes (after I added the new parameter manually to the superclass constructor) in each subclass:

Select the constructor line.

Put the cursor at the and and backtrack 3 positions (parenthesis).

Add the formal parameter.

Go down one line.

Go to the end of this line (which always happens to be the super() call) and backtrack one position.

Add the actual parameter.

There are programs out there allowing to create makros of this kind, I got a trial version of one of them (I'm on a Mac) and did it this way.

Of course, this is still not actually a solution to my question and thus I won't mark this post as a solution. While I now have a makro that that relieves me of almost all typing, I still have to open each class in the editor manually, click the correct line and then fire the makro.
This program will still save me time in the future for similar requirements. But it is not what I hoped it to be, which would be some Eclipse-built-in scripting language with access to Java syntax elements for a more high-level access then regular expressions can offer.


问:
Column Store Indexes in SQL Server
Are column store indexes in SQL Server useful only when the query uses aggregate functions?

答:
Certainly no. Even if they were designed to be used in DWH ambient, they can be used in OLTP environment.

And even when used in DWH, aggregation is not a requirenment.

Columnstore indexes use a different storage format for data, storing
  compressed data on a per-column  rather than a per-row basis. This
  storage format benefits query processing in data warehousing,
  reporting,  and analytics environments where, although they typically
  read a very large number of rows, queries work  with just a subset of
  the columns from a table.

So the first benefit is data compression.

Compression in columnstore is table-wide, non page-wide (I mean dictionary applied) when you use PAGE data compression. So the compression ratio is the best. A table with clustered columnstore index defined uses less space compared to the same table with no columnstore but page compression enambed.

The second benefit is for queries that filter nothing(or almost nothing, needing (almost) all the rows) but need only some columns to be returned.

When the table is stored "per-row", even if you want only 10 columns of 100, and you want all the rows, the whole table will be read, because there is a need to read the whole row to get your 10 requested columns out of it. When you use "per-column" storage, only needed columns will be read.

Of course you can define an index with your 10 needed columns as included, but it will be additional space used and the overhead of maintenance of this index. Now imagin that your queries need these 10, and other 10, and another 2o of 100, so you need to create more indexes for these queries.

With one columnstore index you will be able to satisfy all these queries

Title: Column Store Indexes in SQL Server


答:
You can't say they are always useful for aggregate functions as it depends on which rows are included in the aggregation. If you are performing aggregation on all rows - they are useful. If you are selecting only small amount of the rows because of filtering, you can even get worse result than using traditional non-clustered index.

As it is written in MSDN, they can be used:

to achieve up to 10x query performance gains in your data warehouse
over traditional row-oriented storage

to get 10x data compression over the uncompressed data size (if you are interested in compression in should check the COLUMNSTORE_ARCHIVE option)

Also, depending on your SQL Server version (if SQL Server 2017 or later) you can check the Adaptive Query Processing as one of the conditions is to have such index:

You should look through the documentation and see what options you have depending on your SQL Server version and to test for sure how this index is going to affect the performance, because it is very possible to make the things worse.

It's good that in every article Microsoft have mention the scenarios when the types of column store indexes can be used for good.

Title: Column Store Indexes in SQL Server

Body: Are column store indexes in SQL Server useful only when the query uses aggregate functions?


问:
Class org.springframework.web.jsf.el.SpringBeanFacesELResolver must extend the type javax.el.ELResolver
I am trying to integrate Spring into a JSF application.

In faces-config.xml, I have included this:

```<code><application>
  <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
  <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
</application>
</code>```

but it shows a weird warning which I can't get rid of:

```<code>Class org.springframework.web.jsf.el.SpringBeanFacesELResolver must extend the type javax.el.ELResolver
</code>```

Any ideas?

答:
To solve this type of problem you should extend project with javax prefix because Class ELResolver is an abstract class under javax.el package.

Here is code:

```<code>    <application>
      <javax.el-resolver>
        org.springframework.web.jsf.el.SpringBeanFacesELResolver
      </javax.el-resolver>
    </application>
</code>```

More information about ELResolver class you can get by link.

Body:
I am trying to integrate Spring into a JSF application.

In faces-config.xml, I have included this:

<application>
  <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
  <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
</application>

but it shows a weird warning which I can't get rid of:

Class org.springframework.web.jsf.el.SpringBeanFacesELResolver must extend the type javax.el.ELResolver

Any ideas?

Body:
To solve this type of problem you should extend project with javax prefix because Class ELResolver is an abstract class under javax.el package.

Here is code:

    <application>
      <javax.el-resolver>
        org.springframework.web.jsf.el.SpringBeanFacesELResolver
      </javax.el-resolver>
    </application>

More information about ELResolver class you can get by link.