util.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2020 gorse Project Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package base
  15. import (
  16. "github.com/zhenghaoz/gorse/base/log"
  17. "go.uber.org/zap"
  18. )
  19. // RangeInt generate a slice [0, ..., n-1].
  20. func RangeInt(n int) []int {
  21. a := make([]int, n)
  22. for i := range a {
  23. a[i] = i
  24. }
  25. return a
  26. }
  27. // RepeatFloat32s repeats value n times.
  28. func RepeatFloat32s(n int, value float32) []float32 {
  29. a := make([]float32, n)
  30. for i := range a {
  31. a[i] = value
  32. }
  33. return a
  34. }
  35. // NewMatrix32 creates a 2D matrix of 32-bit floats.
  36. func NewMatrix32(row, col int) [][]float32 {
  37. ret := make([][]float32, row)
  38. for i := range ret {
  39. ret[i] = make([]float32, col)
  40. }
  41. return ret
  42. }
  43. // NewTensor32 creates a 3D tensor of 32-bit floats.
  44. func NewTensor32(a, b, c int) [][][]float32 {
  45. ret := make([][][]float32, a)
  46. for i := range ret {
  47. ret[i] = NewMatrix32(b, c)
  48. }
  49. return ret
  50. }
  51. // NewMatrixInt creates a 2D matrix of integers.
  52. func NewMatrixInt(row, col int) [][]int {
  53. ret := make([][]int, row)
  54. for i := range ret {
  55. ret[i] = make([]int, col)
  56. }
  57. return ret
  58. }
  59. // CheckPanic catches panic.
  60. func CheckPanic() {
  61. if r := recover(); r != nil {
  62. log.Logger().Error("panic recovered", zap.Any("panic", r))
  63. }
  64. }