func (p *Pager) handleKeyEvent(ev termbox.Event) bool { p.width, p.height = termbox.Size() switch ev.Key { case termbox.KeyCtrlN, termbox.KeyArrowDown, termbox.KeyEnter: p.scrollDown(1) case termbox.KeyCtrlP, termbox.KeyArrowUp: p.scrollUp(1) case termbox.KeyCtrlU: p.scrollUp(int(math.Ceil(float64(p.height) / 2))) case termbox.KeyCtrlD: p.scrollDown(int(math.Ceil(float64(p.height) / 2))) case termbox.KeyCtrlF, termbox.KeySpace, termbox.KeyPgdn: p.scrollDown(max(0, p.height-3)) case termbox.KeyCtrlB, termbox.KeyPgup: p.scrollUp(max(0, p.height-3)) default: switch ev.Ch { case 'j': p.scrollDown(1) case 'k': p.scrollUp(1) case 'g': p.viewX = 0 case 'G': p.viewX = max(0, len(p.lines)-p.height) case 'q': return false } } p.Redraw() return true }
// Round return rounded version of x with prec precision. // // Special cases are: // Round(±0) = ±0 // Round(±Inf) = ±Inf // Round(NaN) = NaN func Round(x float64, prec int, method string) float64 { var rounder float64 maxPrec := 7 // define a max precison to cut float errors if maxPrec < prec { maxPrec = prec } pow := math.Pow(10, float64(prec)) intermed := x * pow _, frac := math.Modf(intermed) switch method { case ROUNDING_UP: if frac >= math.Pow10(-maxPrec) { // Max precision we go, rest is float chaos rounder = math.Ceil(intermed) } else { rounder = math.Floor(intermed) } case ROUNDING_DOWN: rounder = math.Floor(intermed) case ROUNDING_MIDDLE: if frac >= 0.5 { rounder = math.Ceil(intermed) } else { rounder = math.Floor(intermed) } default: rounder = intermed } return rounder / pow }
func (v3 *Vector3) Ceil() *Vector3 { v3.X = math.Ceil(v3.X) v3.Y = math.Ceil(v3.Y) v3.Z = math.Ceil(v3.Z) return v3 }
// GridScale determines what scale should be used on the graph, for // both the X and Y axes func (n *New) GridScale(column string, gridCount float64) float64 { xsort := make([]float64, len(n.Xvalues)) ysort := make([]float64, len(n.Yvalues)) copy(xsort, n.Xvalues) copy(ysort, n.Yvalues) sort.Float64s(xsort) sort.Float64s(ysort) // Courtesy: Stack Overflow microAdjust := func(span, grids float64) float64 { width := (span / (grids - 1)) x := math.Ceil(math.Log10(width) - 1) p := math.Pow(10, x) rspace := math.Ceil(width/p) * p return rspace } switch column { case "X": rangeX := n.DataRange("X") return microAdjust(rangeX, gridCount) case "Y": rangeY := n.DataRange("Y") return microAdjust(rangeY, gridCount) default: return 0 } }
// TestLimiterRedis tests Limiter with Redis store. func TestLimiterRedis(t *testing.T) { rate, err := NewRateFromFormatted("3-M") assert.Nil(t, err) store, err := NewRedisStoreWithOptions( newRedisPool(), StoreOptions{Prefix: "limitertests:redis", MaxRetry: 3}) assert.Nil(t, err) limiter := NewLimiter(store, rate) i := 1 for i <= 5 { ctx, err := limiter.Get("boo") assert.Nil(t, err) if i <= 3 { assert.Equal(t, int64(3), ctx.Limit) assert.Equal(t, int64(3-i), ctx.Remaining) assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60) } else { assert.Equal(t, int64(3), ctx.Limit) assert.True(t, ctx.Remaining == 0) assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60) } i++ } }
func (i *Image) Crop(dst, format string, w, h, q int, optimize bool) error { cw, ch := w, h kc := float64(w) / float64(h) ki := float64(i.Width) / float64(i.Height) if ki > kc { ch = i.Height cw = int(math.Ceil(float64(i.Height) * kc)) } else { cw = i.Width ch = int(math.Ceil(float64(i.Width) / kc)) } crop := fmt.Sprintf("%dx%d+0+0", cw, ch) cmd := exec.Command("convert", i.Filename, "-gravity", "Center", "-crop", crop, dst) res, err := cmd.CombinedOutput() if err != nil { e := parseError(string(res)) if e != "" { err = fmt.Errorf("%s", e) } return err } i.Filename = dst err = i.Resize(dst, format, w, h, q, optimize) if err != nil { return err } i.Width = w i.Height = h return nil }
func (g *group) updateBounds(move bool) { if g.model == nil { return } var w, h float64 x0, y0, x1, y1 := detectBounds(g.model.Items()) if !g.folded { w, h = (x1-x0)+2*GroupMargin, (y1-y0)+2*GroupMargin k := math.Ceil(w / GridDefaultGap) w = k * GridDefaultGap k = math.Ceil(h / GridDefaultGap) h = k * GridDefaultGap } fw, fh := g.getFoldedSize() if w < fw { w = fw } if h < fh { h = fh } if move { x, y := x0-GroupMargin, y0-GroupMargin g.Rect = geometry.NewRect(x, y, w, h) } else { g.Rect.Resize(w, h) } }
// If k == 2 // Solves d + (d - 1) + (d - 2) + (d - 3) + (d - 4) + ... + 1 = n // This comes to d(d + 1) / 2 = n and then to // d ** 2 + d - 2 * n = 0, so we solve this quadratic equoation to get d // If k > 2, we check if it's large enough to do a binary search // If yes, we return the number of drops a binary search requires // If not, we use nFloors. d is the smalles number such that nFloors(d, k) >= n func calcDrops(k, n int, cache *map[complex128]int) (d int) { need2binarySearch := int(math.Ceil(math.Log2(float64(n)))) if k > need2binarySearch { return need2binarySearch } if k == 2 { //fmt.Println(">>>", k - 2, n, k) delta := 1 + 4*2*n floatD := (-1 + math.Sqrt(float64(delta))) / 2 d = int(math.Ceil(floatD)) + (k - 2) return d } // If none the above, search for d such that nFloors(d, k) >= n //fmt.Println("Recurrence") d = 1 for { nf := nFloors(d, k, cache) if nf >= n { return d } d += 1 } }
/* NewSketchForEpsilonDelta ... */ func NewSketchForEpsilonDelta(epsilon, delta float64) (*Sketch, error) { var ( width = uint(math.Ceil(math.E / epsilon)) depth = uint(math.Ceil(math.Log(1 / delta))) ) return NewSketch(width, depth, true, 1.00026, true, true, 16) }
// Round returns a point inside the box, making an effort to round to minimal // precision. func (b Box) Round() (lat, lng float64) { x := maxDecimalPower(b.MaxLat - b.MinLat) lat = math.Ceil(b.MinLat/x) * x x = maxDecimalPower(b.MaxLng - b.MinLng) lng = math.Ceil(b.MinLng/x) * x return }
func (this *ThumbFile) ComputeCrop(original *UploadedFile) (int, int, error) { re := regexp.MustCompile("(.*):(.*)") matches := re.FindStringSubmatch(this.CropRatio) if len(matches) != 3 { return 0, 0, errors.New("Invalid crop_ratio") } wRatio, werr := strconv.ParseFloat(matches[1], 64) hRatio, herr := strconv.ParseFloat(matches[2], 64) if werr != nil || herr != nil { return 0, 0, errors.New("Invalid crop_ratio") } var cropWidth, cropHeight float64 if wRatio >= hRatio { wRatio = wRatio / hRatio hRatio = 1 cropWidth = math.Ceil(float64(this.ComputeHeight(original)) * wRatio) cropHeight = math.Ceil(float64(this.ComputeHeight(original)) * hRatio) } else { hRatio = hRatio / wRatio wRatio = 1 cropWidth = math.Ceil(float64(this.ComputeWidth(original)) * wRatio) cropHeight = math.Ceil(float64(this.ComputeWidth(original)) * hRatio) } return int(cropWidth), int(cropHeight), nil }
/** Used to build a rank directory from the given input string. @param data A javascript string containing the data, as readable using the BitString object. @param numBits The number of bits to index. @param l1Size The number of bits that each entry in the Level 1 table summarizes. This should be a multiple of l2Size. @param l2Size The number of bits that each entry in the Level 2 table summarizes. */ func CreateRankDirectory(data string, numBits, l1Size, l2Size uint) RankDirectory { bits := BitString{} bits.Init(data) var p, i uint = 0, 0 var count1, count2 uint = 0, 0 l1bits := uint(math.Ceil(math.Log2(float64(numBits)))) l2bits := uint(math.Ceil(math.Log2(float64(l1Size)))) directory := BitWriter{} for p+l2Size <= numBits { count2 += bits.Count(p, l2Size) i += l2Size p += l2Size if i == l1Size { count1 += count2 directory.Write(count1, l1bits) count2 = 0 i = 0 } else { directory.Write(count2, l2bits) } } rd := RankDirectory{} rd.Init(directory.GetData(), data, numBits, l1Size, l2Size) return rd }
func (c PngController) drawDistribution(img *image.RGBA, lat, lng, scale float32, zipCodes int) { y := int((180 - (lat + 90)) * scale) x := int((lng + 180) * scale) p := image.Rect(x, y, x+int(math.Ceil(float64(scale))), y+int(math.Ceil(float64(scale)))) var zipColor color.RGBA if zipCodes > 1000 { zipColor = color.RGBA{255, 0, 0, 255} } else if zipCodes > 800 { zipColor = color.RGBA{255, 87, 0, 255} } else if zipCodes > 600 { zipColor = color.RGBA{255, 153, 0, 255} } else if zipCodes > 400 { zipColor = color.RGBA{255, 204, 51, 255} } else if zipCodes > 200 { zipColor = color.RGBA{255, 255, 102, 255} } else if zipCodes > 100 { zipColor = color.RGBA{153, 255, 153, 255} } else if zipCodes > 50 { zipColor = color.RGBA{255, 255, 255, 255} } else { zipColor = color.RGBA{204, 204, 204, 255} } draw.Draw(img, p, &image.Uniform{zipColor}, image.ZP, draw.Src) }
func main() { var N, N1, N2, N3, i, sum float64 N = 1000 N1 = math.Ceil(N / 3.0) N2 = math.Ceil(N / 5.0) N3 = math.Ceil(N / 15.0) sum = 0 i = 1 for i < N1 { sum += 3 * i i++ } i = 1 for i < N2 { sum += 5 * i i++ } // Subtracting double counted numbers (multiples of 15) i = 1 for i < N3 { sum -= 15 * i i++ } fmt.Println(sum) }
func testLimiter(t *testing.T, store Store, rate Rate) { limiter := NewLimiter(store, rate) i := 1 for i <= 5 { if i <= 3 { ctx, err := limiter.Peek("boo") assert.NoError(t, err) assert.Equal(t, int64(3-(i-1)), ctx.Remaining) } ctx, err := limiter.Get("boo") assert.NoError(t, err) if i <= 3 { assert.Equal(t, int64(3), ctx.Limit) assert.Equal(t, int64(3-i), ctx.Remaining) assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60) ctx, err := limiter.Peek("boo") assert.NoError(t, err) assert.Equal(t, int64(3-i), ctx.Remaining) } else { assert.Equal(t, int64(3), ctx.Limit) assert.True(t, ctx.Remaining == 0) assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60) } i++ } }
// Get the size of the blocks depending on input size // We don't want signature much larger than 1024B func getBlockSize(inputsize uint64) uint32 { // Substract version and block size in available size maxSize := MAX_SIG_SIZE - 4 - 4 maxBlocks := math.Ceil(float64(maxSize) / float64(ROLLSUM_SIZE+sha1.Size)) return uint32(math.Ceil(float64(inputsize) / maxBlocks)) }
// Increase window size by factor 1.5 until max window size // (window size grows exponentially) // TODO: use duration until ACK to estimate an ok max window size value func (l *lumberjackClient) tryGrowWindowSize(batchSize int) { if l.windowSize <= batchSize { if l.maxOkWindowSize < l.windowSize { logp.Debug("logstash", "update max ok window size: %v < %v", l.maxOkWindowSize, l.windowSize) l.maxOkWindowSize = l.windowSize newWindowSize := int(math.Ceil(1.5 * float64(l.windowSize))) logp.Debug("logstash", "increase window size to: %v", newWindowSize) if l.windowSize <= batchSize && batchSize < newWindowSize { logp.Debug("logstash", "set to batchSize: %v", batchSize) newWindowSize = batchSize } if newWindowSize > l.maxWindowSize { logp.Debug("logstash", "set to max window size: %v", l.maxWindowSize) newWindowSize = l.maxWindowSize } l.windowSize = newWindowSize } else if l.windowSize < l.maxOkWindowSize { logp.Debug("logstash", "update current window size: %v", l.windowSize) l.windowSize = int(math.Ceil(1.5 * float64(l.windowSize))) if l.windowSize > l.maxOkWindowSize { logp.Debug("logstash", "set to max ok window size: %v", l.maxOkWindowSize) l.windowSize = l.maxOkWindowSize } } } }
func (_ *ItemTests) TTL() { now := time.Now().UnixNano() item1 := &Item{expires: now + int64(time.Second)} item2 := &Item{expires: now - int64(time.Second)} Expect(int(math.Ceil(item1.TTL().Seconds()))).To.Equal(1) Expect(int(math.Ceil(item2.TTL().Seconds()))).To.Equal(-1) }
// Estimate estimates the number needed of nodes of the given shape. func (basicEstimator *BasicNodeEstimator) Estimate(node *apiv1.Node) (int, string) { var buffer bytes.Buffer buffer.WriteString("Needed nodes according to:\n") result := 0 if cpuCapcaity, ok := node.Status.Capacity[apiv1.ResourceCPU]; ok { prop := int(math.Ceil(float64(basicEstimator.cpuSum.MilliValue()) / float64(cpuCapcaity.MilliValue()))) buffer.WriteString(fmt.Sprintf("CPU: %d\n", prop)) result = maxInt(result, prop) } if memCapcaity, ok := node.Status.Capacity[apiv1.ResourceMemory]; ok { prop := int(math.Ceil(float64(basicEstimator.memorySum.Value()) / float64(memCapcaity.Value()))) buffer.WriteString(fmt.Sprintf("Mem: %d\n", prop)) result = maxInt(result, prop) } if podCapcaity, ok := node.Status.Capacity[apiv1.ResourcePods]; ok { prop := int(math.Ceil(float64(basicEstimator.GetCount()) / float64(podCapcaity.Value()))) buffer.WriteString(fmt.Sprintf("Pods: %d\n", prop)) result = maxInt(result, prop) } for port, count := range basicEstimator.portSum { buffer.WriteString(fmt.Sprintf("Port %d: %d\n", port, count)) result = maxInt(result, count) } return result, buffer.String() }
// as reference, this is similar to the opencv one // Sampler func elbp(m *Matrix, pos, radius int) (way uint8) { way = 0 cen := m.e[pos] for n := uint8(0); n < 8; n++ { x := float64(-radius) * math.Sin(math.Pi*float64(n)/4.0) y := float64(radius) * math.Cos(math.Pi*float64(n)/4.0) fx := math.Floor(x) fy := math.Floor(y) cx := math.Ceil(x) cy := math.Ceil(y) // fractional part ty := y - fy tx := x - fx // set interpolation weights w1 := (1.0 - tx) * (1.0 - ty) w2 := tx * (1.0 - ty) w3 := (1.0 - tx) * ty w4 := tx * ty t := w1 * float64(m.e[pos+int(fx)+int(fy)*m.w]) t += w2 * float64(m.e[pos+int(cx)+int(fy)*m.w]) t += w3 * float64(m.e[pos+int(fx)+int(cy)*m.w]) t += w4 * float64(m.e[pos+int(cx)+int(cy)*m.w]) if uint8(t) > cen { way |= 1 << n } } return }
// Increase window size by factor 1.5 until max window size // (window size grows exponentially) // TODO: use duration until ACK to estimate an ok max window size value func (w *window) tryGrowWindow(batchSize int) { windowSize := w.get() if windowSize <= batchSize { if w.maxOkWindowSize < windowSize { debug("update max ok window size: %v < %v", w.maxOkWindowSize, w.windowSize) w.maxOkWindowSize = windowSize newWindowSize := int(math.Ceil(1.5 * float64(windowSize))) debug("increase window size to: %v", newWindowSize) if windowSize <= batchSize && batchSize < newWindowSize { debug("set to batchSize: %v", batchSize) newWindowSize = batchSize } if newWindowSize > w.maxWindowSize { debug("set to max window size: %v", w.maxWindowSize) newWindowSize = int(w.maxWindowSize) } windowSize = newWindowSize } else if windowSize < w.maxOkWindowSize { debug("update current window size: %v", w.windowSize) windowSize = int(math.Ceil(1.5 * float64(windowSize))) if windowSize > w.maxOkWindowSize { debug("set to max ok window size: %v", w.maxOkWindowSize) windowSize = w.maxOkWindowSize } } atomic.StoreInt32(&w.windowSize, int32(windowSize)) } }
func (game *GameInfo) handleTeam(team *Team, wg *sync.WaitGroup) { var temperatureRatio float64 var radiationRatio float64 var energyGain float64 var energyLoss float64 var lifeLoss float64 for team.Life > 0 && game.Running { time.Sleep(1 * time.Second) radiationRatio = (float64)(game.Reading.Radiation-minRadiation) / (float64)(maxRadiation-minRadiation) energyLoss = radiationRatio * maxEnergyLoss if float64(team.Energy)-energyLoss <= 0 { team.Shield = false } if team.Shield { team.Energy = int64(math.Max(float64(team.Energy)-math.Ceil(energyLoss), 0)) log.Printf("Team %s: Energy -%.2f\n", team.Name, energyLoss) continue } radiationRatio = (float64)(game.Reading.Radiation-minRadiation) / (float64)(maxRadiation-minRadiation) lifeLoss = radiationRatio * maxLifeLoss team.Life = int64(math.Max(float64(team.Life)-math.Ceil(lifeLoss), 0)) temperatureRatio = (game.Reading.Temperature - minTemperature) / (maxTemperature - minTemperature) energyGain = temperatureRatio * maxEnergyGain team.Energy = int64(math.Min(float64(team.Energy)+math.Ceil(energyGain), 100)) log.Printf("Team %s: Life -%.2f, Energy +%.2f\n", team.Name, lifeLoss, energyGain) } log.Println("Exiting goroutine for team", team.Name) wg.Done() }
// TestLimiterMemory tests Limiter with memory store. func TestLimiterMemory(t *testing.T) { rate, err := NewRateFromFormatted("3-M") assert.Nil(t, err) store := NewMemoryStoreWithOptions(StoreOptions{ Prefix: "limitertests:memory", CleanUpInterval: 30 * time.Second, }) limiter := NewLimiter(store, rate) i := 1 for i <= 5 { ctx, err := limiter.Get("boo") assert.Nil(t, err) if i <= 3 { assert.Equal(t, int64(3), ctx.Limit) assert.Equal(t, int64(3-i), ctx.Remaining) assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60) } else { assert.Equal(t, int64(3), ctx.Limit) assert.True(t, ctx.Remaining == 0) assert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60) } i++ } }
func (e *Entity) Colliding() bool { playerSize := .5 sx := int(math.Floor(e.x - playerSize/2)) sy := int(math.Floor(e.y - playerSize/2)) sz := int(math.Floor(e.z - playerSize/2)) lx := int(math.Ceil(e.x + playerSize/2)) ly := int(math.Ceil(e.y + playerSize/2)) lz := int(math.Ceil(e.z + playerSize/2)) if sx < 0 || lx >= worldW || sz < 0 || lz >= worldD { return true } if sy < 0 || ly >= worldH { return false } for ix := sx; ix < lx; ix += 1 { for iy := sy; iy < ly; iy += 1 { for iz := sz; iz < lz; iz += 1 { blockType := level[ix][iy][iz] if blockType > 0 { return true } } } } return false }
// Round(3.1556,2)=3.16 // Round(3.1556,0)=3 func Round(val float64, places int) float64 { var t float64 f := math.Pow10(places) x := val * f if math.IsInf(x, 0) || math.IsNaN(x) { return val } if x >= 0.0 { t = math.Ceil(x) if (t - x) > 0.50000000001 { t -= 1.0 } } else { t = math.Ceil(-x) if (t + x) > 0.50000000001 { t -= 1.0 } t = -t } x = t / f if !math.IsInf(x, 0) { return x } return t }
func precomputeWeights(dstSize, srcSize int, filter ResampleFilter) []pweights { du := float64(srcSize) / float64(dstSize) scale := du if scale < 1.0 { scale = 1.0 } ru := math.Ceil(scale * filter.Support) out := make([]pweights, dstSize) for v := 0; v < dstSize; v++ { fu := (float64(v)+0.5)*du - 0.5 startu := int(math.Ceil(fu - ru)) if startu < 0 { startu = 0 } endu := int(math.Floor(fu + ru)) if endu > srcSize-1 { endu = srcSize - 1 } wsum := int32(0) for u := startu; u <= endu; u++ { w := int32(0xff * filter.Kernel((float64(u)-fu)/scale)) if w != 0 { wsum += w out[v].iwpairs = append(out[v].iwpairs, iwpair{u, w}) } } out[v].wsum = wsum } return out }
// RGB2HSB convert RGB color to HSB (HSV) func RGB2HSB(r, g, b int) (int, int, int) { if r+g+b == 0 { return 0, 0, 0 } max := mathutil.Max(mathutil.Max(r, g), b) min := mathutil.Min(mathutil.Min(r, g), b) var ( h int s, bb float64 ) switch max { case min: h = 0 case r: h = (60*(g-b)/(max-min) + 360) % 360 case g: h = (60*(b-r)/(max-min) + 120) case b: h = (60*(r-g)/(max-min) + 240) } bb = math.Ceil((float64(max) / 255.0) * 100.0) if max != 0 { fmax, fmin := float64(max), float64(min) s = math.Ceil(((fmax - fmin) / fmax) * 100.0) } return h, int(s), int(bb) }
func CheckCollision(pb *box, dx, dy float64) (col bool, nx, ny float64) { for x := int(math.Floor(pb.x/tileSize) - 1); x <= int(math.Ceil((pb.x+pb.w)/tileSize)+1); x++ { for y := int(math.Floor(pb.y/tileSize) - 1); y <= int(math.Ceil((pb.y+pb.h)/tileSize)+1); y++ { t := GetTile(x, y) if t.IsSolid() { b := &box{ x: float64(x) * tileSize, y: float64(y) * tileSize, w: tileSize, h: tileSize, } if b.collides(pb) { col = true if dx < 0 { nx = b.x + b.w + 0.001 } else if dx > 0 { nx = b.x - pb.w - 0.001 } if dy < 0 { ny = b.y + b.h + 0.001 } else if dy > 0 { ny = b.y - pb.h - 0.001 } nx /= tileSize ny /= tileSize return } } } } return }
func extractLatencyMetrics(latencies []podLatencyData) LatencyMetric { length := len(latencies) perc50 := latencies[int(math.Ceil(float64(length*50)/100))-1].Latency perc90 := latencies[int(math.Ceil(float64(length*90)/100))-1].Latency perc99 := latencies[int(math.Ceil(float64(length*99)/100))-1].Latency return LatencyMetric{Perc50: perc50, Perc90: perc90, Perc99: perc99} }
func (mw *MapWidget) updateChunkBounds() { startX := int(math.Floor(float64(mw.offX) / tileSize)) startZ := int(math.Floor(float64(mw.offZ) / tileSize)) endX := int(math.Ceil(float64(mw.offX+mw.w) / tileSize)) endZ := int(math.Ceil(float64(mw.offZ+mw.h) / tileSize)) mw.regWrap.SetChunkBounds(startX, startZ, endX, endZ) }