text:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <string.h>
#include <assert.h>

#include "glserver.h"

#define TRUE 1
#define FALSE 0

#define GLSE_SET_COMMAND_PTR(PTR, FUNCNAME) gls_##FUNCNAME##_t *PTR = (gls_##FUNCNAME##_t *)glsec_global.cmd_data;

glse_context_t glsec_global;

static inline void pop_batch_command(size_t size)
{
  glsec_global.tmp_buf.ptr = next_ptr(glsec_global.tmp_buf.ptr, size, GLS_ALIGNMENT_BITS);
}

int send_packet(size_t size)
{
  server_thread_args_t *a = glsec_global.sta;
  if (sendto(a->sock_fd, glsec_global.out_buf.buf, size, 0, (struct sockaddr *)&a->sai, sizeof(struct sockaddr_in)) == -1)
  {
    return FALSE;
  }
  gls_sleep(a->max_mbps, size);
  return TRUE;
}

int glse_cmd_send_data(uint32_t offset, uint32_t size, void *data)
{
  gls_cmd_send_data_t *c = (gls_cmd_send_data_t *)glsec_global.out_buf.buf;
  c->cmd = GLSC_SEND_DATA;

  int success = TRUE;
  uint32_t glssize = GLS_DATA_SIZE * 4;
  char *data1 = (char *)data;
  uint32_t offset1;
  for (offset1 = 0; offset1 < size; offset1 += glssize)
  {
    unsigned int size1 = size - offset1;
    c->isLast = (size1 > glssize) ? FALSE : TRUE;
    size1 = (size1 > glssize) ? glssize : size1;
    memcpy(c->data.data_char, data1, size1);
    size_t sendbytes = (size_t)(&c->data.data_char[size1] - (char *)c);
    c->offset = offset + offset1;
    c->size = size1;
    if (send_packet(sendbytes) == FALSE)
    {
      success = FALSE;
    }
    data1 += glssize;
  }
  return success;
}

void glse_cmd_get_context()
{
  gls_cmd_get_context_t *c = (gls_cmd_get_context_t *)glsec_global.cmd_data;
  graphics_context_t *gc = glsec_global.gc;

  gls_ret_get_context_t *ret = (gls_ret_get_context_t *)glsec_global.tmp_buf.buf;
  ret->cmd = c->cmd;
  ret->screen_width = gc->screen_width;
  ret->screen_height = gc->screen_height;
  size_t size = sizeof(gls_ret_get_context_t);
  glse_cmd_send_data(0, size, glsec_global.tmp_buf.buf);
}

void glse_cmd_flip()
{
  gls_cmd_flip_t *c = (gls_cmd_flip_t *)glsec_global.cmd_data;
  graphics_context_t *gc = glsec_global.gc;
  eglSwapBuffers(gc->display, gc->surface);
  check_gl_err();
  gls_ret_flip_t *ret = (gls_ret_flip_t *)glsec_global.tmp_buf.buf;
  ret->cmd = c->cmd;
  ret->frame = c->frame;
  size_t size = sizeof(gls_ret_flip_t);
  glse_cmd_send_data(0, size, glsec_global.tmp_buf.buf);
}

int glse_cmd_recv_data()
{
  gls_cmd_send_data_t *c = (gls_cmd_send_data_t *)glsec_global.cmd_data;
  if ((c->offset + c->size > glsec_global.tmp_buf.size) || (glsec_global.tmp_buf.size == 0))
  {
    return FALSE;
  }
  memcpy(&glsec_global.tmp_buf.buf[c->offset], c->data.data_char, c->size);
  return TRUE;
}

void glse_glBindBuffer()
{
  GLSE_SET_COMMAND_PTR(c, glBindBuffer);
  glBindBuffer(c->target, c->buffer);
  check_gl_err();
}

void glse_glBindTexture()
{
  GLSE_SET_COMMAND_PTR(c, glBindTexture);
  glBindTexture(c->target, c->texture);
  check_gl_err();
}

void glse_glBlendEquationSeparate()
{
  GLSE_SET_COMMAND_PTR(c, glBlendEquationSeparate);
  glBlendEquationSeparate(c->modeRGB, c->modeAlpha);
  check_gl_err();
}

void glse_glBlendFuncSeparate()
{
  GLSE_SET_COMMAND_PTR(c, glBlendFuncSeparate);
  glBlendFuncSeparate(c->srcRGB, c->dstRGB, c->srcAlpha, c->dstAlpha);
  check_gl_err();
}

void glse_glBufferData()
{
  GLSE_SET_COMMAND_PTR(c,glBufferData );
  glBufferData(c->target, c->size, glsec_global.tmp_buf.buf, c->usage);
  check_gl_err();
}

void glse_glBufferSubData()
{
  GLSE_SET_COMMAND_PTR(c, glBufferSubData);
  glBufferSubData(c->target, c->offset, c->size, glsec_global.tmp_buf.buf);
  check_gl_err();
}

void glse_glClear()
{
  GLSE_SET_COMMAND_PTR(c, glClear);
  glClear(c->mask);
  check_gl_err();
}

void glse_glClearColor()
{
  GLSE_SET_COMMAND_PTR(c, glClearColor);
  glClearColor(c->red, c->green, c->blue, c->alpha);
  check_gl_err();
}

void glse_glDeleteBuffers()
{
  GLSE_SET_COMMAND_PTR(c, glDeleteBuffers);
  glDeleteBuffers (c->n, (GLuint *)glsec_global.tmp_buf.buf);
  check_gl_err();
}

void glse_glDrawArrays()
{
  GLSE_SET_COMMAND_PTR(c, glDrawArrays);
  glDrawArrays(c->mode, c->first, c->count);
  check_gl_err();
}

void glse_glEnable()
{
  GLSE_SET_COMMAND_PTR(c, glEnable);
  glEnable(c->cap);
  check_gl_err();
}

void glse_glGenBuffers()
{
  GLSE_SET_COMMAND_PTR(c, glGenBuffers);
  glGenBuffers(c->n, (GLuint*)glsec_global.tmp_buf.buf);
  check_gl_err();
  uint32_t size = c->n * sizeof(uint32_t);
  glse_cmd_send_data(0, size, (char *)glsec_global.tmp_buf.buf);
}

void glse_glGenTextures()
{
  GLSE_SET_COMMAND_PTR(c, glGenTextures);
  glGenTextures(c->n, (GLuint*)glsec_global.tmp_buf.buf);
  check_gl_err();
  uint32_t size = c->n * sizeof(uint32_t);
  glse_cmd_send_data(0, size, (char *)glsec_global.tmp_buf.buf);
}

void glse_glGetAttribLocation()
{
  GLSE_SET_COMMAND_PTR(c, glGetAttribLocation);
  int index = glGetAttribLocation (c->program, c->name);
  check_gl_err();
  gls_ret_glGetAttribLocation_t *ret = (gls_ret_glGetAttribLocation_t *)glsec_global.tmp_buf.buf;
  ret->cmd = GLSC_glGetAttribLocation;
  ret->index = index;
  glse_cmd_send_data(0, sizeof(gls_ret_glGetAttribLocation_t), (char *)glsec_global.tmp_buf.buf);
}

void glse_glEnableVertexAttribArray()
{
  GLSE_SET_COMMAND_PTR(c,glEnableVertexAttribArray );
  glEnableVertexAttribArray(c->index);
  check_gl_err();
}

void glse_glVertexAttribPointer()
{
  GLSE_SET_COMMAND_PTR(c, glVertexAttribPointer);
  glVertexAttribPointer(c->indx, c->size, c->type, c->normalized, c->stride, (const GLvoid*)c->ptr);
  check_gl_err();
}

void glse_glBindFramebuffer()
{
  GLSE_SET_COMMAND_PTR(c, glBindFramebuffer);
  glBindFramebuffer(c->target, c->framebuffer);
  check_gl_err();
}

void glse_glViewport()
{
  GLSE_SET_COMMAND_PTR(c, glViewport);
  glViewport(c->x, c->y, c->width, c->height);
  check_gl_err();
}

void glse_glUseProgram()
{
GLSE_SET_COMMAND_PTR(c, glUseProgram);
  glUseProgram(c->program);
  check_gl_err();
}

void glse_glCreateShader()
{
  GLSE_SET_COMMAND_PTR(c, glCreateShader);
  uint32_t obj = glCreateShader(c->type);
  check_gl_err();
  gls_ret_glCreateShader_t *ret = (gls_ret_glCreateShader_t *)glsec_global.tmp_buf.buf;
  ret->cmd = GLSC_glCreateShader;
  ret->obj = obj;
  glse_cmd_send_data(0, sizeof(gls_ret_glCreateShader_t), (char *)glsec_global.tmp_buf.buf);
}

void glse_glShaderSource()
{
  GLSE_SET_COMMAND_PTR(c, glShaderSource);
  gls_data_glShaderSource_t *dat = (gls_data_glShaderSource_t *)glsec_global.tmp_buf.buf;
  unsigned int i;
  for (i = 0; i < c->count; i++)
  {
    dat->string[i] = (uint32_t)(dat->data + dat->string[i]);
  }
  glShaderSource(c->shader, c->count, (const GLchar**)dat->string, dat->length);
  check_gl_err();
}

void glse_glCompileShader()
{
  GLSE_SET_COMMAND_PTR(c, glCompileShader);
  glCompileShader(c->shader);
  check_gl_err();
}

void glse_glCreateProgram()
{
  GLuint program = glCreateProgram();
  check_gl_err();
  gls_ret_glCreateProgram_t *ret = (gls_ret_glCreateProgram_t *)glsec_global.tmp_buf.buf;
  ret->cmd = GLSC_glCreateProgram;
  ret->program = program;
  glse_cmd_send_data(0, sizeof(gls_ret_glCreateProgram_t), (char *)glsec_global.tmp_buf.buf);
}

void glse_glAttachShader()
{
  GLSE_SET_COMMAND_PTR(c, glAttachShader);
  glAttachShader(c->program, c->shader);
  check_gl_err();
}

void glse_glLinkProgram()
{
  GLSE_SET_COMMAND_PTR(c, glLinkProgram);
  glLinkProgram(c->program);
  check_gl_err();
}

void glse_glDeleteProgram()
{
  GLSE_SET_COMMAND_PTR(c, glDeleteProgram);
  glDeleteProgram(c->program);
  check_gl_err();
}

void glse_glDeleteShader()
{
  GLSE_SET_COMMAND_PTR(c, glDeleteShader);
  glDeleteShader(c->shader);
  check_gl_err();
}

void glse_glUniform1f()
{
  GLSE_SET_COMMAND_PTR(c, glUniform1f);
  glUniform1f(c->location, c->x);
  check_gl_err();
}

void glse_glDisableVertexAttribArray()
{
  GLSE_SET_COMMAND_PTR(c, glDisableVertexAttribArray);
  glDisableVertexAttribArray(c->index);
  check_gl_err();
}

void glse_glDisable()
{
  GLSE_SET_COMMAND_PTR(c, glDisable);
  glDisable(c->cap);
  check_gl_err();
}

void glse_glDrawElements()
{
  GLSE_SET_COMMAND_PTR(c, glDrawElements);
  glDrawElements (c->mode, c->count, c->type, (const GLvoid*)c->indices);
  check_gl_err();
}

void glse_glGetShaderInfoLog()
{
  GLSE_SET_COMMAND_PTR(c, glGetShaderInfoLog);
  gls_ret_glGetShaderInfoLog_t *ret = (gls_ret_glGetShaderInfoLog_t *)glsec_global.tmp_buf.buf;
  uint32_t maxsize = GLSE_TMP_BUFFER_SIZE - (uint32_t)((char*)ret->infolog - (char*)ret) - 256;
  if (c->bufsize > maxsize)
  {
    c->bufsize = maxsize;
  }
  glGetShaderInfoLog(c->shader, c->bufsize, (GLsizei*)&ret->length, (GLchar*)ret->infolog);
  check_gl_err();
  ret->cmd = GLSC_glGetShaderInfoLog;
  uint32_t size = (uint32_t)((char*)ret->infolog - (char*)ret) + ret->length + 1;
  glse_cmd_send_data(0, size, (char *)glsec_global.tmp_buf.buf);
}

void glse_glBindAttribLocation()
{
  GLSE_SET_COMMAND_PTR(c, glBindAttribLocation);
  glBindAttribLocation (c->program, c->index, c->name);
  check_gl_err();
}

void glse_glGetProgramInfoLog()
{
  GLSE_SET_COMMAND_PTR(c, glGetProgramInfoLog);
  gls_ret_glGetProgramInfoLog_t *ret = (gls_ret_glGetProgramInfoLog_t *)glsec_global.tmp_buf.buf;
  uint32_t maxsize = GLSE_TMP_BUFFER_SIZE - (uint32_t)((char*)ret->infolog - (char*)ret) - 256;
  if (c->bufsize > maxsize)
  {
    c->bufsize = maxsize;
  }
  glGetProgramInfoLog(c->program, c->bufsize, (GLsizei*)&ret->length, (GLchar*)ret->infolog);
  check_gl_err();
  ret->cmd = GLSC_glGetProgramInfoLog;
  uint32_t size = (uint32_t)((char*)ret->infolog - (char*)ret) + ret->length + 1;
  glse_cmd_send_data(0, size, (char *)glsec_global.tmp_buf.buf);
}

void glse_glGetUniformLocation()
{
  GLSE_SET_COMMAND_PTR(c, glGetUniformLocation);
  int location = glGetUniformLocation (c->program, (const GLchar*)c->name);
  check_gl_err();
  gls_ret_glGetUniformLocation_t *ret = (gls_ret_glGetUniformLocation_t *)glsec_global.tmp_buf.buf;
  ret->cmd = GLSC_glGetUniformLocation;
  ret->location = (int32_t)location;
  glse_cmd_send_data(0, sizeof(gls_ret_glGetUniformLocation_t), (char *)glsec_global.tmp_buf.buf);
}

void glse_glUniform4fv()
{
  GLSE_SET_COMMAND_PTR(c, glUniform4fv);
  glUniform4fv (c->location, c->count, (const GLfloat *)c->v);
  check_gl_err();
}

void glse_glUniformMatrix4fv()
{
  GLSE_SET_COMMAND_PTR(c, glUniformMatrix4fv);
  glUniformMatrix4fv(c->location, c->count, c->transpose, (const GLfloat *)c->value);
  check_gl_err();
}

void glse_glFinish()
{
  GLSE_SET_COMMAND_PTR(c, glFinish);
  glFinish();
  check_gl_err();
  gls_command_t *ret = (gls_command_t *)glsec_global.tmp_buf.buf;
  ret->cmd = c->cmd;
  size_t size = sizeof(gls_command_t);
  glse_cmd_send_data(0, size, glsec_global.tmp_buf.buf);
}

void glse_glFlush()
{
  glFlush();
  check_gl_err();
}

void glse_glTexParameteri()
{
  GLSE_SET_COMMAND_PTR(c, glTexParameteri);
  glTexParameteri (c->target, c->pname, c->param);
  check_gl_err();
}

void glse_glTexImage2D()
{
  GLSE_SET_COMMAND_PTR(c, glTexImage2D);
  glTexImage2D(c->target, c->level, c->internalformat, c->width, c->height, c->border, c->format, c->type, c->pixels);
  check_gl_err();
}

void glse_glDeleteTextures()
{
  GLSE_SET_COMMAND_PTR(c, glDeleteTextures);
  glDeleteTextures(c->n, c->textures);
  check_gl_err();
}

void glse_glPixelStorei()
{
  GLSE_SET_COMMAND_PTR(c, glPixelStorei);
  glPixelStorei(c->pname, c->param);
  check_gl_err();
}

void glse_glActiveTexture()
{
  GLSE_SET_COMMAND_PTR(c, glActiveTexture);
  glActiveTexture(c->texture);
  check_gl_err();
}

/*
void glse_()
{
  GLSE_SET_COMMAND_PTR(c, );

  check_gl_err();
}

  gls_ret__t *ret = (gls_ret__t *)glsec_global.tmp_buf.buf;
  ret->cmd = GLSC_;
  ret-> = ;
  glse_cmd_send_data(0, sizeof(gls_ret__t), (char *)glsec_global.tmp_buf.buf);
*/

void glse_cmd_flush()
{
  glsec_global.tmp_buf.ptr = 0;
  int quit = FALSE;
  while (quit == FALSE)
  {
    gls_command_t *c = (gls_command_t *)(glsec_global.tmp_buf.buf + glsec_global.tmp_buf.ptr);
    glsec_global.cmd_data = c;
    switch (c->cmd)
    {
      case GLSC_BREAK:
        quit = TRUE;
        break;
      case GLSC_glAttachShader:
        glse_glAttachShader();
        pop_batch_command(sizeof(gls_glAttachShader_t));
        break;
      case GLSC_glActiveTexture:
        glse_glActiveTexture();
        pop_batch_command(sizeof(gls_glActiveTexture_t));
        break;
      case GLSC_glBindBuffer:
        glse_glBindBuffer();
        pop_batch_command(sizeof(gls_glBindBuffer_t));
        break;
      case GLSC_glBindTexture:
        glse_glBindTexture();
        pop_batch_command(sizeof(gls_glBindTexture_t));
        break;
      case GLSC_glBindAttribLocation:
        glse_glBindAttribLocation();
        pop_batch_command(sizeof(gls_glBindAttribLocation_t));
        break;
      case GLSC_glBindFramebuffer:
        glse_glBindFramebuffer();
        pop_batch_command(sizeof(gls_glBindFramebuffer_t));
        break;
      case GLSC_glBlendFuncSeparate:
        glse_glBlendFuncSeparate();
        pop_batch_command(sizeof(gls_glBlendFuncSeparate_t));
        break;
      case GLSC_glBlendEquationSeparate:
        glse_glBlendEquationSeparate();
        pop_batch_command(sizeof(gls_glBlendEquationSeparate_t));
        break;
      case GLSC_glClear:
        glse_glClear();
        pop_batch_command(sizeof(gls_glClear_t));
        break;
      case GLSC_glClearColor:
        glse_glClearColor();
        pop_batch_command(sizeof(gls_glClearColor_t));
        break;
      case GLSC_glCompileShader:
        glse_glCompileShader();
        pop_batch_command(sizeof(gls_glCompileShader_t));
        break;
      case GLSC_glDeleteProgram:
        glse_glDeleteProgram();
        pop_batch_command(sizeof(gls_glDeleteProgram_t));
        break;
      case GLSC_glDeleteShader:
        glse_glDeleteShader();
        pop_batch_command(sizeof(gls_glDeleteShader_t));
        break;
      case GLSC_glDeleteTextures:
        glse_glDeleteTextures();
        pop_batch_command(((gls_glDeleteTextures_t *)c)->cmd_size);
        break;
      case GLSC_glDisable:
        glse_glDisable();
        pop_batch_command(sizeof(gls_glDisable_t));
        break;
      case GLSC_glDisableVertexAttribArray:
        glse_glDisableVertexAttribArray();
        pop_batch_command(sizeof(gls_glDisableVertexAttribArray_t));
        break;
      case GLSC_glDrawArrays:
        glse_glDrawArrays();
        pop_batch_command(sizeof(gls_glDrawArrays_t));
        break;
      case GLSC_glDrawElements:
        glse_glDrawElements();
        pop_batch_command(sizeof(gls_glDrawElements_t));
        break;
      case GLSC_glEnable:
        glse_glEnable();
        pop_batch_command(sizeof(gls_glEnable_t));
        break;
      case GLSC_glEnableVertexAttribArray:
        glse_glEnableVertexAttribArray();
        pop_batch_command(sizeof(gls_glEnableVertexAttribArray_t));
        break;
      case GLSC_glFlush:
        glse_glFlush();
        pop_batch_command(sizeof(gls_command_t));
        break;
      case GLSC_glLinkProgram:
        glse_glLinkProgram();
        pop_batch_command(sizeof(gls_glLinkProgram_t));
        break;
      case GLSC_glPixelStorei:
        glse_glPixelStorei();
        pop_batch_command(sizeof(gls_glPixelStorei_t));
        break;
      case GLSC_glTexImage2D:
        glse_glTexImage2D();
        pop_batch_command(((gls_glTexImage2D_t *)c)->cmd_size);
        break;
      case GLSC_glTexParameteri:
        glse_glTexParameteri();
        pop_batch_command(sizeof(gls_glTexParameteri_t));
        break;
      case GLSC_glUniform1f:
        glse_glUniform1f();
        pop_batch_command(sizeof(gls_glUniform1f_t));
        break;
      case GLSC_glUniform4fv:
        glse_glUniform4fv();
        pop_batch_command(((gls_glUniform4fv_t *)c)->cmd_size);
        break;
      case GLSC_glUniformMatrix4fv:
        glse_glUniformMatrix4fv();
        pop_batch_command(((gls_glUniformMatrix4fv_t *)c)->cmd_size);
        break;
      case GLSC_glUseProgram:
        glse_glUseProgram();
        pop_batch_command(sizeof(gls_glUseProgram_t));
        break;
      case GLSC_glVertexAttribPointer:
        glse_glVertexAttribPointer();
        pop_batch_command(sizeof(gls_glVertexAttribPointer_t));
        break;
      case GLSC_glViewport:
        glse_glViewport();
        pop_batch_command(sizeof(gls_glViewport_t));
        break;
/*
      case GLSC_:
        glse_();
        pop_batch_command(sizeof(gls__t));
        break;
*/
      default:
        printf("Error: Command Flush\n");
        quit = TRUE;
        break;
    }
  }
}

void * glserver_thread(void * arg)
{
  int quit = FALSE;
  server_thread_args_t * a = (server_thread_args_t *)arg;
  static graphics_context_t gc;
  memset(&glsec_global, 0, sizeof(glsec_global));
  memset(&gc, 0, sizeof(gc));
  init_egl(&gc);

  glsec_global.sta = a;
  glsec_global.gc = &gc;
  glsec_global.tmp_buf.buf = (char *)malloc(GLSE_TMP_BUFFER_SIZE);
  glsec_global.tmp_buf.size = GLSE_TMP_BUFFER_SIZE;
  glsec_global.out_buf.buf = (char *)malloc(GLSE_OUT_BUFFER_SIZE);
  glsec_global.out_buf.size = GLSE_OUT_BUFFER_SIZE;

  while (quit == FALSE)
  {
    void *popptr = (void *)fifo_pop_ptr_get(a->fifo);
    if (popptr == NULL)
    {
      usleep(a->sleep_usec);
    }
    else
    {
      gls_command_t *c = (gls_command_t *)popptr;
      glsec_global.cmd_data = c;
      switch (c->cmd)
      {
        case GLSC_FLIP:
          glse_cmd_flip();
          break;
        case GLSC_SEND_DATA:
          glse_cmd_recv_data();
          break;
        case GLSC_FLUSH:
          glse_cmd_flush();
          break;
        case GLSC_get_context:
          glse_cmd_get_context();
          break;
        case GLSC_glBufferData:
          glse_glBufferData();
          break;
        case GLSC_glBufferSubData:
          glse_glBufferSubData();
          break;
        case GLSC_glCreateProgram:
          glse_glCreateProgram();
          break;
        case GLSC_glCreateShader:
          glse_glCreateShader();
          break;
        case GLSC_glDeleteBuffers:
          glse_glDeleteBuffers();
          break;
        case GLSC_glFinish:
          glse_glFinish();
          break;
        case GLSC_glGenBuffers:
          glse_glGenBuffers();
          break;
        case GLSC_glGenTextures:
          glse_glGenTextures();
          break;
        case GLSC_glGetAttribLocation:
          glse_glGetAttribLocation();
          break;
        case GLSC_glGetProgramInfoLog:
          glse_glGetProgramInfoLog();
          break;
        case GLSC_glGetShaderInfoLog:
          glse_glGetShaderInfoLog();
          break;
        case GLSC_glGetUniformLocation:
          glse_glGetUniformLocation();
          break;
        case GLSC_glShaderSource:
          glse_glShaderSource();
          break;
        default:
          printf("Error: Command\n");
          break;
      }
      fifo_pop_ptr_next(a->fifo);
    }
  }

  release_egl(&gc);

  free(glsec_global.tmp_buf.buf);
  free(glsec_global.out_buf.buf);

  pthread_exit(NULL);
}


text:
var get = require("../getter");

module.exports = {
    pattern: /notes/g,
    handler: function(matches, success, fail){
        var getters = [null, "recreation", "boards", "code", "fire", "council", "districtcourt", "communications", "circuitcourt", "generalservices", "planning", "cityattorney", "cityclerk", "manager", "clerkofcourt", "commattorney", "dchs", "courtservice", "courts", "tes/oeq", "finance", "gis", "health", "historic", "housing", "hr", "humanrights", "technology", "internalaudit", "jdrcourt", "budget", "police", "realestate", "risk", "sheriff", "tes", "elections"]
            .map(get);
        var go = function(){
            var result = {};
            var done = getters.reduce(function(a, b){ return a && b.fill(result); }, true);
            if(done){
                success("application/json", JSON.stringify(result));
            }
        };
        getters.forEach(function(g){ g.retrieve(go, fail);});
    }
};

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace DI\Definition;

/**
 * Factory that decorates a sub-definition.
 *
 * @since 5.0
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class DecoratorDefinition extends FactoryDefinition implements Definition, HasSubDefinition
{
    /**
     * @var Definition
     */
    private $decorated;

    /**
     * @return string
     */
    public function getSubDefinitionName()
    {
        return $this->getName();
    }

    /**
     * @param Definition $definition
     */
    public function setSubDefinition(Definition $definition)
    {
        $this->decorated = $definition;
    }

    /**
     * @return Definition
     */
    public function getDecoratedDefinition()
    {
        return $this->decorated;
    }

    public function __toString()
    {
        return 'Decorate(' . $this->getSubDefinitionName() . ')';
    }
}


text:
class Etcd3Exception(Exception):
    def __init__(self, detail_text=None, *args):
        super(Etcd3Exception, self).__init__(*args)
        self.detail_text = detail_text

class WatchTimedOut(Etcd3Exception):
    pass

class InternalServerError(Etcd3Exception):
    pass

class ConnectionFailedError(Etcd3Exception):
    pass

class ConnectionTimeoutError(Etcd3Exception):
    pass

class PreconditionFailedError(Etcd3Exception):
    pass


text:
import os
import sys

# Work around strptime threading issue, see http://bugs.python.org/issue7980
import time
time.strptime("9/9/2010", "%m/%d/%Y")

def main(args):
    if args[1] in ['test', 'harvest']:
        # Prevent network requests while running unit tests.
        prevent_network_calls()

    from django.core.management import execute_from_command_line
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testsettings")
    execute_from_command_line(args)

def prevent_network_calls():
    import urllib, urllib2
    def no_network_while_testing(*args, **kwargs):
        raise urllib2.URLError('No networking while testing')
    urllib.urlretrieve, urllib.real_urlretrieve = (
        no_network_while_testing, urllib.urlretrieve)
    urllib2.urlopen, urllib2.real_urlopen = (
        no_network_while_testing, urllib2.urlopen)
    urllib2.build_opener, urllib2.real_build_opener = (
        no_network_while_testing, urllib2.build_opener)

if __name__ == "__main__":
    main(sys.argv)


text:
<?php

class ZaphpaTestScopedMiddleware extends Zaphpa\BaseMiddleware {
  function preprocess(&$router) {
    $router->addRoute(array(
      'path'   => '/foo',
      'get'    => array('TestController', 'getTestJsonResponse'),
      'post'   => array('TestController', 'getTestJsonResponse'),
      'put'    => array('TestController', 'getTestJsonResponse'),
      'delete' => array('TestController', 'getTestJsonResponse'),
    ));

    $router->addRoute(array(
      'path'   => '/foo/bar',
      'get'    => array('TestController', 'getTestJsonResponse'),
      'post'   => array('TestController', 'getTestJsonResponse'),
      'put'    => array('TestController', 'getTestJsonResponse'),
      'delete' => array('TestController', 'getTestJsonResponse'),
    ));
  }

  function prerender(&$buffer) {
    $dc = json_decode($buffer[0]);
    $dc->scopeModification = "success";
    $buffer[0] = json_encode($dc);
  }
}


text:
<template id="star-rating">

</template>


text:
package org.skfiy.typhon.rnsd.service.handler;

import org.skfiy.typhon.rnsd.domain.Recharging;

/**
 *
 * @author Kevin Zou <kevinz@skfiy.org>
 */
public class RechargingBO {

    private final Recharging recharging;
    private final String result;

    public RechargingBO(Recharging recharging, String result) {
        this.recharging = recharging;
        this.result = result;
    }

    public Recharging getRecharging() {
        return recharging;
    }

    public String getResult() {
        return result;
    }

}


text:
import os, time, pickle, errno, zipfile

from twisted.python import filepath
from twisted.python.runtime import platform
from twisted.trial import unittest

class AbstractFilePathTestCase(unittest.TestCase):

    f1content = "file 1"
    f2content = "file 2"

    def _mkpath(self, *p):
        x = os.path.abspath(os.path.join(self.cmn, *p))
        self.all.append(x)
        return x

    def subdir(self, *dirname):
        os.mkdir(self._mkpath(*dirname))

    def subfile(self, *dirname):
        return open(self._mkpath(*dirname), "wb")

    def setUp(self):
        self.now = time.time()
        cmn = self.cmn = os.path.abspath(self.mktemp())
        self.all = [cmn]
        os.mkdir(cmn)
        self.subdir("sub1")
        f = self.subfile("file1")
        f.write(self.f1content)
        f = self.subfile("sub1", "file2")
        f.write(self.f2content)
        self.subdir('sub3')
        f = self.subfile("sub3", "file3.ext1")
        f = self.subfile("sub3", "file3.ext2")
        f = self.subfile("sub3", "file3.ext3")
        self.all.sort()

        self.path = filepath.FilePath(cmn)

    def test_segmentsFromPositive(self):
        """
        Verify that the segments between two paths are correctly identified.
        """
        self.assertEquals(
            self.path.child("a").child("b").child("c").segmentsFrom(self.path),
            ["a", "b", "c"])

    def test_segmentsFromNegative(self):
        """Verify that segmentsFrom notices when the ancestor isn't an ancestor.
        """
        self.assertRaises(
            ValueError,
            self.path.child("a").child("b").child("c").segmentsFrom,
                self.path.child("d").child("c").child("e"))

    def test_walk(self):
        """Verify that walking the path gives the same result as the known file
        hierarchy.
        """
        x = [foo.path for foo in self.path.walk()]
        x.sort()
        self.assertEquals(x, self.all)

    def test_validSubdir(self):
        """Verify that a valid subdirectory will show up as a directory, but not as a
        file, not as a symlink, and be listable.
        """
        sub1 = self.path.child('sub1')
        self.failUnless(sub1.exists(),
                        "This directory does exist.")
        self.failUnless(sub1.isdir(),
                        "It's a directory.")
        self.failUnless(not sub1.isfile(),
                        "It's a directory.")
        self.failUnless(not sub1.islink(),
                        "It's a directory.")
        self.failUnlessEqual(sub1.listdir(),
                             ['file2'])

    def test_invalidSubdir(self):
        """
        Verify that a subdirectory that doesn't exist is reported as such.
        """
        sub2 = self.path.child('sub2')
        self.failIf(sub2.exists(),
                    "This directory does not exist.")

    def test_validFiles(self):
        """
        Make sure that we can read existent non-empty files.
        """
        f1 = self.path.child('file1')
        self.failUnlessEqual(f1.open().read(), self.f1content)
        f2 = self.path.child('sub1').child('file2')
        self.failUnlessEqual(f2.open().read(), self.f2content)

def zipit(dirname, zfname):
    """
    create a zipfile on zfname, containing the contents of dirname'
    """
    zf = zipfile.ZipFile(zfname, "w")
    basedir = os.path.basename(dirname)
    for root, dirs, files, in os.walk(dirname):
        for fname in files:
            fspath = os.path.join(root, fname)
            arcpath = os.path.join(root, fname)[len(dirname)+1:]
            # print fspath, '=>', arcpath
            zf.write(fspath, arcpath)
    zf.close()

from twisted.python.zippath import ZipArchive

class ZipFilePathTestCase(AbstractFilePathTestCase):

    def setUp(self):
        AbstractFilePathTestCase.setUp(self)
        zipit(self.cmn, self.cmn+'.zip')
        self.path = ZipArchive(self.cmn+'.zip')
        self.all = [x.replace(self.cmn, self.cmn+'.zip') for x in self.all]

class FilePathTestCase(AbstractFilePathTestCase):

    def test_getAndSet(self):
        content = 'newcontent'
        self.path.child('new').setContent(content)
        newcontent = self.path.child('new').getContent()
        self.failUnlessEqual(content, newcontent)
        content = 'content'
        self.path.child('new').setContent(content, '.tmp')
        newcontent = self.path.child('new').getContent()
        self.failUnlessEqual(content, newcontent)

    def testSymbolicLink(self):
        s4 = self.path.child("sub4")
        s3 = self.path.child("sub3")
        os.symlink(s3.path, s4.path)
        self.failUnless(s4.islink())
        self.failIf(s3.islink())
        self.failUnless(s4.isdir())
        self.failUnless(s3.isdir())

    if not hasattr(os, "symlink"):
        testSymbolicLink.skip = "Your platform does not support symbolic links."

    def testMultiExt(self):
        f3 = self.path.child('sub3').child('file3')
        exts = '.foo','.bar', 'ext1','ext2','ext3'
        self.failIf(f3.siblingExtensionSearch(*exts))
        f3e = f3.siblingExtension(".foo")
        f3e.touch()
        self.failIf(not f3.siblingExtensionSearch(*exts).exists())
        self.failIf(not f3.siblingExtensionSearch('*').exists())
        f3e.remove()
        self.failIf(f3.siblingExtensionSearch(*exts))

    def testPreauthChild(self):
        fp = filepath.FilePath('.')
        fp.preauthChild('foo/bar')
        self.assertRaises(filepath.InsecurePath, fp.child, '/foo')

    def testStatCache(self):
        p = self.path.child('stattest')
        p.touch()
        self.failUnlessEqual(p.getsize(), 0)
        self.failUnlessEqual(abs(p.getmtime() - time.time()) // 20, 0)
        self.failUnlessEqual(abs(p.getctime() - time.time()) // 20, 0)
        self.failUnlessEqual(abs(p.getatime() - time.time()) // 20, 0)
        self.failUnlessEqual(p.exists(), True)
        self.failUnlessEqual(p.exists(), True)
        # OOB removal: FilePath.remove() will automatically restat
        os.remove(p.path)
        # test caching
        self.failUnlessEqual(p.exists(), True)
        p.restat(reraise=False)
        self.failUnlessEqual(p.exists(), False)
        self.failUnlessEqual(p.islink(), False)
        self.failUnlessEqual(p.isdir(), False)
        self.failUnlessEqual(p.isfile(), False)

    def testPersist(self):
        newpath = pickle.loads(pickle.dumps(self.path))
        self.failUnlessEqual(self.path.__class__, newpath.__class__)
        self.failUnlessEqual(self.path.path, newpath.path)

    def testInsecureUNIX(self):
        self.assertRaises(filepath.InsecurePath, self.path.child, "..")
        self.assertRaises(filepath.InsecurePath, self.path.child, "/etc")
        self.assertRaises(filepath.InsecurePath, self.path.child, "../..")

    def testInsecureWin32(self):
        self.assertRaises(filepath.InsecurePath, self.path.child, r"..\..")
        self.assertRaises(filepath.InsecurePath, self.path.child, r"C:randomfile")

    if platform.getType() != 'win32':
        testInsecureWin32.skip = "Consider yourself lucky."

    def testInsecureWin32Whacky(self):
        """Windows has 'special' filenames like NUL and CON and COM1 and LPR
        and PRN and ... god knows what else.  They can be located anywhere in
        the filesystem.  For obvious reasons, we do not wish to normally permit
        access to these.
        """
        self.assertRaises(filepath.InsecurePath, self.path.child, "CON")
        self.assertRaises(filepath.InsecurePath, self.path.child, "C:CON")
        self.assertRaises(filepath.InsecurePath, self.path.child, r"C:\CON")

    if platform.getType() != 'win32':
        testInsecureWin32Whacky.skip = "Consider yourself lucky."

    def testComparison(self):
        self.assertEquals(filepath.FilePath('a'),
                          filepath.FilePath('a'))
        self.failUnless(filepath.FilePath('z') >
                        filepath.FilePath('a'))
        self.failUnless(filepath.FilePath('z') >=
                        filepath.FilePath('a'))
        self.failUnless(filepath.FilePath('a') >=
                        filepath.FilePath('a'))
        self.failUnless(filepath.FilePath('a') <=
                        filepath.FilePath('a'))
        self.failUnless(filepath.FilePath('a') <
                        filepath.FilePath('z'))
        self.failUnless(filepath.FilePath('a') <=
                        filepath.FilePath('z'))
        self.failUnless(filepath.FilePath('a') !=
                        filepath.FilePath('z'))
        self.failUnless(filepath.FilePath('z') !=
                        filepath.FilePath('a'))

        self.failIf(filepath.FilePath('z') !=
                    filepath.FilePath('z'))

    def testSibling(self):
        p = self.path.child('sibling_start')
        ts = p.sibling('sibling_test')
        self.assertEquals(ts.dirname(), p.dirname())
        self.assertEquals(ts.basename(), 'sibling_test')
        ts.createDirectory()
        self.assertIn(ts, self.path.children())

    def testTemporarySibling(self):
        ts = self.path.temporarySibling()
        self.assertEquals(ts.dirname(), self.path.dirname())
        self.assertNotIn(ts.basename(), self.path.listdir())
        ts.createDirectory()
        self.assertIn(ts, self.path.parent().children())

    def testRemove(self):
        self.path.remove()
        self.failIf(self.path.exists())

    def testCopyTo(self):
        self.assertRaises((OSError, IOError), self.path.copyTo, self.path.child('file1'))
        oldPaths = list(self.path.walk()) # Record initial state
        fp = filepath.FilePath(self.mktemp())
        self.path.copyTo(fp)
        self.path.remove()
        fp.copyTo(self.path)
        newPaths = list(self.path.walk()) # Record double-copy state
        newPaths.sort()
        oldPaths.sort()
        self.assertEquals(newPaths, oldPaths)

    def testMoveTo(self):
        self.assertRaises((OSError, IOError), self.path.moveTo, self.path.child('file1'))
        oldPaths = list(self.path.walk()) # Record initial state
        fp = filepath.FilePath(self.mktemp())
        self.path.moveTo(fp)
        fp.moveTo(self.path)
        newPaths = list(self.path.walk()) # Record double-move state
        newPaths.sort()
        oldPaths.sort()
        self.assertEquals(newPaths, oldPaths)

    def testCrossMountMoveTo(self):
        """
        """
        # Bit of a whitebox test - force os.rename, which moveTo tries
        # before falling back to a slower method, to fail, forcing moveTo to
        # use the slower behavior.
        invokedWith = []
        def faultyRename(src, dest):
            invokedWith.append((src, dest))
            if len(invokedWith) == 2:
                raise OSError(errno.EXDEV, 'Test-induced failure simulating cross-device rename failure')
            return originalRename(src, dest)

        originalRename = os.rename
        os.rename = faultyRename
        try:
            self.testMoveTo()
            # A bit of a sanity check for this whitebox test - if our rename
            # was never invoked, the test has probably fallen into
            # disrepair!
            self.failUnless(len(invokedWith) >= 2)
        finally:
            os.rename = originalRename

    def testOpen(self):
        # Opening a file for reading when it does not already exist is an error
        nonexistent = self.path.child('nonexistent')
        e = self.assertRaises(IOError, nonexistent.open)
        self.assertEquals(e.errno, errno.ENOENT)

        # Opening a file for writing when it does not exist is okay
        writer = self.path.child('writer')
        f = writer.open('w')
        f.write('abc\ndef')
        f.close()

        # Make sure those bytes ended up there - and test opening a file for
        # reading when it does exist at the same time
        f = writer.open()
        self.assertEquals(f.read(), 'abc\ndef')
        f.close()

        # Re-opening that file in write mode should erase whatever was there.
        f = writer.open('w')
        f.close()
        f = writer.open()
        self.assertEquals(f.read(), '')
        f.close()

        # Put some bytes in a file so we can test that appending does not
        # destroy them.
        appender = self.path.child('appender')
        f = appender.open('w')
        f.write('abc')
        f.close()

        f = appender.open('a')
        f.write('def')
        f.close()

        f = appender.open('r')
        self.assertEquals(f.read(), 'abcdef')
        f.close()

        # read/write should let us do both without erasing those bytes
        f = appender.open('r+')
        self.assertEquals(f.read(), 'abcdef')
        # ANSI C *requires* an fseek or an fgetpos between an fread and an
        # fwrite or an fwrite and a fread.  We can't reliable get Python to
        # invoke fgetpos, so we seek to a 0 byte offset from the current
        # position instead.  Also, Python sucks for making this seek
        # relative to 1 instead of a symbolic constant representing the
        # current file position.
        f.seek(0, 1)
        # Put in some new bytes for us to test for later.
        f.write('ghi')
        f.close()

        # Make sure those new bytes really showed up
        f = appender.open('r')
        self.assertEquals(f.read(), 'abcdefghi')
        f.close()

        # write/read should let us do both, but erase anything that's there
        # already.
        f = appender.open('w+')
        self.assertEquals(f.read(), '')
        f.seek(0, 1) # Don't forget this!
        f.write('123')
        f.close()

        # super append mode should let us read and write and also position the
        # cursor at the end of the file, without erasing everything.
        f = appender.open('a+')

        # The order of these lines may seem surprising, but it is necessary.
        # The cursor is not at the end of the file until after the first write.
        f.write('456')
        f.seek(0, 1) # Asinine.
        self.assertEquals(f.read(), '')

        f.seek(0, 0)
        self.assertEquals(f.read(), '123456')
        f.close()

        # Opening a file exclusively must fail if that file exists already.
        nonexistent.requireCreate(True)
        nonexistent.open('w').close()
        existent = nonexistent
        del nonexistent
        self.assertRaises((OSError, IOError), existent.open)

from twisted.python import urlpath

class URLPathTestCase(unittest.TestCase):
    def setUp(self):
        self.path = urlpath.URLPath.fromString("http://example.com/foo/bar?yes=no&no=yes#footer")

    def testStringConversion(self):
        self.assertEquals(str(self.path), "http://example.com/foo/bar?yes=no&no=yes#footer")

    def testChildString(self):
        self.assertEquals(str(self.path.child('hello')), "http://example.com/foo/bar/hello")
        self.assertEquals(str(self.path.child('hello').child('')), "http://example.com/foo/bar/hello/")

    def testSiblingString(self):
        self.assertEquals(str(self.path.sibling('baz')), 'http://example.com/foo/baz')

        # The sibling of http://example.com/foo/bar/
        #     is http://example.comf/foo/bar/baz
        # because really we are constructing a sibling of
        # http://example.com/foo/bar/index.html
        self.assertEquals(str(self.path.child('').sibling('baz')), 'http://example.com/foo/bar/baz')

    def testParentString(self):
        # parent should be equivalent to '..'
        # 'foo' is the current directory, '/' is the parent directory
        self.assertEquals(str(self.path.parent()), 'http://example.com/')
        self.assertEquals(str(self.path.child('').parent()), 'http://example.com/foo/')
        self.assertEquals(str(self.path.child('baz').parent()), 'http://example.com/foo/')
        self.assertEquals(str(self.path.parent().parent().parent().parent().parent()), 'http://example.com/')

    def testHereString(self):
        # here should be equivalent to '.'
        self.assertEquals(str(self.path.here()), 'http://example.com/foo/')
        self.assertEquals(str(self.path.child('').here()), 'http://example.com/foo/bar/')


text:
package org.apache.camel.component.resteasy.test;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;
import javax.ws.rs.ext.Provider;

@Provider
public class TestApplication extends Application {
    public Set<Class<?>> getClasses() {
        HashSet<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(TestResource.class);
        return classes;
    }
}


text:
FactoryGirl.define do
  factory :vehicle do
    gigawatt_output_rating 1.5
user nil
service_tier nil
  end

end


text:
package org.kie.builder;

import java.util.Collection;

/**
 * A typed collection for knowledge builder results.
 */
public interface KnowledgeBuilderResults
    extends
    Collection<KnowledgeBuilderResult> {

}


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>CLHS: Condition Type ERROR</TITLE>
<META HTTP-EQUIV="Author" CONTENT="Kent M. Pitman">
<META HTTP-EQUIV="Organization" CONTENT="The Harlequin Group Limited">
<LINK REL=TOP HREF="../FrontMatter/index.html">
<LINK REL=COPYRIGHT HREF="../FrontMatter/About-HyperSpec.html#Legal">
<LINK REL=DISCLAIMER HREF="../FrontMatter/About-HyperSpec.html#Disclaimer">
<LINK REL=PREV HREF="contyp_serious-condition.html">
<LINK REL=UP HREF="sec_the_condi_s_dictionary.html">
<LINK REL=NEXT HREF="contyp_cell-error.html">

Condition Type ERROR

Class Precedence List:

 error, serious-condition, condition, t

Description:

The type error consists of all conditions that represent errors.

Copyright 1996, The Harlequin Group Limited.  All Rights Reserved.


text:
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using UserControl = System.Windows.Forms.UserControl;

namespace VSTOContrib.Core.Wpf
{
    /// <summary>
    /// Windows Forms user control that hosts a WPF user Control.
    /// Includes fix for a redraw issue that is present in Office 2007
    /// </summary>
    [ComVisible(true)]
    [ProgId("Office.Contrib.Wpf.WpfPanelHost")]
    [Guid("59A7E2E3-B0AD-449A-81B9-58398873AC8B")]
    public partial class WpfPanelHost : UserControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WpfPanelHost"/> class.
        /// </summary>
        public WpfPanelHost()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Gets or sets the child WPF user control.
        /// </summary>
        /// <value>The child.</value>
        public UIElement Child
        {
            get
            {
                return elementHost1.Child;
            }
            set
            {
                elementHost1.Child = new ScrollViewer
                {
                    Content = value,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto
                };
                elementHost1.Width++;
                elementHost1.Dock = DockStyle.Fill;
            }
        }
    }
}


text:
FOUNDATION_EXPORT double CJFoundationVersionNumber;
FOUNDATION_EXPORT const unsigned char CJFoundationVersionString[];


text:
"""
Django settings for test_project project.

Generated by 'django-admin startproject' using Django 1.11.8.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

from __future__ import unicode_literals

import os
from logging.handlers import SysLogHandler

from modoboa.test_settings import *  # noqa

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.realpath(os.path.dirname(os.path.dirname(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "w537@nm@5n)=+e%-7*z-jxf21a#0k%uv^rbu**+cj4=_u57e(8"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = "DEBUG" in os.environ

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = [
    "127.0.0.1",
    "localhost",
]

SITE_ID = 1

# Security settings

X_FRAME_OPTIONS = "SAMEORIGIN"

# Application definition

INSTALLED_APPS = (
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.sites",
    "django.contrib.staticfiles",
    "reversion",
    "ckeditor",
    "ckeditor_uploader",
    "rest_framework",
    "rest_framework.authtoken",
    "test_without_migrations",
    "django_otp",
    "django_otp.plugins.otp_totp",
    "django_otp.plugins.otp_static",

)

# A dedicated place to register Modoboa applications
# Do not delete it.
# Do not change the order.
MODOBOA_APPS = (
    "modoboa",
    "modoboa.core",
    "modoboa.lib",
    "modoboa.admin",
    "modoboa.transport",
    "modoboa.relaydomains",
    "modoboa.limits",
    "modoboa.parameters",
    "modoboa.dnstools",
    "modoboa.maillog",
    # Modoboa extensions here.
    "modoboa_postfix_autoreply",
)

INSTALLED_APPS += MODOBOA_APPS

AUTH_USER_MODEL = "core.User"

MIDDLEWARE = (
    "x_forwarded_for.middleware.XForwardedForMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "modoboa.core.middleware.LocalConfigMiddleware",
    "modoboa.lib.middleware.AjaxLoginRedirect",
    "modoboa.lib.middleware.CommonExceptionCatcher",
    "modoboa.lib.middleware.RequestCatcherMiddleware",
)

AUTHENTICATION_BACKENDS = (
    # 'modoboa.lib.authbackends.LDAPBackend',
    # 'modoboa.lib.authbackends.SMTPBackend',
    "django.contrib.auth.backends.ModelBackend",
)

# SMTP authentication
# AUTH_SMTP_SERVER_ADDRESS = 'localhost'
# AUTH_SMTP_SERVER_PORT = 25
# AUTH_SMTP_SECURED_MODE = None  # 'ssl' or 'starttls' are accepted

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.template.context_processors.i18n",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
                "django.template.context_processors.tz",
                "django.contrib.messages.context_processors.messages",
                "modoboa.core.context_processors.top_notifications",
            ],
            "debug": TEMPLATE_DEBUG,
        },
    },
]

ROOT_URLCONF = "test_project.urls"

WSGI_APPLICATION = "test_project.wsgi.application"

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = "/sitestatic/"
STATIC_ROOT = os.path.join(BASE_DIR, "sitestatic")
STATICFILES_DIRS = (
    # os.path.join(BASE_DIR, '..', 'modoboa', 'bower_components'),
)

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

# Rest framework settings

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ),
}

# Modoboa settings
# MODOBOA_CUSTOM_LOGO = os.path.join(MEDIA_URL, "custom_logo.png")

# DOVECOT_LOOKUP_PATH = ('/path/to/dovecot', )

MODOBOA_API_URL = "https://api.modoboa.org/1/"

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",  # NOQA:E501
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",  # NOQA:E501
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",  # NOQA:E501
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",  # NOQA:E501
    },
    {
        "NAME": "modoboa.core.password_validation.ComplexityValidator",
        "OPTIONS": {
            "upper": 1,
            "lower": 1,
            "digits": 1,
            "specials": 0
        }
    },
]

# CKeditor

CKEDITOR_UPLOAD_PATH = "uploads/"

CKEDITOR_IMAGE_BACKEND = "pillow"

CKEDITOR_RESTRICT_BY_USER = True

CKEDITOR_BROWSE_SHOW_DIRS = True

CKEDITOR_ALLOW_NONIMAGE_FILES = False

CKEDITOR_CONFIGS = {
    "default": {
        "allowedContent": True,
        "toolbar": "Modoboa",
        "width": None,
        "toolbar_Modoboa": [
            ["Bold", "Italic", "Underline"],
            ["JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock"],
            ["BidiLtr", "BidiRtl", "Language"],
            ["NumberedList", "BulletedList", "-", "Outdent", "Indent"],
            ["Undo", "Redo"],
            ["Link", "Unlink", "Anchor", "-", "Smiley"],
            ["TextColor", "BGColor", "-", "Source"],
            ["Font", "FontSize"],
            ["Image", ],
            ["SpellChecker"]
        ],
    },
}

# Logging configuration

LOGGING = {
    "version": 1,
    "formatters": {
        "syslog": {
            "format": "%(name)s: %(levelname)s %(message)s"
        },
    },
    "handlers": {
        "syslog-auth": {
            "class": "logging.handlers.SysLogHandler",
            "facility": SysLogHandler.LOG_AUTH,
            "formatter": "syslog"
        },
        "modoboa": {
            "class": "modoboa.core.loggers.SQLHandler",
        }
    },
    "loggers": {
        "modoboa.auth": {
            "handlers": ["syslog-auth", "modoboa"],
            "level": "INFO",
            "propagate": False
        },
        "modoboa.admin": {
            "handlers": ["modoboa"],
            "level": "INFO",
            "propagate": False
        }
    }
}

# Load settings from extensions


text:
/**
 *
 */
import { arraysAreEqual } from '../helpers';
import {
  bytesOrderView,
  difatChainStartView,
  directoryChainLengthView,
  directoryChainStartView,
  fatChainLengthView,
  headerClsidView,
  headerSignatureView,
  initialDifatChainView,
  majorVersionView,
  miniFatChainLengthView,
  miniFatStartView,
  miniSectorCutoffView,
  miniSectorShiftView,
  minorVersionView,
  remainingSpaceView,
  reservedView,
  resetHeaderV3,
  resetHeaderV4,
  sectorShiftView,
} from './dataViews';
import { SectorType } from './enums';

function throwError(message: string): never {
  throw new Error(message);
}

/**
 *
 */
export class Header {
  constructor(private buffer: DataView) {}

  public check(): void | never {
    const version = this.version();
    const bytesOrder = this.bytesOrder();
    const sectorSize = this.sectorSize();
    const { buffer } = this;

    if (
      !arraysAreEqual(this.signature(), [
        0xd0,
        0xcf,
        0x11,
        0xe0,
        0xa1,
        0xb1,
        0x1a,
        0xe1,
      ])
    ) {
      throwError('wrong header signature');
    }
    if (version !== '3.62' && version !== '4.62') {
      throwError('wrong version');
    }
    if (
      !headerClsidView(buffer)
        .get()
        .every((value: number) => value === 0)
    ) {
      throwError('wrong clsid');
    }
    if (bytesOrder !== 0xfffe && bytesOrder !== 0xfeff) {
      throwError('wrong bytes order');
    }
    if (version === '3.62' && sectorSize !== 512) {
      throwError('wrong sector size');
    }
    if (version === '4.62' && sectorSize !== 4096) {
      throwError('wrong sector size');
    }
    if (this.miniSectorSize() !== 64) {
      throwError('wrong minisector size');
    }
    if (
      !reservedView(buffer)
        .get()
        .every((value: number) => value === 0)
    ) {
      throwError('wrong reserved');
    }
    if (version === '3.62' && directoryChainLengthView(buffer).get() !== 0) {
      throwError('wrong directory chain length');
    }
    if (this.miniSectorCutoff() !== 4096) {
      throwError('wrong minisector cutoff');
    }
    if (
      version === '4.62' &&
      !remainingSpaceView(buffer)
        .get()
        .every((value: number) => value === 0)
    ) {
      throwError('wrong remaining space');
    }
    this.checkDifat();
  }

  private checkDifat(): boolean {
    const initialDifat = this.getInitialDifat();
    const numberOfFatSectors = this.getNumberOfFatSectors();
    const endOfInitialDifat = initialDifat.indexOf(SectorType.FREESECT);
    const startOfDifat = this.getStartOfDifat();
    if (endOfInitialDifat === -1) {
      if (startOfDifat === SectorType.ENDOFCHAIN) {
        throwError('wrong start of difat');
      }
      if (
        !initialDifat.every((value: number) => value <= SectorType.MAXREGSECT)
      ) {
        throwError('wrong initial difat');
      }
      if (initialDifat.length >= numberOfFatSectors) {
        throwError('wrong number of fat sectors');
      }

      return true;
    }
    const firstSliceOfInitialDifat = initialDifat.slice(0, endOfInitialDifat);
    const secondSliceOfInitialDifat = initialDifat.slice(endOfInitialDifat);

    if (startOfDifat !== SectorType.ENDOFCHAIN) {
      throwError('wrong start of difat');
    }
    if (
      !firstSliceOfInitialDifat.every(
        (value: number) => value <= SectorType.MAXREGSECT
      ) ||
      !secondSliceOfInitialDifat.every(
        (value: number) => value === SectorType.FREESECT
      )
    ) {
      throwError('wrong initial difat');
    }
    if (firstSliceOfInitialDifat.length !== numberOfFatSectors) {
      throwError('wrong number of fat sectors');
    }

    return true;
  }

  private signature(): number[] {
    return headerSignatureView(this.buffer).get();
  }

  private version(): string {
    return `${majorVersionView(this.buffer).get()}.${minorVersionView(
      this.buffer
    ).get()}`;
  }

  public getStartOfMiniFat(): number {
    return miniFatStartView(this.buffer).get();
  }

  public getStartOfDifat(): number {
    return difatChainStartView(this.buffer).get();
  }

  public getStartOfDirectoryChain(): number {
    return directoryChainStartView(this.buffer).get();
  }

  public getInitialDifat(): number[] {
    return initialDifatChainView(this.buffer).get();
  }

  public miniSectorCutoff(): number {
    return miniSectorCutoffView(this.buffer).get();
  }

  public sectorSize(): number {
    // tslint:disable-next-line:no-bitwise
    return 1 << sectorShiftView(this.buffer).get();
  }

  public getNumberOfFatSectors(): number {
    return fatChainLengthView(this.buffer).get();
  }

  public getDirectoryChainLength(): number {
    return directoryChainLengthView(this.buffer).get();
  }

  public getMiniFatChainLength(): number {
    return miniFatChainLengthView(this.buffer).get();
  }

  public miniSectorSize(): number {
    // tslint:disable-next-line:no-bitwise
    return 1 << miniSectorShiftView(this.buffer).get();
  }

  public bytesOrder(): number {
    return bytesOrderView(this.buffer).get();
  }

  public resetAsV3(): void {
    resetHeaderV3(this.buffer);
  }

  public resetAsV4(): void {
    resetHeaderV4(this.buffer);
  }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title>CodeMirror: HAML mode</title>
    <link rel="stylesheet" href="../../../../web/lib/codeMirror/lib/codemirror.css">

    <link rel="stylesheet" href="../../../../web/lib/codeMirror/doc/docs.css">

CodeMirror: HAML mode

    <form><textarea id="code" name="code">
!!!
#content
.left.column(title="title"){:href => "/hello", :test => "#{hello}_#{world}"}

    %h2 Welcome to our site!
    %p= puts "HAML MODE"
  .right.column
    = render :partial => "sidebar"

.container
  .row
    .span8
      %h1.title= @page_title
%p.title= @page_title
%p
  /
    The same as HTML comment
    Hello multiline comment

  -# haml comment
      This wont be displayed
      nor will this
  Date/Time:
  - now = DateTime.now
  %strong= now
  - if now > DateTime.parse("December 31, 2006")
    = "Happy new " + "year!"

%title
  = @title
  \= @title

Title

    Title

    </textarea></form>

MIME types defined: text/x-haml.

Parsing/Highlighting Tests: normal,  verbose.


text:
package com.uber.m3.tally;

import com.uber.m3.util.Duration;
import com.uber.m3.util.ImmutableMap;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class HistogramImplTest {

    private static final double[] BUCKETS = new double[] {
        1.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 125.0, 150.0, 175.0, 200.0,
        225.0, 250.0, 300.0, 350.0, 400.0, 450.0, 500.0, 550.0, 600.0, 650.0, 700.0, 750.0, 800.0, 850.0, 900.0, 950.0, 1000.0
    };

    private TestStatsReporter reporter;
    private ScopeImpl scope;

    private HistogramImpl histogram;

    @Before
    public void setUp() {
        reporter = new TestStatsReporter();
        scope =
            new ScopeBuilder(null, new ScopeImpl.Registry())
                .reporter(reporter)
                .build();
    }

    @Test
    public void test() {
        histogram = new HistogramImpl(scope, "histogram", ImmutableMap.EMPTY, ValueBuckets.custom(BUCKETS));

        double maxUpperBound = BUCKETS[BUCKETS.length - 1];

        List<Double> values =
                IntStream.range(0, 10000)
                    .mapToDouble(ignored -> Math.random() * (maxUpperBound + 1))
                    .mapToObj(a -> a)
                    .collect(Collectors.toList());

        Map<Double, Long> expected = new HashMap<>();

        for (int i = 0; i < values.size(); ++i) {
            int index = Arrays.binarySearch(BUCKETS, values.get(i));
            double upper;
            if (index >= 0) {
                upper = index + 1 < BUCKETS.length ? BUCKETS[index + 1] : Double.MAX_VALUE;
            } else {
                upper = ~index < BUCKETS.length ? BUCKETS[~index] : Double.MAX_VALUE;
            }

            expected.put(upper, expected.getOrDefault(upper, 0L) + 1);

            ////////////////////////////////////////////////////

            histogram.recordValue(values.get(i));

            if (i % 13 == 0) {
                scope.report(reporter);
            }

        }

        scope.report(reporter);

        assertEquals(reporter.getCumulativeValueSamples(), expected);
    }

    @Test
    public void recordValue() {
        Buckets buckets = ValueBuckets.linear(0, 10, 10);

        histogram =
            new HistogramImpl(
                scope,
            "",
            null,
            buckets
            );

        List<Double> log = new ArrayList<>();

        for (int i = 0; i < 3; i++) {
            double val = Math.random() * 10;
            log.add(val);
            histogram.recordValue(val);
        }

        for (int i = 0; i < 5; i++) {
            double val = 50 + Math.random() * 10;
            log.add(val);
            histogram.recordValue(val);
        }

        // Report will actually be fulfilled through scope
        scope.report(reporter);

        assertEquals(new Long(3L), reporter.getValueSamples().get(10d));
        assertEquals(new Long(5L), reporter.getValueSamples().get(60d));
        assertEquals(buckets, reporter.getBuckets());
    }

    @Test
    public void recordDuration() {
        Buckets buckets = DurationBuckets.linear(Duration.ZERO, Duration.ofMillis(10), 10);

        histogram =
            new HistogramImpl(
                scope,
            "",
            null,
            buckets
            );

        for (int i = 0; i < 3; i++) {
            histogram.recordDuration(Duration.ofMillis(Math.random() * 10));
        }

        for (int i = 0; i < 5; i++) {
            histogram.recordDuration(Duration.ofMillis(50).add(Duration.ofMillis(Math.random() * 10)));
        }

        // Report will actually be fulfilled through scope
        scope.report(reporter);

        assertEquals(new Long(3L), reporter.getDurationSamples().get(Duration.ofMillis(10)));
        assertEquals(new Long(5L), reporter.getDurationSamples().get(Duration.ofMillis(60)));
        assertEquals(buckets, reporter.getBuckets());
    }

    @Test
    public void recordStopwatch() {
        Buckets buckets = DurationBuckets.linear(Duration.ZERO, Duration.ofMillis(10), 10);

        histogram =
            new HistogramImpl(
                scope,
            "",
            null,
            buckets
            );

        Stopwatch stopwatch = histogram.start();
        assertNotNull(stopwatch);
        stopwatch.stop();

        // Report will actually be fulfilled through scope
        scope.report(reporter);

        assertEquals(new Long(1L), reporter.getDurationSamples().get(Duration.ofMillis(10)));
    }

    @Test
    public void snapshotValues() {
        Buckets buckets = ValueBuckets.linear(0, 10, 10);

        histogram =
            new HistogramImpl(
                scope,
            "",
            null,
            buckets
            );

        for (int i = 0; i < 3; i++) {
            histogram.recordValue(Math.random() * 10);
        }

        for (int i = 0; i < 5; i++) {
            histogram.recordValue(50 + Math.random() * 10);
        }

        HashMap<Double, Long> expectedMap = new HashMap<>(buckets.size(), 1);
        expectedMap.put(0d, 0L);
        expectedMap.put(10d, 3L);
        expectedMap.put(20d, 0L);
        expectedMap.put(30d, 0L);
        expectedMap.put(40d, 0L);
        expectedMap.put(50d, 0L);
        expectedMap.put(60d, 5L);
        expectedMap.put(70d, 0L);
        expectedMap.put(80d, 0L);
        expectedMap.put(90d, 0L);
        expectedMap.put(Double.MAX_VALUE, 0L);

        assertEquals(expectedMap, histogram.snapshotValues());
    }

    @Test
    public void snapshotDurations() {
        Buckets buckets = DurationBuckets.linear(Duration.ZERO, Duration.ofMillis(10), 5);

        histogram =
            new HistogramImpl(
                scope,
            "",
            null,
            buckets
            );

        for (int i = 0; i < 3; i++) {
            histogram.recordDuration(Duration.ofMillis(Math.random() * 10));
        }

        for (int i = 0; i < 5; i++) {
            histogram.recordDuration(Duration.ofMillis(50).add(Duration.ofMillis(Math.random() * 10)));
        }

        HashMap<Duration, Long> expectedMap = new HashMap<>(buckets.size(), 1);
        expectedMap.put(Duration.ZERO, 0L);
        expectedMap.put(Duration.ofMillis(10d), 3L);
        expectedMap.put(Duration.ofMillis(20d), 0L);
        expectedMap.put(Duration.ofMillis(30d), 0L);
        expectedMap.put(Duration.ofMillis(40d), 0L);
        expectedMap.put(Duration.MAX_VALUE, 5L);

        assertEquals(expectedMap, histogram.snapshotDurations());
    }
}


text:
delete from table1;
delete from table2;


text:
@interface JCRegisterViewController : UIViewController <UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

@property (strong, nonatomic) IBOutlet UITextField *usernameField;
@property (strong, nonatomic) IBOutlet UITextField *emailField;
@property (strong, nonatomic) IBOutlet UITextField *passwordField;
@property (strong, nonatomic) IBOutlet UITextField *reEnterPasswordField;
@property (strong, nonatomic) IBOutlet UIPickerView *schoolPicker;

@property (strong, nonatomic) NSMutableArray *schoolNameList;

@property (weak, nonatomic) UIButton *registerBtn;

- (IBAction)registerAction:(id)sender;

@end


text:
use std::sync::Arc;
use std::collections::HashSet;

use kailua_env::Pos;
use kailua_diag::{Localize, Localized};
use kailua_syntax::lex::{Tok, Punct, NestedToken};
use kailua_types::ty::{TypeContext, Display, Nil, Functions, Function};
use kailua_check::env::Output;

use protocol::*;
use message as m;
use super::{get_prefix_expr_slot, last_non_comment};

// for the interactivity, the lookbehind is limited to a reasonable number
const LOOKBEHIND_LIMIT: usize = 4096;

// look for the enclosing function call and the argument position of the caret.
// returns the index to the first token of arguments and the argument index, if any.
// the callee would have to seek more to find the end position of the function expression,
// and resolve the function slot from that position to continue.
//
// it seeks for the tokens `(` or `{` preceded by something resembling a function,
// while counting the number of commas *at the nesting opened by that `(` or `{`*.
// the token is considered to be the end of a function if it's `)` or a name;
// otherwise it is a subexpression inside a call and the number of commas is reset to 0.
//
// this should also handle a special case of `) "string"` or `NAME "string"`.
fn enclosing_func_call(tokens: &[NestedToken], pos: Pos) -> Option<(usize, usize)> {
    //            blank                    end of line
    //              |                           |
    //  ( N A M E , _ " s t _ r i n g " _ ) _ _ $
    // 0 1 1 1 1 2 3 3 3 3 3 3 3 3 3 3 4 4 5 5 5 = idx
    let idx = match tokens.binary_search_by(|tok| tok.tok.span.end().cmp(&pos)) {
        Ok(i) => i + 1, // tokens[i].end == pos
        Err(i) => i, // tokens[i-1].end or -inf < pos < tokens[i].end or inf
    };

    // no token before the caret or the caret is strictly inside the first token; no call here
    if idx == 0 { return None; }

    // in the delimited sequence of tokens, the opening token and subsequent tokens are
    // in the same nesting, and the closing token is in the outermost nesting.
    // (this is because each token first updates the nestings and gets assigned its nesting.)
    // therefore the nesting for the caret (between two tokens) should be that of the first.
    let mut last_tok;
    let mut init_depth;
    let mut init_serial;
    if let Some(tok) = tokens.get(idx - 1) {
        last_tok = tok;
        init_depth = tok.depth;
        init_serial = tok.serial;
    } else {
        return None;
    }

    // a special case for `<func> "str"`, which has no nesting changes
    let ptok = if idx > 1 { tokens.get(idx - 2) } else { None };
    match (ptok.map(|tok| &tok.tok.base), &last_tok.tok.base) {
        (Some(&Tok::Name(_)), &Tok::Str(_)) |
        (Some(&Tok::Punct(Punct::RParen)), &Tok::Str(_)) => return Some((idx - 1, 0)),
        (_, _) => {}
    }

    let mut commas = 0;
    for (i, tok) in tokens[..idx - 1].iter().enumerate().rev().take(LOOKBEHIND_LIMIT) {
        let prev_tok = last_tok;
        last_tok = tok;

        if tok.depth <= init_depth && tok.serial != init_serial {
            // escaped the current nesting, the last token should have been the opening token.
            match (&tok.tok.base, &prev_tok.tok.base) {
                (&Tok::Name(_), &Tok::Punct(Punct::LParen)) |
                (&Tok::Punct(Punct::RParen), &Tok::Punct(Punct::LParen)) => {
                    // `tok` is likely the last token of the function expression
                    return Some((i + 1, commas));
                }

                (&Tok::Name(_), &Tok::Punct(Punct::LBrace)) |
                (&Tok::Punct(Punct::RParen), &Tok::Punct(Punct::LBrace)) => {
                    // same as above, but the call is `<func> {...}` which has a single argument
                    return Some((i + 1, 0));
                }

                (_, _) => {
                    // otherwise we move to the parent nesting and reset the # of commas
                    init_depth = tok.depth;
                    init_serial = tok.serial;
                    commas = 0;
                }
            }
        } else if tok.depth > init_depth {
            // ignore more nested tokens (but count them towards the threshold)
            continue;
        }

        if let Tok::Punct(Punct::Comma) = prev_tok.tok.base {
            // the number of commas at the current nesting = the eventual argument index
            // note that we take acount for prev_tok as `a , | b` will start with prev_tok = `,`.
            commas += 1;
        }
    }

    None
}

#[derive(Clone, Debug)]
pub struct Loc {
    pub args_token_idx: usize,
    pub arg_idx: usize,
}

pub fn locate(tokens: &[NestedToken], pos: Pos) -> Option<Loc> {
    enclosing_func_call(tokens, pos).map(|(token_idx, arg_idx)| {
        Loc { args_token_idx: token_idx, arg_idx: arg_idx }
    })
}

pub fn help<F>(tokens: &[NestedToken], loc: &Loc, outputs: &[Arc<Output>],
               mut localize: F) -> Option<SignatureHelp>
    where F: for<'a> FnMut(&'a Localize) -> Localized<'a, Localize>
{
    let empty_signature = || {
        SignatureHelp { signatures: Vec::new(), activeSignature: None, activeParameter: None }
    };

    let (end_idx, end) = if let Some((idx, tok)) = last_non_comment(&tokens[..loc.args_token_idx]) {
        (idx, tok.tok.span.end())
    } else {
        // fail fast, this is not a prefix expression
        return Some(empty_signature());
    };

    // now this is definitely a function, so seek more to determine this is a method call or not.
    // tokens[end_idx] is never a comment, so we are sure that
    // tokens[end_idx] is a name and preceding non-comment token is `:`
    // when this is a method call.
    let mut is_method = false;
    if let Tok::Name(_) = tokens[end_idx].tok.base {
        let prev_tok = last_non_comment(&tokens[..end_idx]).map(|(_, tok)| &tok.tok.base);
        if let Some(&Tok::Punct(Punct::Colon)) = prev_tok {
            is_method = true;
        }
    }

    // for multiple outputs, we deduplicate the identical signatures and
    // determine the (first possible) active signature from the current parameter index.
    let mut signatures = Vec::new();
    let mut seen = HashSet::new();
    let mut active_sig = None;
    let mut param_idx = None;
    for output in outputs {
        let slot = get_prefix_expr_slot(end, output);
        debug!("signature_help: get_prefix_expr_slot({:#?}) returns {:?}", end, slot);

        if let Some(slot) = slot {
            // check if it's a callable function (otherwise we fail fast)
            let ty = if let Some(ty) = output.resolve_exact_type(&slot.unlift()) {
                ty
            } else {
                return Some(empty_signature());
            };

            if ty.nil() == Nil::Noisy {
                // nilable function is not callable
                return Some(empty_signature());
            }

            let func = if let Some(&Functions::Simple(ref func)) = ty.get_functions() {
                func
            } else {
                return Some(empty_signature());
            };

            let (label, params) = format_signature(func, is_method, output, &mut localize);
            let paramlist: Vec<_> = params.iter().map(|param| param.label.clone()).collect();
            if !seen.insert((label.clone(), paramlist)) {
                continue;
            }

            let param_idx_for_sig = if loc.arg_idx < params.len() {
                Some(loc.arg_idx as u32)
            } else if func.args.tail.is_some() {
                // clamp to the number of parameters listed,
                // mapping the last arguments to the variadic position
                assert!(!params.is_empty());
                Some((params.len() - 1) as u32)
            } else {
                // otherwise it's an excess parameter and should not be highlighted
                None
            };

            if param_idx_for_sig.is_some() {
                param_idx = param_idx.or(param_idx_for_sig);
                active_sig = active_sig.or(Some(signatures.len()));
            }

            signatures.push(SignatureInformation {
                label: label,
                documentation: None,
                parameters: params,
            });
        }
    }

    if !signatures.is_empty() {
        Some(SignatureHelp {
            signatures: signatures,
            activeSignature: active_sig.map(|i| i as u32),
            activeParameter: param_idx,
        })
    } else {
        // we will retry for the newer output if there is no slot available
        None
    }
}

fn format_signature<F>(func: &Function, is_method: bool, output: &Output,
                       mut localize: F) -> (String, Vec<ParameterInformation>)
    where F: for<'a> FnMut(&'a Localize) -> Localized<'a, Localize>
{
    use std::fmt::Write;

    // parameters are highlighted in the signature as a string pattern.
    // this is darn wrong especially for Kailua
    // because it fails to highlight, for example, `function(string, string)` correctly.
    // to deal with this, we prefix a series of invisible characters (again) to each parameter.
    fn write_invisible_num(s: &mut String, mut n: usize) {
        s.push('\u{2060}');
        while n > 0 {
            s.push(['\u{200b}', '\u{200c}', '\u{200d}'][n % 3]);
            n /= 3;
        }
    }

    // they should be constructed in a lock step,
    // as matching params in the label are underlined.
    let mut label = format!("{}(", if is_method { "method" } else { "function" });
    let mut params = Vec::new();
    let types = output.types() as &TypeContext;

    let mut first = true;
    let mut names = func.argnames.iter();
    for t in &func.args.head {
        let implicit;
        if first {
            first = false;
            implicit = is_method;
            if implicit {
                let _ = write!(label, "{} ", localize(&m::OmittedSelfLabel {}));
            }
        } else {
            label.push_str(", ");
            implicit = false;
        }

        let mut param = String::new();
        write_invisible_num(&mut param, params.len());
        if let Some(name) = names.next() {
            if let Some(ref name) = *name {
                let _ = write!(param, "{:+}: ", name);
            }
        }
        let _ = write!(param, "{}", localize(&t.display(types)));
        label.push_str(&param);
        if !implicit {
            // implicit parameter is not listed
            params.push(ParameterInformation { label: param, documentation: None });
        }
    }

    if let Some(ref t) = func.args.tail {
        if !first {
            label.push_str(", ");
        }
        let mut param = String::new();
        write_invisible_num(&mut param, params.len());
        let _ = write!(param, "{:#}...", localize(&t.display(types)));
        label.push_str(&param);
        params.push(ParameterInformation { label: param, documentation: None });
    }

    match func.returns {
        Some(ref returns) => match (returns.head.len(), returns.tail.is_some()) {
            (0, false) => {
                label.push_str(")");
            }
            (1, false) => {
                let _ = write!(label, ") --> {}",
                               localize(&returns.head[0].display(types)));
            }
            (_, _) => {
                let _ = write!(label, ") --> {}", localize(&returns.display(types)));
            }
        },
        None => {
            label.push_str(") --> !");
        }
    }

    (label, params)
}


text:
namespace rocksdb {
class DBTestDynamicLevel : public DBTestBase {
 public:
  DBTestDynamicLevel() : DBTestBase("/db_dynamic_level_test") {}
};

TEST_F(DBTestDynamicLevel, DynamicLevelMaxBytesBase) {
  if (!Snappy_Supported() || !LZ4_Supported()) {
    return;
  }
  // Use InMemoryEnv, or it would be too slow.
  unique_ptr<Env> env(new MockEnv(env_));

  const int kNKeys = 1000;
  int keys[kNKeys];

  auto verify_func = [&]() {
    for (int i = 0; i < kNKeys; i++) {
      ASSERT_NE("NOT_FOUND", Get(Key(i)));
      ASSERT_NE("NOT_FOUND", Get(Key(kNKeys * 2 + i)));
      if (i < kNKeys / 10) {
        ASSERT_EQ("NOT_FOUND", Get(Key(kNKeys + keys[i])));
      } else {
        ASSERT_NE("NOT_FOUND", Get(Key(kNKeys + keys[i])));
      }
    }
  };

  Random rnd(301);
  for (int ordered_insert = 0; ordered_insert <= 1; ordered_insert++) {
    for (int i = 0; i < kNKeys; i++) {
      keys[i] = i;
    }
    if (ordered_insert == 0) {
      std::random_shuffle(std::begin(keys), std::end(keys));
    }
    for (int max_background_compactions = 1; max_background_compactions < 4;
         max_background_compactions += 2) {
      Options options;
      options.env = env.get();
      options.create_if_missing = true;
      options.db_write_buffer_size = 2048;
      options.write_buffer_size = 2048;
      options.max_write_buffer_number = 2;
      options.level0_file_num_compaction_trigger = 2;
      options.level0_slowdown_writes_trigger = 2;
      options.level0_stop_writes_trigger = 2;
      options.target_file_size_base = 2048;
      options.level_compaction_dynamic_level_bytes = true;
      options.max_bytes_for_level_base = 10240;
      options.max_bytes_for_level_multiplier = 4;
      options.soft_rate_limit = 1.1;
      options.max_background_compactions = max_background_compactions;
      options.num_levels = 5;

      options.compression_per_level.resize(3);
      options.compression_per_level[0] = kNoCompression;
      options.compression_per_level[1] = kLZ4Compression;
      options.compression_per_level[2] = kSnappyCompression;

      DestroyAndReopen(options);

      for (int i = 0; i < kNKeys; i++) {
        int key = keys[i];
        ASSERT_OK(Put(Key(kNKeys + key), RandomString(&rnd, 102)));
        ASSERT_OK(Put(Key(key), RandomString(&rnd, 102)));
        ASSERT_OK(Put(Key(kNKeys * 2 + key), RandomString(&rnd, 102)));
        ASSERT_OK(Delete(Key(kNKeys + keys[i / 10])));
        env_->SleepForMicroseconds(5000);
      }

      uint64_t int_prop;
      ASSERT_TRUE(db_->GetIntProperty("rocksdb.background-errors", &int_prop));
      ASSERT_EQ(0U, int_prop);

      // Verify DB
      for (int j = 0; j < 2; j++) {
        verify_func();
        if (j == 0) {
          Reopen(options);
        }
      }

      // Test compact range works
      dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
      // All data should be in the last level.
      ColumnFamilyMetaData cf_meta;
      db_->GetColumnFamilyMetaData(&cf_meta);
      ASSERT_EQ(5U, cf_meta.levels.size());
      for (int i = 0; i < 4; i++) {
        ASSERT_EQ(0U, cf_meta.levels[i].files.size());
      }
      ASSERT_GT(cf_meta.levels[4U].files.size(), 0U);
      verify_func();

      Close();
    }
  }

  env_->SetBackgroundThreads(1, Env::LOW);
  env_->SetBackgroundThreads(1, Env::HIGH);
}

// Test specific cases in dynamic max bytes
TEST_F(DBTestDynamicLevel, DynamicLevelMaxBytesBase2) {
  Random rnd(301);
  int kMaxKey = 1000000;

  Options options = CurrentOptions();
  options.create_if_missing = true;
  options.db_write_buffer_size = 204800;
  options.write_buffer_size = 20480;
  options.max_write_buffer_number = 2;
  options.level0_file_num_compaction_trigger = 2;
  options.level0_slowdown_writes_trigger = 9999;
  options.level0_stop_writes_trigger = 9999;
  options.target_file_size_base = 9102;
  options.level_compaction_dynamic_level_bytes = true;
  options.max_bytes_for_level_base = 40960;
  options.max_bytes_for_level_multiplier = 4;
  options.max_background_compactions = 2;
  options.num_levels = 5;
  options.max_compaction_bytes = 0;  // Force not expanding in compactions
  BlockBasedTableOptions table_options;
  table_options.block_size = 1024;
  options.table_factory.reset(NewBlockBasedTableFactory(table_options));

  DestroyAndReopen(options);
  ASSERT_OK(dbfull()->SetOptions({
      {"disable_auto_compactions", "true"},
  }));

  uint64_t int_prop;
  std::string str_prop;

  // Initial base level is the last level
  ASSERT_TRUE(db_->GetIntProperty("rocksdb.base-level", &int_prop));
  ASSERT_EQ(4U, int_prop);

  // Put about 28K to L0
  for (int i = 0; i < 70; i++) {
    ASSERT_OK(Put(Key(static_cast<int>(rnd.Uniform(kMaxKey))),
                  RandomString(&rnd, 380)));
  }
  ASSERT_OK(dbfull()->SetOptions({
      {"disable_auto_compactions", "false"},
  }));
  Flush();
  dbfull()->TEST_WaitForCompact();
  ASSERT_TRUE(db_->GetIntProperty("rocksdb.base-level", &int_prop));
  ASSERT_EQ(4U, int_prop);

  // Insert extra about 28K to L0. After they are compacted to L4, base level
  // should be changed to L3.
  ASSERT_OK(dbfull()->SetOptions({
      {"disable_auto_compactions", "true"},
  }));
  for (int i = 0; i < 70; i++) {
    ASSERT_OK(Put(Key(static_cast<int>(rnd.Uniform(kMaxKey))),
                  RandomString(&rnd, 380)));
  }

  ASSERT_OK(dbfull()->SetOptions({
      {"disable_auto_compactions", "false"},
  }));
  Flush();
  dbfull()->TEST_WaitForCompact();
  ASSERT_TRUE(db_->GetIntProperty("rocksdb.base-level", &int_prop));
  ASSERT_EQ(3U, int_prop);
  ASSERT_TRUE(db_->GetProperty("rocksdb.num-files-at-level1", &str_prop));
  ASSERT_EQ("0", str_prop);
  ASSERT_TRUE(db_->GetProperty("rocksdb.num-files-at-level2", &str_prop));
  ASSERT_EQ("0", str_prop);

  // Trigger parallel compaction, and the first one would change the base
  // level.
  // Hold compaction jobs to make sure
  rocksdb::SyncPoint::GetInstance()->SetCallBack(
      "CompactionJob::Run():Start",
      [&](void* arg) { env_->SleepForMicroseconds(100000); });
  rocksdb::SyncPoint::GetInstance()->EnableProcessing();
  ASSERT_OK(dbfull()->SetOptions({
      {"disable_auto_compactions", "true"},
  }));
  // Write about 40K more
  for (int i = 0; i < 100; i++) {
    ASSERT_OK(Put(Key(static_cast<int>(rnd.Uniform(kMaxKey))),
                  RandomString(&rnd, 380)));
  }
  ASSERT_OK(dbfull()->SetOptions({
      {"disable_auto_compactions", "false"},
  }));
  Flush();
  // Wait for 200 milliseconds before proceeding compactions to make sure two
  // parallel ones are executed.
  env_->SleepForMicroseconds(200000);
  dbfull()->TEST_WaitForCompact();
  ASSERT_TRUE(db_->GetIntProperty("rocksdb.base-level", &int_prop));
  ASSERT_EQ(3U, int_prop);
  rocksdb::SyncPoint::GetInstance()->DisableProcessing();

  // Trigger a condition that the compaction changes base level and L0->Lbase
  // happens at the same time.
  // We try to make last levels' targets to be 40K, 160K, 640K, add triggers
  // another compaction from 40K->160K.
  ASSERT_OK(dbfull()->SetOptions({
      {"disable_auto_compactions", "true"},
  }));
  // Write about 650K more.
  // Each file is about 11KB, with 9KB of data.
  for (int i = 0; i < 1300; i++) {
    ASSERT_OK(Put(Key(static_cast<int>(rnd.Uniform(kMaxKey))),
                  RandomString(&rnd, 380)));
  }
  ASSERT_OK(dbfull()->SetOptions({
      {"disable_auto_compactions", "false"},
  }));
  Flush();
  dbfull()->TEST_WaitForCompact();
  ASSERT_TRUE(db_->GetIntProperty("rocksdb.base-level", &int_prop));
  ASSERT_EQ(2U, int_prop);

  // A manual compaction will trigger the base level to become L2
  // Keep Writing data until base level changed 2->1. There will be L0->L2
  // compaction going on at the same time.
  rocksdb::SyncPoint::GetInstance()->DisableProcessing();
  rocksdb::SyncPoint::GetInstance()->ClearAllCallBacks();

  rocksdb::SyncPoint::GetInstance()->LoadDependency({
      {"CompactionJob::Run():Start", "DynamicLevelMaxBytesBase2:0"},
      {"DynamicLevelMaxBytesBase2:1", "CompactionJob::Run():End"},
      {"DynamicLevelMaxBytesBase2:compact_range_finish",
       "FlushJob::WriteLevel0Table"},
  });
  rocksdb::SyncPoint::GetInstance()->EnableProcessing();

  std::thread thread([this] {
    TEST_SYNC_POINT("DynamicLevelMaxBytesBase2:compact_range_start");
    ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
    TEST_SYNC_POINT("DynamicLevelMaxBytesBase2:compact_range_finish");
  });

  TEST_SYNC_POINT("DynamicLevelMaxBytesBase2:0");
  for (int i = 0; i < 2; i++) {
    ASSERT_OK(Put(Key(static_cast<int>(rnd.Uniform(kMaxKey))),
                  RandomString(&rnd, 380)));
  }
  TEST_SYNC_POINT("DynamicLevelMaxBytesBase2:1");

  Flush();

  thread.join();

  rocksdb::SyncPoint::GetInstance()->DisableProcessing();
  rocksdb::SyncPoint::GetInstance()->ClearAllCallBacks();

  ASSERT_TRUE(db_->GetIntProperty("rocksdb.base-level", &int_prop));
  ASSERT_EQ(1U, int_prop);
}

// Test specific cases in dynamic max bytes
TEST_F(DBTestDynamicLevel, DynamicLevelMaxBytesCompactRange) {
  Random rnd(301);
  int kMaxKey = 1000000;

  Options options = CurrentOptions();
  options.create_if_missing = true;
  options.db_write_buffer_size = 2048;
  options.write_buffer_size = 2048;
  options.max_write_buffer_number = 2;
  options.level0_file_num_compaction_trigger = 2;
  options.level0_slowdown_writes_trigger = 9999;
  options.level0_stop_writes_trigger = 9999;
  options.target_file_size_base = 2;
  options.level_compaction_dynamic_level_bytes = true;
  options.max_bytes_for_level_base = 10240;
  options.max_bytes_for_level_multiplier = 4;
  options.max_background_compactions = 1;
  const int kNumLevels = 5;
  options.num_levels = kNumLevels;
  options.max_compaction_bytes = 1;  // Force not expanding in compactions
  BlockBasedTableOptions table_options;
  table_options.block_size = 1024;
  options.table_factory.reset(NewBlockBasedTableFactory(table_options));

  DestroyAndReopen(options);

  // Compact against empty DB
  dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);

  uint64_t int_prop;
  std::string str_prop;

  // Initial base level is the last level
  ASSERT_TRUE(db_->GetIntProperty("rocksdb.base-level", &int_prop));
  ASSERT_EQ(4U, int_prop);

  // Put about 7K to L0
  for (int i = 0; i < 140; i++) {
    ASSERT_OK(Put(Key(static_cast<int>(rnd.Uniform(kMaxKey))),
                  RandomString(&rnd, 80)));
  }
  Flush();
  dbfull()->TEST_WaitForCompact();
  if (NumTableFilesAtLevel(0) == 0) {
    // Make sure level 0 is not empty
    ASSERT_OK(Put(Key(static_cast<int>(rnd.Uniform(kMaxKey))),
                  RandomString(&rnd, 80)));
    Flush();
  }

  ASSERT_TRUE(db_->GetIntProperty("rocksdb.base-level", &int_prop));
  ASSERT_EQ(3U, int_prop);
  ASSERT_TRUE(db_->GetProperty("rocksdb.num-files-at-level1", &str_prop));
  ASSERT_EQ("0", str_prop);
  ASSERT_TRUE(db_->GetProperty("rocksdb.num-files-at-level2", &str_prop));
  ASSERT_EQ("0", str_prop);

  rocksdb::SyncPoint::GetInstance()->DisableProcessing();
  rocksdb::SyncPoint::GetInstance()->ClearAllCallBacks();

  std::set<int> output_levels;
  rocksdb::SyncPoint::GetInstance()->SetCallBack(
      "CompactionPicker::CompactRange:Return", [&](void* arg) {
        Compaction* compaction = reinterpret_cast<Compaction*>(arg);
        output_levels.insert(compaction->output_level());
      });
  rocksdb::SyncPoint::GetInstance()->EnableProcessing();

  dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
  ASSERT_EQ(output_levels.size(), 2);
  ASSERT_TRUE(output_levels.find(3) != output_levels.end());
  ASSERT_TRUE(output_levels.find(4) != output_levels.end());
  ASSERT_TRUE(db_->GetProperty("rocksdb.num-files-at-level0", &str_prop));
  ASSERT_EQ("0", str_prop);
  ASSERT_TRUE(db_->GetProperty("rocksdb.num-files-at-level3", &str_prop));
  ASSERT_EQ("0", str_prop);
  // Base level is still level 3.
  ASSERT_TRUE(db_->GetIntProperty("rocksdb.base-level", &int_prop));
  ASSERT_EQ(3U, int_prop);
}

TEST_F(DBTestDynamicLevel, DynamicLevelMaxBytesBaseInc) {
  Options options = CurrentOptions();
  options.create_if_missing = true;
  options.db_write_buffer_size = 2048;
  options.write_buffer_size = 2048;
  options.max_write_buffer_number = 2;
  options.level0_file_num_compaction_trigger = 2;
  options.level0_slowdown_writes_trigger = 2;
  options.level0_stop_writes_trigger = 2;
  options.target_file_size_base = 2048;
  options.level_compaction_dynamic_level_bytes = true;
  options.max_bytes_for_level_base = 10240;
  options.max_bytes_for_level_multiplier = 4;
  options.soft_rate_limit = 1.1;
  options.max_background_compactions = 2;
  options.num_levels = 5;

  DestroyAndReopen(options);

  int non_trivial = 0;
  rocksdb::SyncPoint::GetInstance()->SetCallBack(
      "DBImpl::BackgroundCompaction:NonTrivial",
      [&](void* arg) { non_trivial++; });
  rocksdb::SyncPoint::GetInstance()->EnableProcessing();

  Random rnd(301);
  const int total_keys = 3000;
  const int random_part_size = 100;
  for (int i = 0; i < total_keys; i++) {
    std::string value = RandomString(&rnd, random_part_size);
    PutFixed32(&value, static_cast<uint32_t>(i));
    ASSERT_OK(Put(Key(i), value));
  }
  Flush();
  dbfull()->TEST_WaitForCompact();
  rocksdb::SyncPoint::GetInstance()->DisableProcessing();

  ASSERT_EQ(non_trivial, 0);

  for (int i = 0; i < total_keys; i++) {
    std::string value = Get(Key(i));
    ASSERT_EQ(DecodeFixed32(value.c_str() + random_part_size),
              static_cast<uint32_t>(i));
  }

  env_->SetBackgroundThreads(1, Env::LOW);
  env_->SetBackgroundThreads(1, Env::HIGH);
}

TEST_F(DBTestDynamicLevel, MigrateToDynamicLevelMaxBytesBase) {
  Random rnd(301);
  const int kMaxKey = 2000;

  Options options;
  options.create_if_missing = true;
  options.db_write_buffer_size = 2048;
  options.write_buffer_size = 2048;
  options.max_write_buffer_number = 8;
  options.level0_file_num_compaction_trigger = 4;
  options.level0_slowdown_writes_trigger = 4;
  options.level0_stop_writes_trigger = 8;
  options.target_file_size_base = 2048;
  options.level_compaction_dynamic_level_bytes = false;
  options.max_bytes_for_level_base = 10240;
  options.max_bytes_for_level_multiplier = 4;
  options.soft_rate_limit = 1.1;
  options.num_levels = 8;

  DestroyAndReopen(options);

  auto verify_func = [&](int num_keys, bool if_sleep) {
    for (int i = 0; i < num_keys; i++) {
      ASSERT_NE("NOT_FOUND", Get(Key(kMaxKey + i)));
      if (i < num_keys / 10) {
        ASSERT_EQ("NOT_FOUND", Get(Key(i)));
      } else {
        ASSERT_NE("NOT_FOUND", Get(Key(i)));
      }
      if (if_sleep && i % 1000 == 0) {
        // Without it, valgrind may choose not to give another
        // thread a chance to run before finishing the function,
        // causing the test to be extremely slow.
        env_->SleepForMicroseconds(1);
      }
    }
  };

  int total_keys = 1000;
  for (int i = 0; i < total_keys; i++) {
    ASSERT_OK(Put(Key(i), RandomString(&rnd, 102)));
    ASSERT_OK(Put(Key(kMaxKey + i), RandomString(&rnd, 102)));
    ASSERT_OK(Delete(Key(i / 10)));
  }
  verify_func(total_keys, false);
  dbfull()->TEST_WaitForCompact();

  options.level_compaction_dynamic_level_bytes = true;
  options.disable_auto_compactions = true;
  Reopen(options);
  verify_func(total_keys, false);

  std::atomic_bool compaction_finished;
  compaction_finished = false;
  // Issue manual compaction in one thread and still verify DB state
  // in main thread.
  std::thread t([&]() {
    CompactRangeOptions compact_options;
    compact_options.change_level = true;
    compact_options.target_level = options.num_levels - 1;
    dbfull()->CompactRange(compact_options, nullptr, nullptr);
    compaction_finished.store(true);
  });
  do {
    verify_func(total_keys, true);
  } while (!compaction_finished.load());
  t.join();

  ASSERT_OK(dbfull()->SetOptions({
      {"disable_auto_compactions", "false"},
  }));

  int total_keys2 = 2000;
  for (int i = total_keys; i < total_keys2; i++) {
    ASSERT_OK(Put(Key(i), RandomString(&rnd, 102)));
    ASSERT_OK(Put(Key(kMaxKey + i), RandomString(&rnd, 102)));
    ASSERT_OK(Delete(Key(i / 10)));
  }

  verify_func(total_keys2, false);
  dbfull()->TEST_WaitForCompact();
  verify_func(total_keys2, false);

  // Base level is not level 1
  ASSERT_EQ(NumTableFilesAtLevel(1), 0);
  ASSERT_EQ(NumTableFilesAtLevel(2), 0);
}
}  // namespace rocksdb

#endif  // !defined(ROCKSDB_LITE)

int main(int argc, char** argv) {
#if !defined(ROCKSDB_LITE)
  rocksdb::port::InstallStackTraceHandler();
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
#else
  return 0;
#endif
}