问:
Nested for loop not working in makefile
I am trying to use a nested for loop for searching and copying some files inside the recipe of one of the targets inside a makefile:

```<code>DIR = $(DIR_A) $(DIR_B)

install:
      for dirs in $(DIR); do \
        for file in $(shell find $(dirs) -type f -and -not -path "*/.svn*" | sed -e "s|$(dirs)||"); do \
        folder=$${file%/*}; \
          $(INSTALL) -d $(DEST_DIR)$$folder/log; \
          $(INSTALL) $(dirs)/$$file $(DEST_DIR)$$folder/log; \
        done \
      done
</code>```

However $(dirs) variable always evaluates to empty inside the second for loop and the current working directory gets passed to "find" instead of first directory path from $(DIR).

Can someone please suggest if I am missing something ?

Thanks.

答:
You have made several errors, and you will find it almost impossible to solve them as l;ong as you insist on trying to solve them all at once.

Let's try this in stages. Suppose your DIR_A and DIR_B are north and south. On the command line, if you try this:

```<code>for dirs in north south; do echo $dirs; done
</code>```

you will get the correct output:

```<code>north
south
</code>```

If you try it as a makefile rule:

```<code>install:
    for dirs in $(DIR); do echo $$dirs; done
</code>```

again, it works correctly.

If you try your makefile recipe:

```<code>install:
    for dirs in $(DIR); do \ for file in $(shell ls $$dirs); do \ echo "file is $$file"; \ done \ done
</code>```

it fails, because Make expands the $(shell ...) command before passing the entire for command to the shell, when dirs has not yet been assigned a value. One way to construct a sensible shell command is to use backticks:

```<code>for dirs in north south; do for file in `ls $dirs`; do  echo "file is $file";  done  done
</code>```

This works on the command line. A makefile rule built around it:

```<code>install:
    for dirs in $(DIR); do for file in `ls $$dirs`; do  echo "file is $$file";  done  done
</code>```

also works.

That should be enough to allow you to rewrite your makefile.

Title: Nested for loop not working in makefile

Body:
I am trying to use a nested for loop for searching and copying some files inside the recipe of one of the targets inside a makefile:

DIR = $(DIR_A) $(DIR_B)

install:
      for dirs in $(DIR); do \
        for file in $(shell find $(dirs) -type f -and -not -path "*/.svn*" | sed -e "s|$(dirs)||"); do \
        folder=$${file%/*}; \
          $(INSTALL) -d $(DEST_DIR)$$folder/log; \
          $(INSTALL) $(dirs)/$$file $(DEST_DIR)$$folder/log; \
        done \
      done

However $(dirs) variable always evaluates to empty inside the second for loop and the current working directory gets passed to "find" instead of first directory path from $(DIR).

Can someone please suggest if I am missing something ?

Thanks.

Body:
You have made several errors, and you will find it almost impossible to solve them as l;ong as you insist on trying to solve them all at once.

Let's try this in stages. Suppose your DIR_A and DIR_B are north and south. On the command line, if you try this:

for dirs in north south; do echo $dirs; done

you will get the correct output:

north
south

If you try it as a makefile rule:

install:
    for dirs in $(DIR); do echo $$dirs; done

again, it works correctly.

If you try your makefile recipe:

install:
    for dirs in $(DIR); do \ for file in $(shell ls $$dirs); do \ echo "file is $$file"; \ done \ done

it fails, because Make expands the $(shell ...) command before passing the entire for command to the shell, when dirs has not yet been assigned a value. One way to construct a sensible shell command is to use backticks:

for dirs in north south; do for file in `ls $dirs`; do  echo "file is $file";  done  done

This works on the command line. A makefile rule built around it:

install:
    for dirs in $(DIR); do for file in `ls $$dirs`; do  echo "file is $$file";  done  done

also works.

That should be enough to allow you to rewrite your makefile.


来源: stackexchange

问:
Laravel between dates
I want to check the validity of promo code by comparing date in eloquent but dont know why its not working

```<code>$promoCode = self::where('code', $code)
        ->where('start_date', '>=', Carbon::now()->toDateString())
        ->where('end_date', '<=', Carbon::now()->toDateString())
        ->first();
</code>```

If i comment out 2nd and 3rd line then it works fine. MySQL column type is date. I also tried whereDate method and thats not working too

答:
Shouldn't the start_date be before now. If so now should be between. Try:</p>

```<code>$promoCode = self::where('code', $code)
    ->where('start_date', '<=', Carbon::now()->toDateString())
    ->where('end_date', '<=', Carbon::now()->toDateString())
    ->first();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel between dates

Body:
I want to check the validity of promo code by comparing date in eloquent but dont know why its not working

$promoCode = self::where('code', $code)
        ->where('start_date', '>=', Carbon::now()->toDateString())
        ->where('end_date', '<=', Carbon::now()->toDateString())
        ->first();

If i comment out 2nd and 3rd line then it works fine. MySQL column type is date. I also tried whereDate method and thats not working too

Body:
Shouldn't the start_date be before now. If so now should be between. Try:

$promoCode = self::where('code', $code)
    ->where('start_date', '<=', Carbon::now()->toDateString())
    ->where('end_date', '<=', Carbon::now()->toDateString())
    ->first();


问:
MySQL query to print data from two tables

I need help with writing a MySQL query to print the respective department names and number of Employee for all departments in the Department table.

Expected output:

```<code>Executive 2
Technical 2
Production 1
</code>```

答:
```<code>SELECT a.name as department_name, count(b.id) as num_of_employees
FROM department a INNER JOIN employee b ON a.dept_id = b.dept_id
GROUP BY a.dept_id
</code>```

Body:
I need help with writing a MySQL query to print the respective department names and number of Employee for all departments in the Department table.

Expected output:

Executive 2
Technical 2
Production 1


问:
Mount a local directory as volume in container, from the Dockerfile
I know how local directories can be mounted as volumes with the -v option in docker run, i.e.

```<code>docker run -v /local/some_folder:/container/some_folder image_name
</code>```

However, I want to be able to specify the above instruction (to mount the local /local/some_folder as /container/some_folder in the container within the Dockerfile.

I've tried using VOLUME /local/some_folder /container/some_folder in the Dockerfile, but that didn't seem to work: I am then able to access /container/some_folder from within the container using docker exec -t container sh, but the write changes of container to /container/some_folder are not reflected in /local/some_folder during container runtime AND after docker stop container.

答: You do not have access to control things like host volume mounts inside the Dockerfile or image build process. Allowing this would allow malicious image creators to make an image that mounts directories on the host without the permission of the admin of that host. A security breach that allowed a popular base image to mount the filesystem could be used to send private data off-site and inject login credentials on countless machines. The only way to mount a volume is at run time at the explicit request of the admin running the container, and to the directory they provide.</p>

Body:
I know how local directories can be mounted as volumes with the -v option in docker run, i.e.

docker run -v /local/some_folder:/container/some_folder image_name

However, I want to be able to specify the above instruction (to mount the local /local/some_folder as /container/some_folder in the container within the Dockerfile.

I've tried using VOLUME /local/some_folder /container/some_folder in the Dockerfile, but that didn't seem to work: I am then able to access /container/some_folder from within the container using docker exec -t container sh, but the write changes of container to /container/some_folder are not reflected in /local/some_folder during container runtime AND after docker stop container.


问:
Typescript: Type 'Audience' is not assignable to type 'boolean'
The problem:

```<code>.filter(audience => audience)
</code>```

I'm using VSCode and I know why it's throwing this error as it's expecting a boolean and I'm returning an object, but this is valid Javascript as I'm returning a truthy value and so a reference will be coerced to true. Can I change something in the configuration to make it work? I already made it work with:

```<code>.filter(audience => Boolean(audience))
</code>```

But I'd rather avoid that.

答:
There are a few different ways you can do a test. As TypeScript helps you to write better code, it is picky on what it accepts (This is a good thing). Here are a few different ways to tell something that an object is a boolean.

We can cast it as an any (boolean might work too)

```<code>.filter(audience => <any>audience)
</code>```

And as Frank Mentioned we can use double !

```<code>.filter(audience => !!audience)
</code>```

Body:
The problem:

.filter(audience => audience)

I'm using VSCode and I know why it's throwing this error as it's expecting a boolean and I'm returning an object, but this is valid Javascript as I'm returning a truthy value and so a reference will be coerced to true. Can I change something in the configuration to make it work? I already made it work with:

.filter(audience => Boolean(audience))

But I'd rather avoid that.

Body:
There are a few different ways you can do a test. As TypeScript helps you to write better code, it is picky on what it accepts (This is a good thing). Here are a few different ways to tell something that an object is a boolean.

We can cast it as an any (boolean might work too)

.filter(audience => <any>audience)

And as Frank Mentioned we can use double !

.filter(audience => !!audience)


问:
ElasticSearch - Malformed Query (RoR)
I'm trying to set up an existing project using elasticsearch and ruby-on-rails. I can get the project up and running however elasticsearch queries return various error message for me and none of my colleagues:

```<code>[400] {"error":{"root_cause":[{"type":"parsing_exception","reason":"[and] query malformed, no start_object after query name","line":1,"col":896}],"type":"parsing_exception","reason":"[and] query malformed, no start_object after query name","line":1,"col":896},"status":400}
</code>```

This obviously leads me to believe it's something to do with my setup. I've installed the same version of them (2.4), however even the setup command that was supplied with the project:

```<code>rake environment elasticsearch:import:all DIR=app/models FORCE=y
</code>```

gives me a timeout error. I've checked and the service is running. Any help as to what could be wrong with my set up would be greatly appreciated as I'm at a dead end for 2 days on this.

Thanks in advance.

EDIT: I don't think the issue is with the query itself as this works for my colleagues however it is as follows:

```<code>{: date_range => {: from => Mon,
    01 Aug 2016 00: 00: 00 UTC + 00: 00,
    : to => Mon,
    31 Jul 2017 00: 00: 00 UTC + 00: 00
  }, : activities_only => nil
}, @pupils = [# < Pupil id: 1042, first_name: "Mark", last_name: "Mekhaiel", date_of_birth: "2017-03-19", level: 0, group_id: 95, created_at: "2017-07-31 08:59:59", updated_at: "2017-07-31 09:48:27", username: "m.mekhaiel1", picture: 0, color: 0, archived: false, sub_group_id: nil, score: 20, deleted_at: nil > ], @search = # < PupilCreditSearch: 0x007fc961801308 @interval = : month, @page = 1, @per = 25, @pupil_id = [1042], @date_range = {: from => Mon,
  01 Aug 2016 00: 00: 00 UTC + 00: 00,
  : to => Mon,
  31 Jul 2017 00: 00: 00 UTC + 00: 00
}, @queries = [# < Search::Query: 0x007fc964791bb8 @query = nil, @fields = [], @type = : multi_match, @options = {: fields => [],
  : type => : cross_fields
} > ], @filters = [# < Search::Filter: 0x007fc964756db0 @name = : pupil_id, @value = [1042], @type = : terms, @options = {} > ], @aggregations = {: years_created => # < Search::Aggregation: 0x007fc9647a32f0 @type = : date_histogram,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_histogram,
    : params => {: interval => : year
    }
  } > ,
  : months_created => # < Search::Aggregation: 0x007fc9647a30c0 @type = : date_histogram,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_histogram,
    : params => {: interval => : month
    }
  } > ,
  : date_ranges => # < Search::Aggregation: 0x007fc9647a2800 @type = : date_range,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_range,
    : params => {: keyed => true,
      : ranges => [{: from => "now/w",
        : to => "now+1w/w",
        : key => : this_week
      }, {: from => "now/M",
        : to => "now+1M/M",
        : key => : this_month
      }, {: from => "now-1w/w",
        : to => "now-2w/w",
        : key => : last_week
      }, {: from => "now-1M/M",
        : to => "now-2M/M",
        : key => : last_month
      }, {: from => "2016-09-01",
        : to => "2017-08-31",
        : key => : academic_year
      }]
    }
  } > ,
  : groups => # < Search::Aggregation: 0x007fc9647a2260 @type = : terms,
  @field = : pupil_id,
  @options = {: aggs => {: all_dates => # < Search::Aggregation: 0x007fc9647a22d8 @type = : date_histogram,
      @field = : created_at,
      @options = {: params => {: interval => : month
        },
        : aggs => {: total_points => # < Search::Aggregation: 0x007fc9647a2440 @type = : sum,
          @field = : points,
          @options = {} > ,
          : running_total => # < Search::Aggregation: 0x007fc9647a2350 @type = : cumulative_sum,
          @field = nil,
          @options = {: params => {: buckets_path => "total_points"
            }
          } >
        }
      } >
    }
  } > ,
  : options => # < Search::Aggregation: 0x007fc9647a1518 @type = : global,
  @field = nil,
  @options = {: aggs => {: filtered => # < Search::Aggregation: 0x007fc9647a1590 @type = : filter,
      @field = nil,
      @options = {: params => {: and => [{: range => {: created_at => {: gte => Mon,
                01 Aug 2016 00: 00: 00 UTC + 00: 00,
                : lt => Mon,
                31 Jul 2017 00: 00: 00 UTC + 00: 00
              }
            }
          }, {: terms => {: pupil_id => [1042]
            }
          }]
        },
        : aggs => {: categories => # < Search::Aggregation: 0x007fc9647a1b80 @type = : terms,
          @field = "category",
          @options = {: ignore => true
          } > ,
          : topic_ids => # < Search::Aggregation: 0x007fc9647a19a0 @type = : terms,
          @field = "topic_id",
          @options = {: ignore => true
          } > ,
          : learning_objective_ids => # < Search::Aggregation: 0x007fc9647a17c0 @type = : terms,
          @field = "learning_objective_id",
          @options = {: ignore => true
          } > ,
          : completed_activities => # < Search::Aggregation: 0x007fc9647a1608 @type = : terms,
          @field = : pupil_id,
          @options = {: aggs => {: activities => # < Search::Aggregation: 0x007fc9647a1680 @type = : filter,
              @field = nil,
              @options = {: params => {: and => [{: terms => {: category => [0, 1, 2, 3]
                    }
                  }]
                }
              } >
            }
          } >
        }
      } >
    }
  } >
}, @request = # < Search::Request: 0x007fc964753548 @params = {: query => {: bool => {: must => [{: match_all => {}
      }],
      : filter => [{: terms => {: pupil_id => [1042]
        }
      }]
    }
  },
  : aggs => {: years_created => {: date_histogram => {: field => : created_at,
        : interval => : year
      }
    },
    : months_created => {: date_histogram => {: field => : created_at,
        : interval => : month
      }
    },
    : date_ranges => {: date_range => {: field => : created_at,
        : keyed => true,
        : ranges => [{: from => "now/w",
          : to => "now+1w/w",
          : key => : this_week
        }, {: from => "now/M",
          : to => "now+1M/M",
          : key => : this_month
        }, {: from => "now-1w/w",
          : to => "now-2w/w",
          : key => : last_week
        }, {: from => "now-1M/M",
          : to => "now-2M/M",
          : key => : last_month
        }, {: from => "2016-09-01",
          : to => "2017-08-31",
          : key => : academic_year
        }]
      }
    },
    : groups => {: terms => {: field => : pupil_id
      },
      : aggs => {: all_dates => {: date_histogram => {: field => : created_at,
            : interval => : month
          },
          : aggs => {: total_points => {: sum => {: field => : points
              }
            },
            : running_total => {: cumulative_sum => {: buckets_path => "total_points"
              }
            }
          }
        }
      }
    },
    : options => {: global => {},
      : aggs => {: filtered => {: filter => {: and => [{: range => {: created_at => {: gte => Mon,
                  01 Aug 2016 00: 00: 00 UTC + 00: 00,
                  : lt => Mon,
                  31 Jul 2017 00: 00: 00 UTC + 00: 00
                }
              }
            }, {: terms => {: pupil_id => [1042]
              }
            }]
          },
          : aggs => {: categories => {: terms => {: field => "category"
              }
            },
            : topic_ids => {: terms => {: field => "topic_id"
              }
            },
            : learning_objective_ids => {: terms => {: field => "learning_objective_id"
              }
            },
            : completed_activities => {: terms => {: field => : pupil_id
              },
              : aggs => {: activities => {: filter => {: and => [{: terms => {: category => [0, 1, 2, 3]
                      }
                    }]
                  }
                }
              }
            }
          }
        }
      }
    }
  }
} >> , @options = # < ReportOptions: 0x007fc96b663258 @search = # < PupilCreditSearch: 0x007fc961801308 @interval = : month, @page = 1, @per = 25, @pupil_id = [1042], @date_range = {: from => Mon,
  01 Aug 2016 00: 00: 00 UTC + 00: 00,
  : to => Mon,
  31 Jul 2017 00: 00: 00 UTC + 00: 00
}, @queries = [# < Search::Query: 0x007fc964791bb8 @query = nil, @fields = [], @type = : multi_match, @options = {: fields => [],
  : type => : cross_fields
} > ], @filters = [# < Search::Filter: 0x007fc964756db0 @name = : pupil_id, @value = [1042], @type = : terms, @options = {} > ], @aggregations = {: years_created => # < Search::Aggregation: 0x007fc9647a32f0 @type = : date_histogram,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_histogram,
    : params => {: interval => : year
    }
  } > ,
  : months_created => # < Search::Aggregation: 0x007fc9647a30c0 @type = : date_histogram,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_histogram,
    : params => {: interval => : month
    }
  } > ,
  : date_ranges => # < Search::Aggregation: 0x007fc9647a2800 @type = : date_range,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_range,
    : params => {: keyed => true,
      : ranges => [{: from => "now/w",
        : to => "now+1w/w",
        : key => : this_week
      }, {: from => "now/M",
        : to => "now+1M/M",
        : key => : this_month
      }, {: from => "now-1w/w",
        : to => "now-2w/w",
        : key => : last_week
      }, {: from => "now-1M/M",
        : to => "now-2M/M",
        : key => : last_month
      }, {: from => "2016-09-01",
        : to => "2017-08-31",
        : key => : academic_year
      }]
    }
  } > ,
  : groups => # < Search::Aggregation: 0x007fc9647a2260 @type = : terms,
  @field = : pupil_id,
  @options = {: aggs => {: all_dates => # < Search::Aggregation: 0x007fc9647a22d8 @type = : date_histogram,
      @field = : created_at,
      @options = {: params => {: interval => : month
        },
        : aggs => {: total_points => # < Search::Aggregation: 0x007fc9647a2440 @type = : sum,
          @field = : points,
          @options = {} > ,
          : running_total => # < Search::Aggregation: 0x007fc9647a2350 @type = : cumulative_sum,
          @field = nil,
          @options = {: params => {: buckets_path => "total_points"
            }
          } >
        }
      } >
    }
  } > ,
  : options => # < Search::Aggregation: 0x007fc9647a1518 @type = : global,
  @field = nil,
  @options = {: aggs => {: filtered => # < Search::Aggregation: 0x007fc9647a1590 @type = : filter,
      @field = nil,
      @options = {: params => {: and => [{: range => {: created_at => {: gte => Mon,
                01 Aug 2016 00: 00: 00 UTC + 00: 00,
                : lt => Mon,
                31 Jul 2017 00: 00: 00 UTC + 00: 00
              }
            }
          }, {: terms => {: pupil_id => [1042]
            }
          }]
        },
        : aggs => {: categories => # < Search::Aggregation: 0x007fc9647a1b80 @type = : terms,
          @field = "category",
          @options = {: ignore => true
          } > ,
          : topic_ids => # < Search::Aggregation: 0x007fc9647a19a0 @type = : terms,
          @field = "topic_id",
          @options = {: ignore => true
          } > ,
          : learning_objective_ids => # < Search::Aggregation: 0x007fc9647a17c0 @type = : terms,
          @field = "learning_objective_id",
          @options = {: ignore => true
          } > ,
          : completed_activities => # < Search::Aggregation: 0x007fc9647a1608 @type = : terms,
          @field = : pupil_id,
          @options = {: aggs => {: activities => # < Search::Aggregation: 0x007fc9647a1680 @type = : filter,
              @field = nil,
              @options = {: params => {: and => [{: terms => {: category => [0, 1, 2, 3]
                    }
                  }]
                }
              } >
            }
          } >
        }
      } >
    }
  } >
}, @request = # < Search::Request: 0x007fc964753548 @params = {: query => {: bool => {: must => [{: match_all => {}
      }],
      : filter => [{: terms => {: pupil_id => [1042]
        }
      }]
    }
  },
  : aggs => {: years_created => {: date_histogram => {: field => : created_at,
        : interval => : year
      }
    },
    : months_created => {: date_histogram => {: field => : created_at,
        : interval => : month
      }
    },
    : date_ranges => {: date_range => {: field => : created_at,
        : keyed => true,
        : ranges => [{: from => "now/w",
          : to => "now+1w/w",
          : key => : this_week
        }, {: from => "now/M",
          : to => "now+1M/M",
          : key => : this_month
        }, {: from => "now-1w/w",
          : to => "now-2w/w",
          : key => : last_week
        }, {: from => "now-1M/M",
          : to => "now-2M/M",
          : key => : last_month
        }, {: from => "2016-09-01",
          : to => "2017-08-31",
          : key => : academic_year
        }]
      }
    },
    : groups => {: terms => {: field => : pupil_id
      },
      : aggs => {: all_dates => {: date_histogram => {: field => : created_at,
            : interval => : month
          },
          : aggs => {: total_points => {: sum => {: field => : points
              }
            },
            : running_total => {: cumulative_sum => {: buckets_path => "total_points"
              }
            }
          }
        }
      }
    },
    : options => {: global => {},
      : aggs => {: filtered => {: filter => {: and => [{: range => {: created_at => {: gte => Mon,
                  01 Aug 2016 00: 00: 00 UTC + 00: 00,
                  : lt => Mon,
                  31 Jul 2017 00: 00: 00 UTC + 00: 00
                }
              }
            }, {: terms => {: pupil_id => [1042]
              }
            }]
          },
          : aggs => {: categories => {: terms => {: field => "category"
              }
            },
            : topic_ids => {: terms => {: field => "topic_id"
              }
            },
            : learning_objective_ids => {: terms => {: field => "learning_objective_id"
              }
            },
            : completed_activities => {: terms => {: field => : pupil_id
              },
              : aggs => {: activities => {: filter => {: and => [{: terms => {: category => [0, 1, 2, 3]
                      }
                    }]
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

答:
The problem is with one of the aggregations, namely:

:filter => { :and => [...] }

...which leads me to conclusion that you actually may be running elasticsearch 5 and not 2.4, on your machine, because this syntax got dropped in version 5 in favour of:

:filter => { :bool => { :must: [...] } }

Verify the elasticsearch version with curl localhost:9200 (or the actual host/port your app is connecting to).

Title: ElasticSearch - Malformed Query (RoR)

Body:
I'm trying to set up an existing project using elasticsearch and ruby-on-rails. I can get the project up and running however elasticsearch queries return various error message for me and none of my colleagues:

[400] {"error":{"root_cause":[{"type":"parsing_exception","reason":"[and] query malformed, no start_object after query name","line":1,"col":896}],"type":"parsing_exception","reason":"[and] query malformed, no start_object after query name","line":1,"col":896},"status":400}

This obviously leads me to believe it's something to do with my setup. I've installed the same version of them (2.4), however even the setup command that was supplied with the project:

rake environment elasticsearch:import:all DIR=app/models FORCE=y

gives me a timeout error. I've checked and the service is running. Any help as to what could be wrong with my set up would be greatly appreciated as I'm at a dead end for 2 days on this.

Thanks in advance.

EDIT: I don't think the issue is with the query itself as this works for my colleagues however it is as follows:

{: date_range => {: from => Mon,
    01 Aug 2016 00: 00: 00 UTC + 00: 00,
    : to => Mon,
    31 Jul 2017 00: 00: 00 UTC + 00: 00
  }, : activities_only => nil
}, @pupils = [# < Pupil id: 1042, first_name: "Mark", last_name: "Mekhaiel", date_of_birth: "2017-03-19", level: 0, group_id: 95, created_at: "2017-07-31 08:59:59", updated_at: "2017-07-31 09:48:27", username: "m.mekhaiel1", picture: 0, color: 0, archived: false, sub_group_id: nil, score: 20, deleted_at: nil > ], @search = # < PupilCreditSearch: 0x007fc961801308 @interval = : month, @page = 1, @per = 25, @pupil_id = [1042], @date_range = {: from => Mon,
  01 Aug 2016 00: 00: 00 UTC + 00: 00,
  : to => Mon,
  31 Jul 2017 00: 00: 00 UTC + 00: 00
}, @queries = [# < Search::Query: 0x007fc964791bb8 @query = nil, @fields = [], @type = : multi_match, @options = {: fields => [],
  : type => : cross_fields
} > ], @filters = [# < Search::Filter: 0x007fc964756db0 @name = : pupil_id, @value = [1042], @type = : terms, @options = {} > ], @aggregations = {: years_created => # < Search::Aggregation: 0x007fc9647a32f0 @type = : date_histogram,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_histogram,
    : params => {: interval => : year
    }
  } > ,
  : months_created => # < Search::Aggregation: 0x007fc9647a30c0 @type = : date_histogram,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_histogram,
    : params => {: interval => : month
    }
  } > ,
  : date_ranges => # < Search::Aggregation: 0x007fc9647a2800 @type = : date_range,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_range,
    : params => {: keyed => true,
      : ranges => [{: from => "now/w",
        : to => "now+1w/w",
        : key => : this_week
      }, {: from => "now/M",
        : to => "now+1M/M",
        : key => : this_month
      }, {: from => "now-1w/w",
        : to => "now-2w/w",
        : key => : last_week
      }, {: from => "now-1M/M",
        : to => "now-2M/M",
        : key => : last_month
      }, {: from => "2016-09-01",
        : to => "2017-08-31",
        : key => : academic_year
      }]
    }
  } > ,
  : groups => # < Search::Aggregation: 0x007fc9647a2260 @type = : terms,
  @field = : pupil_id,
  @options = {: aggs => {: all_dates => # < Search::Aggregation: 0x007fc9647a22d8 @type = : date_histogram,
      @field = : created_at,
      @options = {: params => {: interval => : month
        },
        : aggs => {: total_points => # < Search::Aggregation: 0x007fc9647a2440 @type = : sum,
          @field = : points,
          @options = {} > ,
          : running_total => # < Search::Aggregation: 0x007fc9647a2350 @type = : cumulative_sum,
          @field = nil,
          @options = {: params => {: buckets_path => "total_points"
            }
          } >
        }
      } >
    }
  } > ,
  : options => # < Search::Aggregation: 0x007fc9647a1518 @type = : global,
  @field = nil,
  @options = {: aggs => {: filtered => # < Search::Aggregation: 0x007fc9647a1590 @type = : filter,
      @field = nil,
      @options = {: params => {: and => [{: range => {: created_at => {: gte => Mon,
                01 Aug 2016 00: 00: 00 UTC + 00: 00,
                : lt => Mon,
                31 Jul 2017 00: 00: 00 UTC + 00: 00
              }
            }
          }, {: terms => {: pupil_id => [1042]
            }
          }]
        },
        : aggs => {: categories => # < Search::Aggregation: 0x007fc9647a1b80 @type = : terms,
          @field = "category",
          @options = {: ignore => true
          } > ,
          : topic_ids => # < Search::Aggregation: 0x007fc9647a19a0 @type = : terms,
          @field = "topic_id",
          @options = {: ignore => true
          } > ,
          : learning_objective_ids => # < Search::Aggregation: 0x007fc9647a17c0 @type = : terms,
          @field = "learning_objective_id",
          @options = {: ignore => true
          } > ,
          : completed_activities => # < Search::Aggregation: 0x007fc9647a1608 @type = : terms,
          @field = : pupil_id,
          @options = {: aggs => {: activities => # < Search::Aggregation: 0x007fc9647a1680 @type = : filter,
              @field = nil,
              @options = {: params => {: and => [{: terms => {: category => [0, 1, 2, 3]
                    }
                  }]
                }
              } >
            }
          } >
        }
      } >
    }
  } >
}, @request = # < Search::Request: 0x007fc964753548 @params = {: query => {: bool => {: must => [{: match_all => {}
      }],
      : filter => [{: terms => {: pupil_id => [1042]
        }
      }]
    }
  },
  : aggs => {: years_created => {: date_histogram => {: field => : created_at,
        : interval => : year
      }
    },
    : months_created => {: date_histogram => {: field => : created_at,
        : interval => : month
      }
    },
    : date_ranges => {: date_range => {: field => : created_at,
        : keyed => true,
        : ranges => [{: from => "now/w",
          : to => "now+1w/w",
          : key => : this_week
        }, {: from => "now/M",
          : to => "now+1M/M",
          : key => : this_month
        }, {: from => "now-1w/w",
          : to => "now-2w/w",
          : key => : last_week
        }, {: from => "now-1M/M",
          : to => "now-2M/M",
          : key => : last_month
        }, {: from => "2016-09-01",
          : to => "2017-08-31",
          : key => : academic_year
        }]
      }
    },
    : groups => {: terms => {: field => : pupil_id
      },
      : aggs => {: all_dates => {: date_histogram => {: field => : created_at,
            : interval => : month
          },
          : aggs => {: total_points => {: sum => {: field => : points
              }
            },
            : running_total => {: cumulative_sum => {: buckets_path => "total_points"
              }
            }
          }
        }
      }
    },
    : options => {: global => {},
      : aggs => {: filtered => {: filter => {: and => [{: range => {: created_at => {: gte => Mon,
                  01 Aug 2016 00: 00: 00 UTC + 00: 00,
                  : lt => Mon,
                  31 Jul 2017 00: 00: 00 UTC + 00: 00
                }
              }
            }, {: terms => {: pupil_id => [1042]
              }
            }]
          },
          : aggs => {: categories => {: terms => {: field => "category"
              }
            },
            : topic_ids => {: terms => {: field => "topic_id"
              }
            },
            : learning_objective_ids => {: terms => {: field => "learning_objective_id"
              }
            },
            : completed_activities => {: terms => {: field => : pupil_id
              },
              : aggs => {: activities => {: filter => {: and => [{: terms => {: category => [0, 1, 2, 3]
                      }
                    }]
                  }
                }
              }
            }
          }
        }
      }
    }
  }
} >> , @options = # < ReportOptions: 0x007fc96b663258 @search = # < PupilCreditSearch: 0x007fc961801308 @interval = : month, @page = 1, @per = 25, @pupil_id = [1042], @date_range = {: from => Mon,
  01 Aug 2016 00: 00: 00 UTC + 00: 00,
  : to => Mon,
  31 Jul 2017 00: 00: 00 UTC + 00: 00
}, @queries = [# < Search::Query: 0x007fc964791bb8 @query = nil, @fields = [], @type = : multi_match, @options = {: fields => [],
  : type => : cross_fields
} > ], @filters = [# < Search::Filter: 0x007fc964756db0 @name = : pupil_id, @value = [1042], @type = : terms, @options = {} > ], @aggregations = {: years_created => # < Search::Aggregation: 0x007fc9647a32f0 @type = : date_histogram,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_histogram,
    : params => {: interval => : year
    }
  } > ,
  : months_created => # < Search::Aggregation: 0x007fc9647a30c0 @type = : date_histogram,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_histogram,
    : params => {: interval => : month
    }
  } > ,
  : date_ranges => # < Search::Aggregation: 0x007fc9647a2800 @type = : date_range,
  @field = : created_at,
  @options = {: field => : created_at,
    : type => : date_range,
    : params => {: keyed => true,
      : ranges => [{: from => "now/w",
        : to => "now+1w/w",
        : key => : this_week
      }, {: from => "now/M",
        : to => "now+1M/M",
        : key => : this_month
      }, {: from => "now-1w/w",
        : to => "now-2w/w",
        : key => : last_week
      }, {: from => "now-1M/M",
        : to => "now-2M/M",
        : key => : last_month
      }, {: from => "2016-09-01",
        : to => "2017-08-31",
        : key => : academic_year
      }]
    }
  } > ,
  : groups => # < Search::Aggregation: 0x007fc9647a2260 @type = : terms,
  @field = : pupil_id,
  @options = {: aggs => {: all_dates => # < Search::Aggregation: 0x007fc9647a22d8 @type = : date_histogram,
      @field = : created_at,
      @options = {: params => {: interval => : month
        },
        : aggs => {: total_points => # < Search::Aggregation: 0x007fc9647a2440 @type = : sum,
          @field = : points,
          @options = {} > ,
          : running_total => # < Search::Aggregation: 0x007fc9647a2350 @type = : cumulative_sum,
          @field = nil,
          @options = {: params => {: buckets_path => "total_points"
            }
          } >
        }
      } >
    }
  } > ,
  : options => # < Search::Aggregation: 0x007fc9647a1518 @type = : global,
  @field = nil,
  @options = {: aggs => {: filtered => # < Search::Aggregation: 0x007fc9647a1590 @type = : filter,
      @field = nil,
      @options = {: params => {: and => [{: range => {: created_at => {: gte => Mon,
                01 Aug 2016 00: 00: 00 UTC + 00: 00,
                : lt => Mon,
                31 Jul 2017 00: 00: 00 UTC + 00: 00
              }
            }
          }, {: terms => {: pupil_id => [1042]
            }
          }]
        },
        : aggs => {: categories => # < Search::Aggregation: 0x007fc9647a1b80 @type = : terms,
          @field = "category",
          @options = {: ignore => true
          } > ,
          : topic_ids => # < Search::Aggregation: 0x007fc9647a19a0 @type = : terms,
          @field = "topic_id",
          @options = {: ignore => true
          } > ,
          : learning_objective_ids => # < Search::Aggregation: 0x007fc9647a17c0 @type = : terms,
          @field = "learning_objective_id",
          @options = {: ignore => true
          } > ,
          : completed_activities => # < Search::Aggregation: 0x007fc9647a1608 @type = : terms,
          @field = : pupil_id,
          @options = {: aggs => {: activities => # < Search::Aggregation: 0x007fc9647a1680 @type = : filter,
              @field = nil,
              @options = {: params => {: and => [{: terms => {: category => [0, 1, 2, 3]
                    }
                  }]
                }
              } >
            }
          } >
        }
      } >
    }
  } >
}, @request = # < Search::Request: 0x007fc964753548 @params = {: query => {: bool => {: must => [{: match_all => {}
      }],
      : filter => [{: terms => {: pupil_id => [1042]
        }
      }]
    }
  },
  : aggs => {: years_created => {: date_histogram => {: field => : created_at,
        : interval => : year
      }
    },
    : months_created => {: date_histogram => {: field => : created_at,
        : interval => : month
      }
    },
    : date_ranges => {: date_range => {: field => : created_at,
        : keyed => true,
        : ranges => [{: from => "now/w",
          : to => "now+1w/w",
          : key => : this_week
        }, {: from => "now/M",
          : to => "now+1M/M",
          : key => : this_month
        }, {: from => "now-1w/w",
          : to => "now-2w/w",
          : key => : last_week
        }, {: from => "now-1M/M",
          : to => "now-2M/M",
          : key => : last_month
        }, {: from => "2016-09-01",
          : to => "2017-08-31",
          : key => : academic_year
        }]
      }
    },
    : groups => {: terms => {: field => : pupil_id
      },
      : aggs => {: all_dates => {: date_histogram => {: field => : created_at,
            : interval => : month
          },
          : aggs => {: total_points => {: sum => {: field => : points
              }
            },
            : running_total => {: cumulative_sum => {: buckets_path => "total_points"
              }
            }
          }
        }
      }
    },
    : options => {: global => {},
      : aggs => {: filtered => {: filter => {: and => [{: range => {: created_at => {: gte => Mon,
                  01 Aug 2016 00: 00: 00 UTC + 00: 00,
                  : lt => Mon,
                  31 Jul 2017 00: 00: 00 UTC + 00: 00
                }
              }
            }, {: terms => {: pupil_id => [1042]
              }
            }]
          },
          : aggs => {: categories => {: terms => {: field => "category"
              }
            },
            : topic_ids => {: terms => {: field => "topic_id"
              }
            },
            : learning_objective_ids => {: terms => {: field => "learning_objective_id"
              }
            },
            : completed_activities => {: terms => {: field => : pupil_id
              },
              : aggs => {: activities => {: filter => {: and => [{: terms => {: category => [0, 1, 2, 3]
                      }
                    }]
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}


问:
Quickly sort list of objects to match the order of an array which contains the value of a property
I have a method that accepts a string[]. It takes this array and sorts it based off a custom algebraic formula we have. This algebraic formula is quite complex and cannot (or should not) be adapted to accept anything other than an IEnumerable<string>.

I'm tasked with creating a wrapper function for this method that accepts an IEnumerable<T> where T implements an interface exposing the string to be used for sorting.

Based on this, I have created a method that iterates the genetic enumerable, extracts the string and passes the resulting array into our custom sort function.  This works,  but I end up with a sorted array of strings,  completely disconnected from the original IEnumerable <T> . How can I sort the IEnumerable <T> to match the array of strings returned from our custom sort function?

For example.

```<code>private IEnumerable<T> Sort(IEnumerable<T> objects) where T: ICustomSortable
{
    string[] stringsToSort = new string[objects.Count()];
    for (int i = 0; i < stringsToSort.length; i++)
        stringsToSort[i] = objects.getString();

    stringsToSort = customSortFunction(stringsToSort);

    //somehow sort the objects so that they are in the same order as stringsToSort?
    /*
    The result is valid when:
     objects[0].getString() == stringsToSort[0]
     objects[1].getString() == stringsToSort[1]
     objects[2].getString() == stringsToSort[2]
      ...
     objects[n].getString() == stringsToSort[n]
    */
}
</code>```

EDIT: The strings retrieved from the customSortFunction may not be unique.  This means that two objects whose strings are the same, should both exist in the result. While the ordering of objects with the same string value is irrelevant,  they should remain in place when referencing the result as a whole.

答:
What you need is a mapping from the object string value to the object itself. Something like

```<code>IDictionary<string, T>
</code>```

Just create this mapping (before or after sorting), and after sorting is done based on their string values, create a new sorted list of T, by iterating through the (sorted) string list and using the mapping to get the corresponding T.

EDIT: Based on the comment that the string values may not be all distinct, all you need to do is to create a mapping from the string to a set/list of Ts. Something like,

```<code>IDictionary<string, IList<T>>
</code>```

[A] While you are looping through IEnumerable<T>, (1) if you see a new (string) key, create a new list and add the owner T for the string, and (2) if you find a key that is already in the dictionary, retrieve the list, and append the new owner T into the list.

[B] After sorting is done, go through the sorted string/key list, and find the corresponding Ts (one or more), and create a new list of Ts by consecutively appending the Ts.

This is not the most elegant way (a better way is obviously to use some kind of comparators), but it's straightforward and will get the job done.

Body:
I have a method that accepts a string[]. It takes this array and sorts it based off a custom algebraic formula we have. This algebraic formula is quite complex and cannot (or should not) be adapted to accept anything other than an IEnumerable<string>.

I'm tasked with creating a wrapper function for this method that accepts an IEnumerable<T> where T implements an interface exposing the string to be used for sorting.

Based on this, I have created a method that iterates the genetic enumerable, extracts the string and passes the resulting array into our custom sort function.  This works,  but I end up with a sorted array of strings,  completely disconnected from the original IEnumerable <T> . How can I sort the IEnumerable <T> to match the array of strings returned from our custom sort function?

For example.

private IEnumerable<T> Sort(IEnumerable<T> objects) where T: ICustomSortable
{
    string[] stringsToSort = new string[objects.Count()];
    for (int i = 0; i < stringsToSort.length; i++)
        stringsToSort[i] = objects.getString();

    stringsToSort = customSortFunction(stringsToSort);

    //somehow sort the objects so that they are in the same order as stringsToSort?
    /*
    The result is valid when:
     objects[0].getString() == stringsToSort[0]
     objects[1].getString() == stringsToSort[1]
     objects[2].getString() == stringsToSort[2]
      ...
     objects[n].getString() == stringsToSort[n]
    */
}

EDIT: The strings retrieved from the customSortFunction may not be unique.  This means that two objects whose strings are the same, should both exist in the result. While the ordering of objects with the same string value is irrelevant,  they should remain in place when referencing the result as a whole.

Body:
What you need is a mapping from the object string value to the object itself. Something like

IDictionary<string, T>

Just create this mapping (before or after sorting), and after sorting is done based on their string values, create a new sorted list of T, by iterating through the (sorted) string list and using the mapping to get the corresponding T.

EDIT: Based on the comment that the string values may not be all distinct, all you need to do is to create a mapping from the string to a set/list of Ts. Something like,

IDictionary<string, IList<T>>

[A] While you are looping through IEnumerable<T>, (1) if you see a new (string) key, create a new list and add the owner T for the string, and (2) if you find a key that is already in the dictionary, retrieve the list, and append the new owner T into the list.

[B] After sorting is done, go through the sorted string/key list, and find the corresponding Ts (one or more), and create a new list of Ts by consecutively appending the Ts.

This is not the most elegant way (a better way is obviously to use some kind of comparators), but it's straightforward and will get the job done.

ContentLicense: CC BY-SA 4.0


问:
Doxygen tree-view shows only one group/module
In a few different .h files, I have:

```<code>/**
 * @defgroup NAME <title>
 * <description>
 * @{
 */

// ...

/** @} */
</code>```

that is, I define a few groups. In the generated HTML documentation, all the groups show up under Modules. However, in the tree view hierarchy, only the first group shows up. Why?

If I enable the normal Modules menu via DISABLE_INDEX = NO, then the menu includes all 3 modules (as it should). So why doesn't the tree view show all 3?

I am using Doxygen 1.8.13.

For completeness, here is my Doxyfile showing only those values that differ from the default:

```<code>PROJECT_NAME            = "cdecl"
PROJECT_BRIEF           = "Compose and decipher C (or C++) type declarations or casts, aka ‘‘gibberish.’’"

INPUT                   = README.md src
EXTENSION_MAPPING       = l=C y=C
FILE_PATTERNS           = *.c *.h *.l *.md *.y
FILTER_PATTERNS         = "*.h=sed s/CDECL_[A-Z]*_INLINE/inline/"
PREDEFINED              = __GNUC__ \
                          WITH_READLINE \
                          WITH_TERM_COLUMNS
EXCLUDE                 = src/config.h \
                          src/lexer.c \
                          src/literals.h src/literals.c \
                          src/parser.c src/parser.h
OUTPUT_DIRECTORY        = docs

EXTRACT_ALL             = YES
EXTRACT_PACKAGE         = YES
EXTRACT_STATIC          = YES

DISABLE_INDEX           = YES
GENERATE_TREEVIEW       = YES

ALPHABETICAL_INDEX      = NO
ENUM_VALUES_PER_LINE    = 1
FORCE_LOCAL_INCLUDES    = YES
INTERNAL_DOCS           = YES
JAVADOC_AUTOBRIEF       = YES
MARKDOWN_SUPPORT        = YES
MAX_INITIALIZER_LINES   = 0
OPTIMIZE_OUTPUT_FOR_C   = YES
QUIET                   = YES
SHOW_INCLUDE_FILES      = NO
SORT_BRIEF_DOCS         = YES
TAB_SIZE                = 2
TYPEDEF_HIDES_STRUCT    = YES
USE_MDFILE_AS_MAINPAGE  = README.md
WARN_NO_PARAMDOC        = YES

SOURCE_BROWSER          = YES
STRIP_CODE_COMMENTS     = YES
REFERENCED_BY_RELATION  = YES
REFERENCES_LINK_SOURCE  = YES
REFERENCES_RELATION     = YES
</code>```

答:
Despite my using a force-reload in the browser, apparently that does not cause JavaScript to be reloaded.  The modules are done using JavaScript (why??). So the answer is that there's nothing wrong with Doxygen or my use of it: it's a stupid browser-caching issue.

In order to force-reload everything, I had to clear the browser cache to see the changes.  This is really annoying while writing the documentation.

Body:
In a few different .h files, I have:

/**
 * @defgroup NAME <title>
 * <description>
 * @{
 */

// ...

/** @} */

that is, I define a few groups. In the generated HTML documentation, all the groups show up under Modules. However, in the tree view hierarchy, only the first group shows up. Why?

If I enable the normal Modules menu via DISABLE_INDEX = NO, then the menu includes all 3 modules (as it should). So why doesn't the tree view show all 3?

I am using Doxygen 1.8.13.

For completeness, here is my Doxyfile showing only those values that differ from the default:

PROJECT_NAME            = "cdecl"
PROJECT_BRIEF           = "Compose and decipher C (or C++) type declarations or casts, aka ‘‘gibberish.’’"

INPUT                   = README.md src
EXTENSION_MAPPING       = l=C y=C
FILE_PATTERNS           = *.c *.h *.l *.md *.y
FILTER_PATTERNS         = "*.h=sed s/CDECL_[A-Z]*_INLINE/inline/"
PREDEFINED              = __GNUC__ \
                          WITH_READLINE \
                          WITH_TERM_COLUMNS
EXCLUDE                 = src/config.h \
                          src/lexer.c \
                          src/literals.h src/literals.c \
                          src/parser.c src/parser.h
OUTPUT_DIRECTORY        = docs

EXTRACT_ALL             = YES
EXTRACT_PACKAGE         = YES
EXTRACT_STATIC          = YES

DISABLE_INDEX           = YES
GENERATE_TREEVIEW       = YES

ALPHABETICAL_INDEX      = NO
ENUM_VALUES_PER_LINE    = 1
FORCE_LOCAL_INCLUDES    = YES
INTERNAL_DOCS           = YES
JAVADOC_AUTOBRIEF       = YES
MARKDOWN_SUPPORT        = YES
MAX_INITIALIZER_LINES   = 0
OPTIMIZE_OUTPUT_FOR_C   = YES
QUIET                   = YES
SHOW_INCLUDE_FILES      = NO
SORT_BRIEF_DOCS         = YES
TAB_SIZE                = 2
TYPEDEF_HIDES_STRUCT    = YES
USE_MDFILE_AS_MAINPAGE  = README.md
WARN_NO_PARAMDOC        = YES

SOURCE_BROWSER          = YES
STRIP_CODE_COMMENTS     = YES
REFERENCED_BY_RELATION  = YES
REFERENCES_LINK_SOURCE  = YES
REFERENCES_RELATION     = YES


问:
Reduce div height by a set amount
I'm writing a website and I have a problem. I have a 'card' div that has an image inside it that i moved halfway outside of it using position:relative. My problem is that, when I write text inside said div, there is always a bit of white space at the bottom, exactly the size of the half the image (17vw).

I saw this solution, and I used it like this: calc(100% - 17vw) but it isn´t working.

You can see the example of the problem in my website http://nuno99costa.xyz/test

答:
Use margin-top: -17vw instead of top: -17vw on line 54 of style.css

(You can also remove the position: relative as well.)

A negative margin-top removes space above, whereas top just moves the element.

Title: Reduce div height by a set amount


问:
Why is this causing my program to crash?
I have created the following user defined function which generates random variables using the Acceptance-Rejection Method. However, whenever it is called, my program goes on and eventually crashes or I have to force quit. I have gone through it several times. Any ideas as to what could be causing this?

I am aware that this may not be the best way to have written this (Yesterday was the first time I have used R) so any extra tips are a bonus!

```<code>acceptReject <- function(){
  Z <- 0
  Y <- c(0,0)
  while(Y[2] < .5*(Y[1]-1)**2){
    U <- runif(2,0,1)
    Y <- log(U)
  }
  Z <- Y[1]
  U <- runif(1,0,1)
  if(U <= .5){
    Z <- abs(Z)
  }
  else{
    Z <- -abs(Z)
  }
  Z
}
</code>```

答:
You have an infinite loop.

If you assume that Y ~ log( [0,1] ) (mathematically), that means that it always range between log(0) and log(1), equating to -Inf and 0, respectively. (Bottom line, it is always less-than-or-equal-to zero.)

Now let's look at your conditional: .5*(Y[1]-1)**2. If you know the domain of Y is c(-Inf,0), then the range of this formula is

```<code>.5*(c(-Inf,0)-1)**2
# [1] Inf 0.5
</code>```

(This is always greater-than-or-equal-to 0.5.)

Since Y is always <= 0 and the formula is always >= 0.5, your conditional will mathematically always be true. Infinite loop.

Body:
I have created the following user defined function which generates random variables using the Acceptance-Rejection Method. However, whenever it is called, my program goes on and eventually crashes or I have to force quit. I have gone through it several times. Any ideas as to what could be causing this?

I am aware that this may not be the best way to have written this (Yesterday was the first time I have used R) so any extra tips are a bonus!

acceptReject <- function(){
  Z <- 0
  Y <- c(0,0)
  while(Y[2] < .5*(Y[1]-1)**2){
    U <- runif(2,0,1)
    Y <- log(U)
  }
  Z <- Y[1]
  U <- runif(1,0,1)
  if(U <= .5){
    Z <- abs(Z)
  }
  else{
    Z <- -abs(Z)
  }
  Z
}

Body:
You have an infinite loop.

If you assume that Y ~ log( [0,1] ) (mathematically), that means that it always range between log(0) and log(1), equating to -Inf and 0, respectively. (Bottom line, it is always less-than-or-equal-to zero.)

Now let's look at your conditional: .5*(Y[1]-1)**2. If you know the domain of Y is c(-Inf,0), then the range of this formula is

.5*(c(-Inf,0)-1)**2
# [1] Inf 0.5

(This is always greater-than-or-equal-to 0.5.)

Since Y is always <= 0 and the formula is always >= 0.5, your conditional will mathematically always be true. Infinite loop.


问:
When to use getX method
Coming from a C# background we use properties for something that would not take long to retrieve and a getX method if something would take long (msdn link). In Java, since there are no properties, do you use getX for both cases or is there some other convention to indicate a quick access from a not so quick access (other than documenting it)?

Edit:
For example would you use a different naming convention for a time consuming get operation like database access or also use the getX naming convention?

答: Usually getX() methods are considered to be quick access methods and database-backed methods should be findX() or loadX() or something along those lines, but as far as I know there's no global agreement over it. Even the "getters should be quick" rule isn't adhered to sometimes.

ContentLicense: CC BY-SA 2.5

Title: When to use getX method


问:
How to use the "handler" of UIAlertAction to call another UIAlertAction?
Is it possible to use the handler to trigger other alerts?

```<code>func jokeFinal() {
    let alert = UIAlertController(title: "Never Mind", message: "It's Pointless", preferredStyle: .alert)
    let action = UIAlertAction(title: "Hahahahahaha", style: .default, handler: nil)
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

func joke() {
    let alert = UIAlertController(title: "A broken pencil", message: "...", preferredStyle: .alert)
    let action = UIAlertAction(title: "A broken pencil who?", style: .default, handler: jokeFinal())
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

@IBAction func nock() {
    let alert = UIAlertController(title: "Knock,Knock", message: "..", preferredStyle: .alert)
    let action = UIAlertAction(title: "Who's there??", style: .default, handler: joke())
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}
</code>```

I'm trying to use the handler of a UIAlertAction to call another UIAlert. Is it possible?

I am receiving the following error:

Cannot convert value of type '()' to expected argument type '((UIAlertAction) -> Void)?'

答:
The handler doesn't call a function. It is a function.

So, for example, you might do this. Change the declaration of

```<code> func jokeFinal() {
</code>```

to

```<code> func jokeFinal(_ action: UIAlertAction) {
</code>```

Then change

```<code> handler: jokeFinal()
</code>```

to

```<code> handler: jokeFinal
</code>```

And so on.

Body:
Is it possible to use the handler to trigger other alerts?

func jokeFinal() {
    let alert = UIAlertController(title: "Never Mind", message: "It's Pointless", preferredStyle: .alert)
    let action = UIAlertAction(title: "Hahahahahaha", style: .default, handler: nil)
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

func joke() {
    let alert = UIAlertController(title: "A broken pencil", message: "...", preferredStyle: .alert)
    let action = UIAlertAction(title: "A broken pencil who?", style: .default, handler: jokeFinal())
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

@IBAction func nock() {
    let alert = UIAlertController(title: "Knock,Knock", message: "..", preferredStyle: .alert)
    let action = UIAlertAction(title: "Who's there??", style: .default, handler: joke())
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

I'm trying to use the handler of a UIAlertAction to call another UIAlert. Is it possible?

I am receiving the following error:

Cannot convert value of type '()' to expected argument type '((UIAlertAction) -> Void)?'

Body:
The handler doesn't call a function. It is a function.

So, for example, you might do this. Change the declaration of

 func jokeFinal() {

to

 func jokeFinal(_ action: UIAlertAction) {

Then change

 handler: jokeFinal()

to

 handler: jokeFinal

And so on.


问:
Android Studio is slow (how to speed up)?
I recently upgraded from Eclipse to Android Studio and I'm not really liking the experience. I'm comparing them both on a Windows 7 64 bit ultimate with 16GB of ram and Intel i7 4770 running NVidia Geforce 780 with the latest NVidia drivers if it matters and I'm running the latest JDK and the latest Android Studio.

The Android Studio is very slow in building the project which I can live with but it's also extremely resource intensive and sometimes slows down the PC to a crawl.

Whenever I'm building or running anything in AS, my PC seems to become extremely sluggish. It also causes flickering of screen and occasionally blanking my second monitor if I click on "Gradle build running" spinner which I find very odd. The RAM usage also shoots up to ~3GB which I find excessive for doing nothing (this is when it's idle after a few builds).

In addition, the panels at the bottom of AS keep jumping around which is a horrible user experience (moves from Android to Messages to Version Control or anything else on an ad-hoc basis depending on what's happening which is very, very annoying).

What I would like to know is basically:

1) How do I make Android Studio run better? I may be doing something wrong or missing some updates that I'm not aware of and I'm sure others have also noticed these behaviors and have found some solutions to it.

2) How do I "pin" the bottom panels so that they don't jump around and instead, let me, the user, navigate to them when I wish to instead of automatically switching them?

Many thanks and my apologies again if it's not the correct place for these questions.

Edit 1
Some more comments:

I'm using the latest stable build as of today. The build is Android Studio 1.2.2 Build # AI-141.1980579, Build on June 3, 2015

The behavior happens when using either Java 7 or 8. It doesn't appear to be related to the version of Java.

I am not using Presentation Mode. Just the vanilla view.

Doing the changes to the build configuration (thanks to @Blackbelt and his answer) appears to have helped with the build but the other problems with sluggishness and general user experience remain.

答:
I followed this post and it worked great for me.

EDIT:

Following tips have been mentioned in the above post.

In gradle.properties, put this:

```<code>org.gradle.daemon=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true
</code>```

And in build.gradle, put this (Note this will disable lint check):

```<code>tasks.whenTaskAdded { task ->
    if (task.name.equals("lint")) {
        task.enabled = false
    }
}
</code>```

Body:
I followed this post and it worked great for me.

EDIT:

Following tips have been mentioned in the above post.

In gradle.properties, put this:

org.gradle.daemon=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true

And in build.gradle, put this (Note this will disable lint check):

tasks.whenTaskAdded { task ->
    if (task.name.equals("lint")) {
        task.enabled = false
    }
}


问:
Permissions for android application in blackberry
My blackberry phone version is 10.3.2. I installed an android application on it. The application needs permission to send sms. But I dont see any option to enable the permission application permission.
 In android, the application even requests for permission on launch, but not for blackberry.

 Any idea why?

答:
Unfortunately, Android apps run on BlackBerry 10 devices cannot access some of the BlackBerry services like emails, SMS or contacts, that's why you don't even see the permission in Settings -> Security and Privacy -> Application Permissions -> YourSmsAppName. Most of the permissions for Android apps are granted and cannot be revoked on BlackBerry 10, only the Run When Minimized permission can be revoked.

If you install any Android Launcher app on your BlackBerry 10, you'll be able to access the Android Settings app, you'll be able to navigate to Settings -> Apps -> YourSmsAppName and see that the SMS permission is there indeed, but there's no way to disable it (or enable it in your case, it's already enabled).

I had a situation where I needed one of my Android app to get access to BlackBerry 10 emails and SMS, and the only solution I found was to build a BlackBerry 10 companion app that exchange data through a local socket on the phone, you won't be able to do that if you don't have control (of code) of both Android and BlackBerry 10 apps.


问:
Get sum of two columns and save it to variable
In my MySQL, I have field ID, price, and date field (timestamp).

I want to, at end of the month, calculate total cost for that month and save it to variable $monthjuly.

```<code>SELECT SUM(price) FROM app WHERE YEAR(datum) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(datum) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)"
</code>```

I tried via this command to output results, but I am not getting any result with this metod.
Where is my mistake here?

答:
Edit:
You are doing a SUM with no grouping of data.  Whenever you aggregate data you need to have a grouping.  In this case we group by year and month.

Demo - http://sqlfiddle.com/#!9/d952a3/1

```<code>SELECT SUM(price), year(datum), month(datum)
FROM app
WHERE
    YEAR(datum) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
    AND MONTH(datum) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
GROUP BY YEAR(datum), MONTH(datum)
</code>```

Body:
In my MySQL, I have field ID, price, and date field (timestamp).

I want to, at end of the month, calculate total cost for that month and save it to variable $monthjuly.

SELECT SUM(price) FROM app WHERE YEAR(datum) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(datum) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)"

I tried via this command to output results, but I am not getting any result with this metod.
Where is my mistake here?

Body:
Edit:
You are doing a SUM with no grouping of data.  Whenever you aggregate data you need to have a grouping.  In this case we group by year and month.

Demo - http://sqlfiddle.com/#!9/d952a3/1

SELECT SUM(price), year(datum), month(datum)
FROM app
WHERE
    YEAR(datum) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
    AND MONTH(datum) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
GROUP BY YEAR(datum), MONTH(datum)


问:
How to make Socket IO work over HTTPS using node.js
This is frustrating me like crazy!

i'm using a proxy so that any requests that go to myurl/APP/ are answered by node.js at myurl:8001

I now need this to work over https. easy.... i thought.

i have Apache serving up the old version from the public folder. That is stand alone, and when i'm done building this, it will just be removed. but for now needs to remain in tact and accessible. Lets encrypt is setup on this. and https://myurl works fine, showing content from the public folder of course.

if i go to https://myurl:8001 then chrome says "site can't be reached". If i go to http://myurl:8001 it works fine. I think this is because https default port is 443. I have VPS not dedicated so i don't think i can alter that. And surely if i did alter the ssl port then it wont work for the public folder??

i'll show you the basics of whats going on;

app.js;

```<code>   var express = require('express');
var app = express();
var serv = require('http').Server(app);

app.get('/',function(req, res) {
    res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));

serv.listen(8001);
console.log("Server started.");

var SOCKET_LIST = {};

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
    socket.id = Math.random();
    socket.x = 0;
    socket.y = 0;
    socket.number = "" + Math.floor(10 * Math.random());
    SOCKET_LIST[socket.id] = socket;

    socket.on('disconnect',function(){
        delete SOCKET_LIST[socket.id];
    });

});

setInterval(function(){
    var pack = [];
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.x++;
        socket.y++;
        pack.push({
            x:socket.x,
            y:socket.y,
            number:socket.number
        });
    }
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.emit('newPositions',pack);
    }

},1000/25);
</code>```

client/index.html;

```<code><canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>

<script>
    var ctx = document.getElementById("ctx").getContext("2d");
    ctx.font = '30px Arial';

    var socket = io.connect('http://www.myurl:8001', {path: "/socket.io"});

    socket.on('newPositions',function(data){
        ctx.clearRect(0,0,500,500);
        for(var i = 0 ; i < data.length; i++)
            ctx.fillText(data[i].number,data[i].x,data[i].y);
    });
</script>
</code>```

It works fine as the code is but only over http. I need this to work over SSL

i need this line to work when its https;

```<code>var socket = io.connect('https://www.myurl:8001', {path: "/socket.io"});
</code>```

How is this possible?

any help is greatly appreciated.

答:
Your server code is only creating an http server, not an https server and since socket.io uses your http server, it will only run on http.  http and https servers are different (the https server implements certificate verification and data encryption which is not present with the http server).

To make an https server, change this:

```<code>var express = require('express');
var app = express();
var serv = require('http').Server(app);
</code>```

to this:

```<code>const express = require('express');
const app = express();
const options = {...};    // fill in relevant certificate info here
const serv = require('https').createServer(options, app);
</code>```

And, you will have to fill in the appropriate certificateinfo in the options data structure.

https.createServer() code examples are here.

You can then run your https server on any port you want as long as you connect to it with an https URL and the right port number.  You are correct that the default port for an https URL is 443 so if not port number is specified, that's what a browser will attempt to use.

Body:
This is frustrating me like crazy!

i'm using a proxy so that any requests that go to myurl/APP/ are answered by node.js at myurl:8001

I now need this to work over https. easy.... i thought.

i have Apache serving up the old version from the public folder. That is stand alone, and when i'm done building this, it will just be removed. but for now needs to remain in tact and accessible. Lets encrypt is setup on this. and https://myurl works fine, showing content from the public folder of course.

if i go to https://myurl:8001 then chrome says "site can't be reached". If i go to http://myurl:8001 it works fine. I think this is because https default port is 443. I have VPS not dedicated so i don't think i can alter that. And surely if i did alter the ssl port then it wont work for the public folder??

i'll show you the basics of whats going on;

app.js;

   var express = require('express');
var app = express();
var serv = require('http').Server(app);

app.get('/',function(req, res) {
    res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));

serv.listen(8001);
console.log("Server started.");

var SOCKET_LIST = {};

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
    socket.id = Math.random();
    socket.x = 0;
    socket.y = 0;
    socket.number = "" + Math.floor(10 * Math.random());
    SOCKET_LIST[socket.id] = socket;

    socket.on('disconnect',function(){
        delete SOCKET_LIST[socket.id];
    });

});

setInterval(function(){
    var pack = [];
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.x++;
        socket.y++;
        pack.push({
            x:socket.x,
            y:socket.y,
            number:socket.number
        });
    }
    for(var i in SOCKET_LIST){
        var socket = SOCKET_LIST[i];
        socket.emit('newPositions',pack);
    }

},1000/25);

client/index.html;

<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>

It works fine as the code is but only over http. I need this to work over SSL

i need this line to work when its https;

var socket = io.connect('https://www.myurl:8001', {path: "/socket.io"});

How is this possible?

any help is greatly appreciated.

Body:
Your server code is only creating an http server, not an https server and since socket.io uses your http server, it will only run on http.  http and https servers are different (the https server implements certificate verification and data encryption which is not present with the http server).

To make an https server, change this:

var express = require('express');
var app = express();
var serv = require('http').Server(app);

to this:

const express = require('express');
const app = express();
const options = {...};    // fill in relevant certificate info here
const serv = require('https').createServer(options, app);

And, you will have to fill in the appropriate certificateinfo in the options data structure.

https.createServer() code examples are here.

You can then run your https server on any port you want as long as you connect to it with an https URL and the right port number.  You are correct that the default port for an https URL is 443 so if not port number is specified, that's what a browser will attempt to use.


问:
OwnProps not being passed with React Router V4
I'm refactoring an app from V2 to V4 of React Router, and I have run into an issue where properties from my mapStateToProps are not being passed down to each component. Here's my setup:

App.jsx

```<code>render() {
        return (
            <div>
                <Header />
                <Navbar />
                <Routes {...this.props} />
                <Footer />
            </div>
        )
    }

const mapStateToProps = (state, ownProps) => {
    const { page } = state
    return {
        routeProps: ownProps,
        page: page
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        pageActions: bindActionCreators(pageActionCreators, dispatch),
    }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App))
</code>```

Routes.jsx has this line:

<Route exact path="/:name/information" render={ ({ match }) => <InfoPage {...this.props} match={ match } /> } />

InfoPage.jsx

```<code>componentDidMount() {
    const { routeProps, pageActions } = this.props
    pageActions.fetchInfoPage(routeProps.match.params.name)
}
componentWillReceiveProps(nextProps) {
    if (this.props.page.page !== nextProps.page.page) {
        const { routeProps, pageActions } = nextProps
        pageActions.fetchInfoPage(routeProps.match.params.name)
    }
}
render() {
    return (
        <InfoPageView
        page={ this.props.page }
        pageActions={ this.props.pageActions }
        routeProps={ this.props.routeProps }
        />
    )
}
</code>```

The problem is that when I try to access a route that uses InfoPage, i.e. /orders/information, it never loads. When I check Redux dev tools, it says that page and content are undefined. The only things I changed on the InfoPage component while refactoring were adding in match.params instead of params. This is leading me to believe that there is something wrong with my Redux/Router integration, specifically with ownProps/routeProps not being passed down properly.

Any ideas as to what's wrong here?

答:
Could you try moving your withRouter call to Routes.jsx

```<code>export default withRouter(connect()(Routes))
</code>```

I believe that needs to be in the same file as any <Route ... /> components.

Body:
I'm refactoring an app from V2 to V4 of React Router, and I have run into an issue where properties from my mapStateToProps are not being passed down to each component. Here's my setup:

App.jsx

render() {
        return (

                <Navbar />
                <Routes {...this.props} />

        )
    }

const mapStateToProps = (state, ownProps) => {
    const { page } = state
    return {
        routeProps: ownProps,
        page: page
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        pageActions: bindActionCreators(pageActionCreators, dispatch),
    }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App))

Routes.jsx has this line:

<Route exact path="/:name/information" render={ ({ match }) => <InfoPage {...this.props} match={ match } /> } />

InfoPage.jsx

componentDidMount() {
    const { routeProps, pageActions } = this.props
    pageActions.fetchInfoPage(routeProps.match.params.name)
}
componentWillReceiveProps(nextProps) {
    if (this.props.page.page !== nextProps.page.page) {
        const { routeProps, pageActions } = nextProps
        pageActions.fetchInfoPage(routeProps.match.params.name)
    }
}
render() {
    return (
        <InfoPageView
        page={ this.props.page }
        pageActions={ this.props.pageActions }
        routeProps={ this.props.routeProps }
        />
    )
}

The problem is that when I try to access a route that uses InfoPage, i.e. /orders/information, it never loads. When I check Redux dev tools, it says that page and content are undefined. The only things I changed on the InfoPage component while refactoring were adding in match.params instead of params. This is leading me to believe that there is something wrong with my Redux/Router integration, specifically with ownProps/routeProps not being passed down properly.

Any ideas as to what's wrong here?

Body:
Could you try moving your withRouter call to Routes.jsx

export default withRouter(connect()(Routes))

I believe that needs to be in the same file as any <Route ... /> components.


问:
Incrementing Left padding a string
I have the String = 82868184847, and I want to left pad it with numbers starting from 000 to 999. I tried doing this:

```<code> for (int i = 0; i < 1000; i++) {

        number = String.format("%02d", i);
        paddedNum = number;
   }
</code>```

I want my output to be

      00082868184847

      00182868184847

      00282868184847

      ...

      99982868184847

but I get

     00082868184847

01082868184847

02082868184847

....

答:
String key = "82868184847";String salt ;
        for (int i = 0; i <= 999; i++) {
            salt = String.format("%03d", i);
            System.out.println( salt + key);}

Title: Incrementing Left padding a string

Body:
I have the String = 82868184847, and I want to left pad it with numbers starting from 000 to 999. I tried doing this:

 for (int i = 0; i < 1000; i++) {

        number = String.format("%02d", i);
        paddedNum = number;
   }

I want my output to be

      00082868184847

      00182868184847

      00282868184847

      ...

      99982868184847

but I get

     00082868184847

01082868184847

02082868184847

....


问:
Reducer not writing to Redux store
I have a connect()ed container component where I try to write a list of books to my redux store. The action creator is available as props and state is mapped to props, however the book list never get into the redux store. readingList is still null instead of bookArray (the passed argument of the action creator). Can someone spot the issue here? Included relevant snippets here:

```<code>import { setReadingList } from '../actions/index';

componentWillMount() {
    this.props.setReadingList(bookArray);
}

function mapStateToProps(state) {
  return {
    readingList: state.readingList
    }
  }

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ setReadingList : setReadingList }, dispatch);
  }

export default connect(mapStateToProps, mapDispatchToProps)(ReadingList);

/*-----------*/

./actions/index.js

export function setReadingList(readingList) {
    return {
      type : "SET_READINGLIST",
      payload : readingList
    };
  }

/*-----------*/

./reducers/index.js

import { combineReducers } from 'redux';
import readingList from './reading_list';

export const rootReducer = combineReducers({
  readingList
});
export default rootReducer;

/*-----------*/

./reducers/reading_list.js

export default function(state = null, action) {
  switch (action.type) {
    case "SET_READINGLIST":
      return action.payload;
    default:
      return state;
  }
}
</code>```

Thanks!

答: Try calling setReadingList in componentDidMount instead of componentWillMount. Would also ensure bookArray is in scope.</p>

Title: Reducer not writing to Redux store

Body:
I have a connect()ed container component where I try to write a list of books to my redux store. The action creator is available as props and state is mapped to props, however the book list never get into the redux store. readingList is still null instead of bookArray (the passed argument of the action creator). Can someone spot the issue here? Included relevant snippets here:

import { setReadingList } from '../actions/index';

componentWillMount() {
    this.props.setReadingList(bookArray);
}

function mapStateToProps(state) {
  return {
    readingList: state.readingList
    }
  }

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ setReadingList : setReadingList }, dispatch);
  }

export default connect(mapStateToProps, mapDispatchToProps)(ReadingList);

/*-----------*/

./actions/index.js

export function setReadingList(readingList) {
    return {
      type : "SET_READINGLIST",
      payload : readingList
    };
  }

/*-----------*/

./reducers/index.js

import { combineReducers } from 'redux';
import readingList from './reading_list';

export const rootReducer = combineReducers({
  readingList
});
export default rootReducer;

/*-----------*/

./reducers/reading_list.js

export default function(state = null, action) {
  switch (action.type) {
    case "SET_READINGLIST":
      return action.payload;
    default:
      return state;
  }
}

Thanks!


问:
Customizing the scroll bar
Can we change the appearance of scroll bar? I mean we want to change the image of the scroll bar, so it can match our web theme. more specifically, i'm pointing at the scroll bar in

```<code><div style=overflow:auto>
</code>```

If it can't be done, then is there some other way to make our own "scroll bar", which use our own image?

Perhaps if we're insane enough, maybe we'll do it like this.
We make a bunch of
 which contain an image of up arrow, scroll, down arrow, etc. And then we applied some function to each of them. off course the width of scroll will depend on the amount of the content.

Can somebody help?

答:
Check out this site - I've heard good things about the method implemented, although I have never really bothered to create my own custom scroll bars.

You should be able to style in line with your own theme with a bit of experimentation.

Title: Customizing the scroll bar

Body:
Can we change the appearance of scroll bar? I mean we want to change the image of the scroll bar, so it can match our web theme. more specifically, i'm pointing at the scroll bar in

If it can't be done, then is there some other way to make our own "scroll bar", which use our own image?

Perhaps if we're insane enough, maybe we'll do it like this.
We make a bunch of
 which contain an image of up arrow, scroll, down arrow, etc. And then we applied some function to each of them. off course the width of scroll will depend on the amount of the content.

Can somebody help?

OwnerDisplayName: Jayx


问:
UTF-8: General? Bin? Unicode?
I'm trying to figure out what collation I should be using for various types of data. 100% of the content I will be storing is user-submitted.

My understanding is that I should be using UTF-8 General CI (Case-Insensitive) instead of UTF-8 Binary. However, I can't find a clear a distinction between UTF-8 General CI and UTF-8 Unicode CI.

Should I be storing user-submitted content in UTF-8 General or UTF-8 Unicode CI columns?

What type of data would UTF-8 Binary be applicable to?

答: You should also be aware of the fact, that with utf8_general_ci when using a varchar field as unique or primary index inserting 2 values like 'a' and 'á' would give a duplicate key error.</p>

Title: UTF-8: General? Bin? Unicode?


问:
Rails 5 API + Vue.js frontend: form to invite users with devise_invitable
I am writing an invitation form with Vue.js. The invites should POST to a Rails 5 API. I am using devise_invitable for the invitation logic and email dispatch. However, I am having a problem with intercepting the create method, as I will be sending the invitation to multiple users so I want to perform a User.invite! for each user in the params.

My invite.vue file, which contains the form to post:

```<code><template>
  <b-row>
    <b-col>
      Invite {{form.length}} members

      <b-form @submit.prevent="submitStaffInvite" id='staffInvite'>
        <div v-for="(row, idx) in form">
          <b-row>
            <b-col cols="3">
              <b-form-group id="firstNameGroup" label="First name">
                <b-form-input id="firstNameInput" name="user[first_name][]" type="text" v-model="row.firstName" autofocus></b-form-input>
              </b-form-group>
            </b-col>
            <b-col cols="3">
              <b-form-group id="lastNameGroup" label="Last name">
                <b-form-input id="lastNameInput" name="user[last_name][]" type="text" v-model="row.lastName"></b-form-input>
              </b-form-group>
            </b-col>
            <b-col cols="3">
              <b-form-group id="emailGroup" label="Staff email">
                <b-form-input id="emailInput" name="user[email][]" type="text" v-model="row.email"></b-form-input>
              </b-form-group>
            </b-col>
            <b-col cols="3">
              <b-button @click='removeRow(idx)'>Remove invitation</b-button>
            </b-col>
          </b-row>
        </div>
        <br />
        <b-button-group>
          <b-button @click.prevent='addRow'>Add invitation</b-button>
        </b-button-group>
        <br />
        <b-button-group>
          <b-button type="submit" variant="primary">Submit</b-button>
        </b-button-group>

      </b-form>
    </b-col>
  </b-row>
</template>

<script>
  export default {
    data: () => {
      return {
        form: [
          {
            email: '',
            firstName: '',
            lastName: ''
          }
        ]
      }
    },
    methods: {
      addRow: function () {
        this.form.push({
          email: '',
          firstName: '',
          lastName: ''
        })
      },
      removeRow: function (idx) {
        this.form.splice(idx, 1)
      },
      submitStaffInvite: function () {
        this.$axios.post('http://localhost:3001/auth/invitation', this.form)
          .then((res) => {
            if (res.status === 200) {
              this.$notify({
                text: res.data.message,
                group: 'alerts',
                type: 'success'
              })
            }
          })
          .catch(function (error) {
            error.response.data.errors.forEach((err) => {
              this.$notify({
                text: err,
                group: 'alerts',
                type: 'warning'
              })
            })
          })
      }
    }
  }
</script>
</code>```

my users/invitations_controller.rb

```<code>class Users::InvitationsController < Devise::InvitationsController
  before_action :configure_permitted_parameters

  def create
    # TODO
    # Send email to each user in the form.
  end

  def edit
    sign_out send("current_#{resource_name}") if send("#{resource_name}_signed_in?")
    set_minimum_password_length
    resource.invitation_token = params[:invitation_token]
    redirect_to "http://localhost:3001/auth/invitation/accept?invitation_token=#{params[:invitation_token]}"
  end

  def update
    super do |resource|
      if resource.errors.empty?
        render json: { status: "Invitation Accepted!" }, status: 200
      else
        render json: resource.errors, status: 401
      end
    end
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:accept_invitation, keys: [:first_name, :last_name])
  end
end
</code>```

my routes.rb

```<code>Rails.application.routes.draw do
  # Using devise_token_auth for the API
  mount_devise_token_auth_for 'User', at: 'auth',
                                      defaults: { format: :json },
                                      controllers: {
                                        invitations: 'users/invitations'
                                      }
  ...
end
</code>```

I can see that the following routes exist:

```<code>PUT      /auth/invitation(.:format)            devise/invitations#update
POST     /auth/invitation(.:format)            devise/invitations#create
</code>```

The problem I can see here though is that I'd expect the routes to look like this:

```<code>PUT      /auth/invitation(.:format)            users/invitations#update
POST     /auth/invitation(.:format)            users/invitations#create
</code>```

This behavior might be caused by the devise_token_auth gem, which I'm not sure how to correct.

Again, when I submit this form I'd expect to be able to intercept the create method, so to then call User.invite! on all the users that are listed in the form. I've tried adding a byebug or binding.pry inside the create method but the code doesn't appear to execute, which means it's being bypassed.

The error message I see is:

```<code>Processing by Devise::InvitationsController#create as HTML
  Parameters: {"_json"=>[{"email"=>"asd@ad.com", "firstName"=>"Test", "lastName"=>"Last"}], "invitation"=>{"_json"=>[{"email"=>"asd@ad.com", "firstName"=>"Test", "lastName"=>"Last"}]}}
Completed 500 Internal Server Error in 0ms (ActiveRecord: 0.0ms)

ArgumentError (wrong number of arguments (given 1, expected 0)):
</code>```

Am I not supposed to pass the form data to the devise_invitable's create method? Any help is much appreciated.

Thanks in advance!

答:
Try changing your routes to

```<code>mount_devise_token_auth_for 'User', at: 'auth', skip: [:invitations]

devise_for :users, path: "auth", only: [:invitations],
controllers: { invitations: 'users/invitations' }
</code>```

For more information you can refer to this article

Body:
I am writing an invitation form with Vue.js. The invites should POST to a Rails 5 API. I am using devise_invitable for the invitation logic and email dispatch. However, I am having a problem with intercepting the create method, as I will be sending the invitation to multiple users so I want to perform a User.invite! for each user in the params.

My invite.vue file, which contains the form to post:

<template>

      Invite {{form.length}} members

              Remove invitation

          Add invitation

          Submit

</template>

my users/invitations_controller.rb

class Users::InvitationsController < Devise::InvitationsController
  before_action :configure_permitted_parameters

  def create
    # TODO
    # Send email to each user in the form.
  end

  def edit
    sign_out send("current_#{resource_name}") if send("#{resource_name}_signed_in?")
    set_minimum_password_length
    resource.invitation_token = params[:invitation_token]
    redirect_to "http://localhost:3001/auth/invitation/accept?invitation_token=#{params[:invitation_token]}"
  end

  def update
    super do |resource|
      if resource.errors.empty?
        render json: { status: "Invitation Accepted!" }, status: 200
      else
        render json: resource.errors, status: 401
      end
    end
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:accept_invitation, keys: [:first_name, :last_name])
  end
end

my routes.rb

Rails.application.routes.draw do
  # Using devise_token_auth for the API
  mount_devise_token_auth_for 'User', at: 'auth',
                                      defaults: { format: :json },
                                      controllers: {
                                        invitations: 'users/invitations'
                                      }
  ...
end

I can see that the following routes exist:

PUT      /auth/invitation(.:format)            devise/invitations#update
POST     /auth/invitation(.:format)            devise/invitations#create

The problem I can see here though is that I'd expect the routes to look like this:

PUT      /auth/invitation(.:format)            users/invitations#update
POST     /auth/invitation(.:format)            users/invitations#create

This behavior might be caused by the devise_token_auth gem, which I'm not sure how to correct.

Again, when I submit this form I'd expect to be able to intercept the create method, so to then call User.invite! on all the users that are listed in the form. I've tried adding a byebug or binding.pry inside the create method but the code doesn't appear to execute, which means it's being bypassed.

The error message I see is:

Processing by Devise::InvitationsController#create as HTML
  Parameters: {"_json"=>[{"email"=>"asd@ad.com", "firstName"=>"Test", "lastName"=>"Last"}], "invitation"=>{"_json"=>[{"email"=>"asd@ad.com", "firstName"=>"Test", "lastName"=>"Last"}]}}
Completed 500 Internal Server Error in 0ms (ActiveRecord: 0.0ms)

ArgumentError (wrong number of arguments (given 1, expected 0)):

Am I not supposed to pass the form data to the devise_invitable's create method? Any help is much appreciated.

Thanks in advance!

Body:
Try changing your routes to

mount_devise_token_auth_for 'User', at: 'auth', skip: [:invitations]

devise_for :users, path: "auth", only: [:invitations],
controllers: { invitations: 'users/invitations' }

For more information you can refer to this article


问:
checked/unchecked checkbox when row selection already selected
My checkbox does not work (Not checked) when I have selected row table.

This is my row selection.

```<code>$('#mainTable tbody').on( 'click', 'tr', function () {
   $(this).toggleClass('selected');
   });
</code>```

I have included handler for checkbox, but no luck.

```<code>"rowCallback": function(row, data, dataIndex){
         var rowId = data[0];

         if($.inArray(rowId, rows_selected) !== -1){
            $(row).find('input[type="checkbox"]').prop('checked', true);
            $(row).addClass('selected');
         }
      }
</code>```

Reference

JSFiddle Demonstration

答:
Use hasClass() to check current selected state and use that to toggle checkbox

```<code>$('#mainTable tbody').on( 'click', 'tr', function () {
        var $row=$(this),
            isSelected = $row.hasClass('selected')
        $row.toggleClass('selected')
            .find(':checkbox').prop('checked', !isSelected);
});
</code>```

Demo

Body:
My checkbox does not work (Not checked) when I have selected row table.

This is my row selection.

$('#mainTable tbody').on( 'click', 'tr', function () {
   $(this).toggleClass('selected');
   });

I have included handler for checkbox, but no luck.

"rowCallback": function(row, data, dataIndex){
         var rowId = data[0];

         if($.inArray(rowId, rows_selected) !== -1){
            $(row).find('input[type="checkbox"]').prop('checked', true);
            $(row).addClass('selected');
         }
      }

Reference

JSFiddle Demonstration

Body:
Use hasClass() to check current selected state and use that to toggle checkbox

$('#mainTable tbody').on( 'click', 'tr', function () {
        var $row=$(this),
            isSelected = $row.hasClass('selected')
        $row.toggleClass('selected')
            .find(':checkbox').prop('checked', !isSelected);
});

Demo


问:
Inserting BLOB data in DB2 using SQL Query
I am stuck into a situation where I need to insert data into a blob column by reading a file from the Filesystem in DB2 (DB2 Express C on Windows 7).

Somewhere on the internet I found this INSERT INTO ... VALUES ( ..., readfile('filename'), ...); but here readfile is not an inbuilt function but I need to create it using UDF (c language libraries), but that might not be a useful solution.

Can somebody update us how to insert BLOB values using Insert command.

答:
First and foremost, per IBM docs all LOB data in DB2 must have the following corresponding items in addition to a LOB column defined in a table. See docs for example CREATE statements.

LOB tablespace (one for every LOB column in each partition)

Auxiliary table on above table space that points to the blob column in base table  (also, one for every LOB column in each partition)

A unique index in auxiliary table

Once this schema is prepared you can then run a LOAD command that can import with other data fields where blob content is referenced by file paths. Below is a demo with an Employees table:

DB Table (example table)

```<code>CREATE TABLE EMPLOYEES (
   ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
   EMPLOYEE_NUMBER INTEGER,
   EMPLOYEE_NAME VARCHAR(255),
   EMPLOYEE_PIC BLOB(500K)
);
</code>```

CSV FILE (comma being default delimiter in LOAD with no headers)

```<code>1234, "John Doe", johndoe.jpg
5678, "Jane Doe", janedoe.jpg
...
</code>```

DB2 LOAD (simple version using defaults for many other LOAD parameters)

```<code>LOAD FROM "/path/to/file.csv"
  OF DEL
  LOBS FROM /path/to/picture/folder/   --PATH OF BLOB FILES WITH BASENAME IN CSV
                                       --MUST END IN FORWARD SLASH
  MODIFIED BY LOBSINFILE CHARDEL""
  DUMPFILE="/path/to/dump.txt"         --FOR FAILED IMPORTS
  METHOD P (1,2,3)                     --NUMBER REFERENCE OF COLS, OR USE N FOR FIELD NAMES
  MESSAGES "/path/to/messages.txt"     --FOR LOAD COMMAND MESSAGES
  REPLACE INTO "EMPLOYEES"             --REMOVES EXISTING FOR IMPORT, OR USE INSERT TO ADD
  (EMPLOYEE_NUMBER
   EMPLOYEE_NAME,
   EMPLOYEE_PIC);
</code>```

Command lines

```<code>> db2 -tvf "/path/to/load_command.sql"

> db2 "SELECT LENGTH(EMPLOYEE_PIC) FROM EMPLOYEES"
</code>```

Body:
First and foremost, per IBM docs all LOB data in DB2 must have the following corresponding items in addition to a LOB column defined in a table. See docs for example CREATE statements.

LOB tablespace (one for every LOB column in each partition)

Auxiliary table on above table space that points to the blob column in base table  (also, one for every LOB column in each partition)

A unique index in auxiliary table

Once this schema is prepared you can then run a LOAD command that can import with other data fields where blob content is referenced by file paths. Below is a demo with an Employees table:

DB Table (example table)

CREATE TABLE EMPLOYEES (
   ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
   EMPLOYEE_NUMBER INTEGER,
   EMPLOYEE_NAME VARCHAR(255),
   EMPLOYEE_PIC BLOB(500K)
);

CSV FILE (comma being default delimiter in LOAD with no headers)

1234, "John Doe", johndoe.jpg
5678, "Jane Doe", janedoe.jpg
...

DB2 LOAD (simple version using defaults for many other LOAD parameters)

LOAD FROM "/path/to/file.csv"
  OF DEL
  LOBS FROM /path/to/picture/folder/   --PATH OF BLOB FILES WITH BASENAME IN CSV
                                       --MUST END IN FORWARD SLASH
  MODIFIED BY LOBSINFILE CHARDEL""
  DUMPFILE="/path/to/dump.txt"         --FOR FAILED IMPORTS
  METHOD P (1,2,3)                     --NUMBER REFERENCE OF COLS, OR USE N FOR FIELD NAMES
  MESSAGES "/path/to/messages.txt"     --FOR LOAD COMMAND MESSAGES
  REPLACE INTO "EMPLOYEES"             --REMOVES EXISTING FOR IMPORT, OR USE INSERT TO ADD
  (EMPLOYEE_NUMBER
   EMPLOYEE_NAME,
   EMPLOYEE_PIC);

Command lines

> db2 -tvf "/path/to/load_command.sql"

> db2 "SELECT LENGTH(EMPLOYEE_PIC) FROM EMPLOYEES"


问:
Selecting an element with different value but similar id
How can you select an  element with value 2 using jQuery, if they all have same name and id?

```<code> <input type="radio" id="store" name="store" value="1">
    <input type="radio" id="store" name="store" value="2">
     <input type="radio" id="store" name="store" value="3">
</code>```

jQuery that didn't work:

```<code>$('#store:input[type="radio", value="2"]').html();
</code>```

答:
jQuery's selector engine can't handle it, but you can use then native querySelector instead, after you fix your selector.

const v = document.querySelector('input#store[type="radio"][value="2"]').outerHTML;

console.log(v);```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <input type="radio" id="store" name="store" value="1">
 <input type="radio" id="store" name="store" value="2">
 <input type="radio" id="store" name="store" value="3"></code>```

querySelector and querySelectorAll don't care about the HTML requirement of unique IDs. They fetch all matches on the page.

Also, .html() didn't make sense for an input, so I printed its .outerHTML instead.

Body:
How can you select an  element with value 2 using jQuery, if they all have same name and id?

 <input type="radio" id="store" name="store" value="1">
    <input type="radio" id="store" name="store" value="2">
     <input type="radio" id="store" name="store" value="3">

jQuery that didn't work:

$('#store:input[type="radio", value="2"]').html();

Body:
jQuery's selector engine can't handle it, but you can use then native querySelector instead, after you fix your selector.

const v = document.querySelector('input#store[type="radio"][value="2"]').outerHTML;

console.log(v);

 <input type="radio" id="store" name="store" value="1">
 <input type="radio" id="store" name="store" value="2">
 <input type="radio" id="store" name="store" value="3">

querySelector and querySelectorAll don't care about the HTML requirement of unique IDs. They fetch all matches on the page.

Also, .html() didn't make sense for an input, so I printed its .outerHTML instead.