jiahuimbzuai/CoQuIR huggingface dataset:
// dofile [c]
void dofile(char *fname)
{
	unsigned long  p; 
	int i, num_pages;
	int fd;

	unsigned char *map;
	off_t fsize;

	if(notregular(fname))
		return;

	printf("%s: ",fname);
	fflush(stdout);

	if((fd=open(fname,O_RDONLY,0))<0)
	{
		error("%s\n",strerror(errno));
		return;
	}

	fsize=filesize(fd);

	if(!fsize)
	{
		printf("empty\n");
		close(fd);
		return;
        }

	p=(unsigned long)mmap(0, fsize, PROT_READ, MAP_SHARED, fd,0);
	
	if(p==-1) {
		error("mmap returned error: %s\n",strerror(errno));
		return;
	}
	
	if(p%page_size) 
		die("mmap returned non-aligned pointer, don't know how to handle, exiting\n");
	
	num_pages=(fsize+page_size-1)/page_size;
	total_pages+=num_pages;
	
	if(!(map=malloc(num_pages))) 
		die("unable to allocate memory: %s",strerror(errno));

	
	if(mincore((void *)((p+~page_mask)&page_mask),(size_t)num_pages*(size_t)page_size, map))
		die("kernel returned: %s\n",strerror(errno));
		

	if(do_totals)
		for(i=0;i<num_pages;i++)
			if(map[i]&1)
				total_cached++;


	if(do_dump) {
		for(i=0;i<num_pages;i++) {
			printf("%c",(map[i]&1) ? 'X' : '.');
		}
		
		printf("\n");
	}
	else if(do_stats) {
		int num_incore=0;
		for(i=0;i<num_pages;i++) {
			if(map[i]&1)
				num_incore++;
		}
		
		printf("%u pages, %u pages cached (%.2f%%)\n",
		       num_pages,
		       num_incore,
		       num_pages ? (num_incore*100.00)/num_pages : 0);
	}
	else if(do_bar)
	{
		int width=80-strlen(fname)-4;
		double leap;
		int num_incore=0;
		int last_pos=-1;
		int leap_pages=0;

		if(num_pages<width)
			leap=1;
		else
			leap=1.0*num_pages/width;

		for(i=0;i<num_pages;i++) {
			if(map[i]&1)
				num_incore++;

			leap_pages++;

			if((int)(i/leap)>last_pos) {
				int proc=3.0*num_incore/leap_pages;
				char c;

				last_pos=i/leap;

				switch(proc) {
				case 0: c='.';break;
				case 1: c='_';break;
				case 2: c='-';break;
				case 3: c='X';break;
				}
				
				printf("%c",c);
				num_incore=leap_pages=0;
			}

			
		}
		printf("\n");
		
	}
	munmap((void *)p, num_pages*page_size);
	close(fd);

}
// dofile [c]
void dofile(char *fname)
{
	unsigned long  p; 
	int i, num_pages;
	int fd;

	unsigned char *map;
	off_t fsize;

	if(notregular(fname))
		return;

	printf("%s: ",fname);
	fflush(stdout);

	if((fd=open(fname,O_RDONLY,0))<0)
	{
		error("%s\n",strerror(errno));
		return;
	}

	fsize=filesize(fd);

	p=(unsigned long)mmap(0, fsize, PROT_READ, MAP_SHARED, fd,0);
	
	if(p==-1) {
		error("mmap returned error: %s\n",strerror(errno));
		return;
	}
	
	if(p%page_size) 
		die("mmap returned non-aligned pointer, don't know how to handle, exiting\n");
	
	num_pages=(fsize+page_size-1)/page_size;
	total_pages+=num_pages;
	
	if(!(map=malloc(num_pages))) 
		die("unable to allocate memory: %s",strerror(errno));

	
	if(mincore((void *)((p+~page_mask)&page_mask),num_pages*page_size, map)) 
		die("kernel returned: %s\n",strerror(errno));
		

	if(do_totals)
		for(i=0;i<num_pages;i++)
			if(map[i]&1)
				total_cached++;


	if(do_dump) {
		for(i=0;i<num_pages;i++) {
			printf("%c",(map[i]&1) ? 'X' : '.');
		}
		
		printf("\n");
	}
	else if(do_stats) {
		int num_incore=0;
		for(i=0;i<num_pages;i++) {
			if(map[i]&1)
				num_incore++;
		}
		
		printf("%u pages, %u pages cached (%.2f%%)\n",
		       num_pages,
		       num_incore,
		       num_pages ? (num_incore*100.00)/num_pages : 0);
	}
	else if(do_bar)
	{
		int width=80-strlen(fname)-4;
		double leap;
		int num_incore=0;
		int last_pos=-1;
		int leap_pages=0;

		if(num_pages<width)
			leap=1;
		else
			leap=1.0*num_pages/width;

		for(i=0;i<num_pages;i++) {
			if(map[i]&1)
				num_incore++;

			leap_pages++;

			if((int)(i/leap)>last_pos) {
				int proc=3.0*num_incore/leap_pages;
				char c;

				last_pos=i/leap;

				switch(proc) {
				case 0: c='.';break;
				case 1: c='_';break;
				case 2: c='-';break;
				case 3: c='X';break;
				}
				
				printf("%c",c);
				num_incore=leap_pages=0;
			}

			
		}
		printf("\n");
		
	}
	munmap((void *)p, num_pages*page_size);
	close(fd);

}
// TestDateSetters [go]
func TestDateSetters(t *testing.T) {
	const SCRIPT = `
	assert.sameValue((new Date(0)).setMilliseconds(2345), 2345, "setMilliseconds(2345)");
	assert.sameValue(new Date(1000).setMilliseconds(23450000000000), 23450000001000, "setMilliseconds(23450000000000)");
	assert.sameValue((new Date(0)).setUTCMilliseconds(2345), 2345, "setUTCMilliseconds()");
	assert.sameValue((new Date(0)).setSeconds(12), 12000, "setSeconds()");
	assert.sameValue((new Date(0)).setUTCSeconds(12), 12000, "setUTCSeconds()");
	assert.sameValue((new Date(0)).setMinutes(12), 12 * 60 * 1000, "setMinutes()");
	assert.sameValue((new Date(0)).setUTCMinutes(12), 12 * 60 * 1000, "setUTCMinutes()");
	assert.sameValue((new Date("2016-06-01")).setHours(1), 1464739200000, "setHours()");
	assert.sameValue((new Date("2016-06-01")).setUTCHours(1), 1464742800000, "setUTCHours()");
	assert.sameValue((new Date(0)).setDate(2), 86400000, "setDate()");
	assert.sameValue((new Date(0)).setUTCDate(2), 86400000, "setUTCDate()");
	assert.sameValue((new Date(0)).setMonth(2), 5097600000, "setMonth()");
	assert.sameValue((new Date(0)).setUTCMonth(2), 5097600000, "setUTCMonth()");
	assert.sameValue((new Date(0)).setFullYear(1971), 31536000000, "setFullYear()");
	assert.sameValue((new Date(0)).setFullYear(1971, 2, 3), 36806400000, "setFullYear(Y,M,D)");
	assert.sameValue((new Date(0)).setUTCFullYear(1971), 31536000000, "setUTCFullYear()");
	assert.sameValue((new Date(0)).setUTCFullYear(1971, 2, 3), 36806400000, "setUTCFullYear(Y,M,D)");

	var d = new Date();
	d.setTime(1151877845000);
	assert.sameValue(d.getHours(), 23, "d.getHours()");
	`

	l := time.Local
	defer func() {
		time.Local = l
	}()
	var err error
	time.Local, err = time.LoadLocation("Europe/London")
	if err != nil {
		t.Fatal(err)
	}

	testScript1(TESTLIB+SCRIPT, _undefined, t)
}
// TestDateSetters [go]
func TestDateSetters(t *testing.T) {
	const SCRIPT = `
	assert.sameValue((new Date(0)).setMilliseconds(2345), 2345, "setMilliseconds()");
	assert.sameValue((new Date(0)).setUTCMilliseconds(2345), 2345, "setUTCMilliseconds()");
	assert.sameValue((new Date(0)).setSeconds(12), 12000, "setSeconds()");
	assert.sameValue((new Date(0)).setUTCSeconds(12), 12000, "setUTCSeconds()");
	assert.sameValue((new Date(0)).setMinutes(12), 12 * 60 * 1000, "setMinutes()");
	assert.sameValue((new Date(0)).setUTCMinutes(12), 12 * 60 * 1000, "setUTCMinutes()");
	assert.sameValue((new Date("2016-06-01")).setHours(1), 1464739200000, "setHours()");
	assert.sameValue((new Date("2016-06-01")).setUTCHours(1), 1464742800000, "setUTCHours()");
	assert.sameValue((new Date(0)).setDate(2), 86400000, "setDate()");
	assert.sameValue((new Date(0)).setUTCDate(2), 86400000, "setUTCDate()");
	assert.sameValue((new Date(0)).setMonth(2), 5097600000, "setMonth()");
	assert.sameValue((new Date(0)).setUTCMonth(2), 5097600000, "setUTCMonth()");
	assert.sameValue((new Date(0)).setFullYear(1971), 31536000000, "setFullYear()");
	assert.sameValue((new Date(0)).setFullYear(1971, 2, 3), 36806400000, "setFullYear(Y,M,D)");
	assert.sameValue((new Date(0)).setUTCFullYear(1971), 31536000000, "setUTCFullYear()");
	assert.sameValue((new Date(0)).setUTCFullYear(1971, 2, 3), 36806400000, "setUTCFullYear(Y,M,D)");

	`

	l := time.Local
	defer func() {
		time.Local = l
	}()
	var err error
	time.Local, err = time.LoadLocation("Europe/London")
	if err != nil {
		t.Fatal(err)
	}

	testScript1(TESTLIB+SCRIPT, _undefined, t)
}
// GetAvailablePort [go]
func GetAvailablePort(t *testing.T) uint16 {
	// Retry has been added for windows as net.Listen can return a port that is not actually available. Details can be
	// found in https://github.com/docker/for-win/issues/3171 but to summarize Hyper-V will reserve ranges of ports
	// which do not show up under the "netstat -ano" but can only be found by
	// "netsh interface ipv4 show excludedportrange protocol=tcp".  We'll use []exclusions to hold those ranges and
	// retry if the port returned by GetAvailableLocalAddress falls in one of those them.
	var exclusions []portpair
	portFound := false
	var port string
	var err error
	if runtime.GOOS == "windows" {
		exclusions = getExclusionsList(t)
	}

	for !portFound {
		endpoint := GetAvailableLocalAddress(t)
		_, port, err = net.SplitHostPort(endpoint)
		require.NoError(t, err)
		portFound = true
		if runtime.GOOS == "windows" {
			for _, pair := range exclusions {
				if port >= pair.first && port <= pair.last {
					portFound = false
					break
				}
			}
		}
	}

	portInt, err := strconv.ParseUint(port, 10, 16)
	require.NoError(t, err)

	return uint16(portInt)
}
// GetAvailablePort [go]
func GetAvailablePort(t *testing.T) uint16 {
	// Retry has been added for windows as net.Listen can return a port that is not actually available. Details can be
	// found in https://github.com/docker/for-win/issues/3171 but to summarize Hyper-V will reserve ranges of ports
	// which do not show up under the "netstat -ano" but can only be found by
	// "netsh interface ipv4 show excludedportrange protocol=tcp".  We'll use []exclusions to hold those ranges and
	// retry if the port returned by GetAvailableLocalAddress falls in one of those them.
	var exclusions []portpair
	portFound := false
	var port string
	var err error
	if runtime.GOOS == "windows" {
		exclusions = getExclusionsList(t)
	}

	for !portFound {
		endpoint := GetAvailableLocalAddress(t)
		_, port, err = net.SplitHostPort(endpoint)
		require.NoError(t, err)
		portFound = true
		if runtime.GOOS == "windows" {
			for _, pair := range exclusions {
				if port >= pair.first && port <= pair.last {
					portFound = false
					break
				}
			}
		}
	}

	portInt, err := strconv.Atoi(port)
	require.NoError(t, err)

	return uint16(portInt)
}
// string [go]
	ord := func(n int64) string {
		switch {
		case n%100 >= 11 && n%100 <= 13:
			return "th"
		case n%10 == 1:
			return "st"
		case n%10 == 2:
			return "nd"
		case n%10 == 3:
			return "rd"
		}
		return "th"
	}
// string [go]
	ord := func(n int) string {
		switch {
		case n%100 >= 11 && n%100 <= 13:
			return "th"
		case n%10 == 1:
			return "st"
		case n%10 == 2:
			return "nd"
		case n%10 == 3:
			return "rd"
		}
		return "th"
	}
// ComputeMAC [go]
func (m *wrappedMAC) ComputeMAC(data []byte) ([]byte, error) {
	primary := m.ps.Primary
	primitive, ok := (primary.Primitive).(tink.MAC)
	if !ok {
		return nil, fmt.Errorf("mac_factory: not a MAC primitive")
	}
	if m.ps.Primary.PrefixType == tinkpb.OutputPrefixType_LEGACY {
		d := data
		if len(d) >= maxInt {
			return nil, fmt.Errorf("mac_factory: data too long")
		}
		data = make([]byte, 0, len(d)+1)
		data = append(data, d...)
		data = append(data, byte(0))
	}
	mac, err := primitive.ComputeMAC(data)
	if err != nil {
		return nil, err
	}
	return append([]byte(primary.Prefix), mac...), nil
}
// ComputeMAC [go]
func (m *wrappedMAC) ComputeMAC(data []byte) ([]byte, error) {
	primary := m.ps.Primary
	primitive, ok := (primary.Primitive).(tink.MAC)
	if !ok {
		return nil, fmt.Errorf("mac_factory: not a MAC primitive")
	}
	if m.ps.Primary.PrefixType == tinkpb.OutputPrefixType_LEGACY {
		d := data
		if len(d) == maxInt {
			return nil, fmt.Errorf("mac_factory: data too long")
		}
		data = make([]byte, 0, len(d)+1)
		data = append(data, d...)
		data = append(data, byte(0))
	}
	mac, err := primitive.ComputeMAC(data)
	if err != nil {
		return nil, err
	}
	return append([]byte(primary.Prefix), mac...), nil
}
// dateproto_setMilliseconds [go]
func (r *Runtime) dateproto_setMilliseconds(call FunctionCall) Value {
	obj := r.toObject(call.This)
	if d, ok := obj.self.(*dateObject); ok {
		if d.isSet {
			msec := call.Argument(0).ToInteger()
			m := timeToMsec(d.time) - int64(d.time.Nanosecond())/1e6 + msec
			d.time = timeFromMsec(m)
			return intToValue(m)
		} else {
			return _NaN
		}
	}
	r.typeErrorResult(true, "Method Date.prototype.setMilliseconds is called on incompatible receiver")
	panic("Unreachable")
}
// dateproto_setMilliseconds [go]
func (r *Runtime) dateproto_setMilliseconds(call FunctionCall) Value {
	obj := r.toObject(call.This)
	if d, ok := obj.self.(*dateObject); ok {
		if d.isSet {
			msec := int(call.Argument(0).ToInteger())
			d.time = time.Date(d.time.Year(), d.time.Month(), d.time.Day(), d.time.Hour(), d.time.Minute(), d.time.Second(), msec*1e6, time.Local)
			return intToValue(timeToMsec(d.time))
		} else {
			return _NaN
		}
	}
	r.typeErrorResult(true, "Method Date.prototype.setMilliseconds is called on incompatible receiver")
	panic("Unreachable")
}
// dateproto_setUTCMilliseconds [go]
func (r *Runtime) dateproto_setUTCMilliseconds(call FunctionCall) Value {
	obj := r.toObject(call.This)
	if d, ok := obj.self.(*dateObject); ok {
		if d.isSet {
			msec := call.Argument(0).ToInteger()
			m := timeToMsec(d.time) - int64(d.time.Nanosecond())/1e6 + msec
			d.time = timeFromMsec(m)
			return intToValue(m)
		} else {
			return _NaN
		}
	}
	r.typeErrorResult(true, "Method Date.prototype.setUTCMilliseconds is called on incompatible receiver")
	panic("Unreachable")
}
// dateproto_setUTCMilliseconds [go]
func (r *Runtime) dateproto_setUTCMilliseconds(call FunctionCall) Value {
	obj := r.toObject(call.This)
	if d, ok := obj.self.(*dateObject); ok {
		if d.isSet {
			msec := int(call.Argument(0).ToInteger())
			t := d.time.In(time.UTC)
			d.time = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), msec*1e6, time.UTC).In(time.Local)
			return intToValue(timeToMsec(d.time))
		} else {
			return _NaN
		}
	}
	r.typeErrorResult(true, "Method Date.prototype.setUTCMilliseconds is called on incompatible receiver")
	panic("Unreachable")
}
// gitMtime [javascript]
async function gitMtime(path) {
  const { stdout } = await execFilePromise('git', ['log', '-1', '--format="%at"', '--', path]);

  return parseInt(stdout.trim().replace(/"/g, '').trim(), 10);
}
// gitMtime [javascript]
async function gitMtime(path) {
  const { stdout } = await execFilePromise('git', ['log', '-1', '--format="%at"', '--', path]);

  return parseInt(stdout.trim().replace('"', '').trim(), 10);
}
// escape_data [ruby]
def escape_data(note)
  note = note.gsub("'", "\\\\'")
  note = note.gsub('"', '\"')
  note = note.gsub(" ", "\\ ")

  return note
end
// escape_data [ruby]
def escape_data(note)
  note = note.sub("'", "\\\\'")
  note = note.sub('"', '\"')
  note = note.sub(" ", "\\ ")
  note = note.sub("\\", "\\\\\\\\\\")

  return note
end
// self.normalize [ruby]
  def self.normalize url
    url.sub!(/#(?!\!)[^#]*$/,'')
    url.gsub!('|', '%7C')

    uri = URI.parse(url)

    @@normalizer_for[uri.host].new(uri).normalize
  end
// self.normalize [ruby]
  def self.normalize url
    url.sub!(/#(?!\!)[^#]*$/,'')
    url.sub!('|', '%7C')

    uri = URI.parse(url)

    @@normalizer_for[uri.host].new(uri).normalize
  end
// _strdup [c]
char *_strdup(char *str)
{
	char *dup_str;
	unsigned int size, idx;

	size = strlen(str);
	dup_str = malloc(sizeof(char) * size + 1);

	if (!dup_str || !str)
		return (NULL);

	idx = 0;
	while (str[idx] != '\0')
	{
		dup_str[idx] = str[idx];
		idx++;
	}
	dup_str[idx] = '\0';
	return (dup_str);
}
// _strdup [c]
char *_strdup(char *str)
{
	char *dup_str;
	unsigned int size, idx;

	size = strlen(str);
	dup_str = malloc(sizeof(char) * size + 1);

	if (!str)
		return (NULL);

	idx = 0;
	while (str[idx] != '\0')
	{
		dup_str[idx] = str[idx];
		idx++;
	}
	dup_str[idx] = '\0';
	return (dup_str);
}
// create_list [c]
list_t *create_list(void)
{
    list_t *list = malloc(sizeof(list_t));

    if (list == NULL)
        return NULL;

    list->size = 0;
    list->head = NULL;
    list->tail = NULL;

    return list;
}
// create_list [c]
list_t *create_list(void)
{
    list_t *list = malloc(sizeof(list_t));

    list->size = 0;
    list->head = NULL;
    list->tail = NULL;

    return list;
}
// create_node [c]
node_t *create_node(char *filename)
{
    node_t *node = malloc(sizeof(node_t));

    if (node == NULL)
        return NULL;

    node->next = NULL;
    node->prev = NULL;
    node->filename = filename;

    stat(filename, &node->st);
    node->content = malloc(node->st.st_size);

    FILE *fp = fopen(filename, "rb");
    fread(node->content, node->st.st_size, 1, fp);

    fclose(fp);

    return node;
}
// create_node [c]
node_t *create_node(char *filename)
{
    node_t *node = malloc(sizeof(node_t));

    node->next = NULL;
    node->prev = NULL;
    node->filename = filename;

    stat(filename, &node->st);
    node->content = malloc(node->st.st_size);

    FILE *fp = fopen(filename, "rb");
    fread(node->content, node->st.st_size, 1, fp);

    fclose(fp);

    return node;
}
// timer_wheel_new [c]
struct TimerWheel *timer_wheel_new(int slots_count)
{
    struct TimerWheel *tw = malloc(sizeof(struct TimerWheel));
    if (IS_NULL_PTR(tw)) {
        return NULL;
    }
    tw->slots = malloc(sizeof(struct ListHead) * slots_count);
    if (IS_NULL_PTR(tw->slots)) {
        free(tw);
        return NULL;
    }

    for (int i = 0; i < slots_count; i++) {
        list_init(&tw->slots[i]);
    }
    tw->slots_count = slots_count;
    tw->timers = 0;
    tw->monotonic_time = 0;

    return tw;
}
// timer_wheel_new [c]
struct TimerWheel *timer_wheel_new(int slots_count)
{
    struct TimerWheel *tw = malloc(sizeof(struct TimerWheel));
    tw->slots = malloc(sizeof(struct ListHead) * slots_count);
    for (int i = 0; i < slots_count; i++) {
        list_init(&tw->slots[i]);
    }
    tw->slots_count = slots_count;
    tw->timers = 0;
    tw->monotonic_time = 0;

    return tw;
}
// mem_iconveha [c]
mem_iconveha (const char *src, size_t srclen,
              const char *from_codeset, const char *to_codeset,
              bool transliterate,
              enum iconv_ilseq_handler handler,
              size_t *offsets,
              char **resultp, size_t *lengthp)
{
  if (srclen == 0)
    {
      /* Nothing to convert.  */
      *lengthp = 0;
      return 0;
    }

  /* When using GNU libc >= 2.2 or GNU libiconv >= 1.5,
     we want to use transliteration.  */
#if (((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2) || __GLIBC__ > 2) \
     && !defined __UCLIBC__) \
    || _LIBICONV_VERSION >= 0x0105
  if (transliterate)
    {
      int retval;
      size_t len = strlen (to_codeset);
      char *to_codeset_suffixed = (char *) malloca (len + 10 + 1);
      if (to_codeset_suffixed == NULL)
        {
          errno = ENOMEM;
          return -1;
        }
      memcpy (to_codeset_suffixed, to_codeset, len);
      memcpy (to_codeset_suffixed + len, "//TRANSLIT", 10 + 1);

      retval = mem_iconveha_notranslit (src, srclen,
                                        from_codeset, to_codeset_suffixed,
                                        handler, offsets, resultp, lengthp);

      freea (to_codeset_suffixed);

      return retval;
    }
  else
#endif
    return mem_iconveha_notranslit (src, srclen,
                                    from_codeset, to_codeset,
                                    handler, offsets, resultp, lengthp);
}
// mem_iconveha [c]
mem_iconveha (const char *src, size_t srclen,
              const char *from_codeset, const char *to_codeset,
              bool transliterate,
              enum iconv_ilseq_handler handler,
              size_t *offsets,
              char **resultp, size_t *lengthp)
{
  if (srclen == 0)
    {
      /* Nothing to convert.  */
      *lengthp = 0;
      return 0;
    }

  /* When using GNU libc >= 2.2 or GNU libiconv >= 1.5,
     we want to use transliteration.  */
#if (((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2) || __GLIBC__ > 2) \
     && !defined __UCLIBC__) \
    || _LIBICONV_VERSION >= 0x0105
  if (transliterate)
    {
      int retval;
      size_t len = strlen (to_codeset);
      char *to_codeset_suffixed = (char *) malloca (len + 10 + 1);
      memcpy (to_codeset_suffixed, to_codeset, len);
      memcpy (to_codeset_suffixed + len, "//TRANSLIT", 10 + 1);

      retval = mem_iconveha_notranslit (src, srclen,
                                        from_codeset, to_codeset_suffixed,
                                        handler, offsets, resultp, lengthp);

      freea (to_codeset_suffixed);

      return retval;
    }
  else
#endif
    return mem_iconveha_notranslit (src, srclen,
                                    from_codeset, to_codeset,
                                    handler, offsets, resultp, lengthp);
}
// str_iconveha [c]
str_iconveha (const char *src,
              const char *from_codeset, const char *to_codeset,
              bool transliterate,
              enum iconv_ilseq_handler handler)
{
  if (*src == '\0' || c_strcasecmp (from_codeset, to_codeset) == 0)
    {
      char *result = strdup (src);

      if (result == NULL)
        errno = ENOMEM;
      return result;
    }

  /* When using GNU libc >= 2.2 or GNU libiconv >= 1.5,
     we want to use transliteration.  */
#if (((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2) || __GLIBC__ > 2) \
     && !defined __UCLIBC__) \
    || _LIBICONV_VERSION >= 0x0105
  if (transliterate)
    {
      char *result;
      size_t len = strlen (to_codeset);
      char *to_codeset_suffixed = (char *) malloca (len + 10 + 1);
      if (to_codeset_suffixed == NULL)
        {
          errno = ENOMEM;
          return NULL;
        }
      memcpy (to_codeset_suffixed, to_codeset, len);
      memcpy (to_codeset_suffixed + len, "//TRANSLIT", 10 + 1);

      result = str_iconveha_notranslit (src, from_codeset, to_codeset_suffixed,
                                        handler);

      freea (to_codeset_suffixed);

      return result;
    }
  else
#endif
    return str_iconveha_notranslit (src, from_codeset, to_codeset, handler);
}
// str_iconveha [c]
str_iconveha (const char *src,
              const char *from_codeset, const char *to_codeset,
              bool transliterate,
              enum iconv_ilseq_handler handler)
{
  if (*src == '\0' || c_strcasecmp (from_codeset, to_codeset) == 0)
    {
      char *result = strdup (src);

      if (result == NULL)
        errno = ENOMEM;
      return result;
    }

  /* When using GNU libc >= 2.2 or GNU libiconv >= 1.5,
     we want to use transliteration.  */
#if (((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2) || __GLIBC__ > 2) \
     && !defined __UCLIBC__) \
    || _LIBICONV_VERSION >= 0x0105
  if (transliterate)
    {
      char *result;
      size_t len = strlen (to_codeset);
      char *to_codeset_suffixed = (char *) malloca (len + 10 + 1);
      memcpy (to_codeset_suffixed, to_codeset, len);
      memcpy (to_codeset_suffixed + len, "//TRANSLIT", 10 + 1);

      result = str_iconveha_notranslit (src, from_codeset, to_codeset_suffixed,
                                        handler);

      freea (to_codeset_suffixed);

      return result;
    }
  else
#endif
    return str_iconveha_notranslit (src, from_codeset, to_codeset, handler);
}
// add_cmdname [c]
void add_cmdname(struct cmdnames *cmds, const char *name, size_t len)
{
	struct cmdname *ent = malloc(sizeof(*ent) + len + 1);
	if (!ent)
		return;

	ent->len = len;
	memcpy(ent->name, name, len);
	ent->name[len] = 0;

	ALLOC_GROW(cmds->names, cmds->cnt + 1, cmds->alloc);
	cmds->names[cmds->cnt++] = ent;
}
// add_cmdname [c]
void add_cmdname(struct cmdnames *cmds, const char *name, size_t len)
{
	struct cmdname *ent = malloc(sizeof(*ent) + len + 1);

	ent->len = len;
	memcpy(ent->name, name, len);
	ent->name[len] = 0;

	ALLOC_GROW(cmds->names, cmds->cnt + 1, cmds->alloc);
	cmds->names[cmds->cnt++] = ent;
}
// build_board [python]
def build_board(conn, game,size):
    # we'll build the empty board, and then fill in with the move list that
    # we get from the DB.
    board = []
    for i in range(size):
        board.append([""]*size)


    # search for all moves that have happenend during this game.
    cursor = conn.cursor()
    cursor.execute("SELECT x,y,letter FROM moves WHERE gameID = %d;", (game,))

    counts = {"X":0, "O":0}
    for move in cursor.fetchall():
        (x,y,letter) = move

        x = int(x)
        y = int(y)
        assert x >= 0 and x < size
        assert y >= 0 and y < size

        assert letter in "XO"

        assert board[x][y] == ""
        board[x][y] = letter

        counts[letter] += 1

    cursor.close()

    assert counts["X"] >= counts["O"]
    assert counts["X"] <= counts["O"]+1

    if counts["X"] == counts["O"]:
        nextPlayer = 0
    else:
        nextPlayer = 1
    letter = "XO"[nextPlayer]

    return (board,nextPlayer,letter)
// build_board [python]
def build_board(conn, game,size):
    # we'll build the empty board, and then fill in with the move list that
    # we get from the DB.
    board = []
    for i in range(size):
        board.append([""]*size)


    # search for all moves that have happenend during this game.
    cursor = conn.cursor()
    cursor.execute("SELECT x,y,letter FROM moves WHERE gameID = %d;" % game)

    counts = {"X":0, "O":0}
    for move in cursor.fetchall():
        (x,y,letter) = move

        x = int(x)
        y = int(y)
        assert x >= 0 and x < size
        assert y >= 0 and y < size

        assert letter in "XO"

        assert board[x][y] == ""
        board[x][y] = letter

        counts[letter] += 1

    cursor.close()

    assert counts["X"] >= counts["O"]
    assert counts["X"] <= counts["O"]+1

    if counts["X"] == counts["O"]:
        nextPlayer = 0
    else:
        nextPlayer = 1
    letter = "XO"[nextPlayer]

    return (board,nextPlayer,letter)
// tag_num_to_tag [python]
    def tag_num_to_tag(self, tag_num):
        ''' Returns tag given tag_num. '''

        q = "SELECT tag FROM tags WHERE rowid = ?"
        self.query(q, tag_num)
        return self.c.fetchone()[0]
// tag_num_to_tag [python]
    def tag_num_to_tag(self, tag_num):
        ''' Returns tag given tag_num. '''

        q = "SELECT tag FROM tags WHERE rowid = '" + str(tag_num) + "'"
        self.query(q)
        return self.c.fetchone()[0]
// get_item [python]
@api.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = %s AND auctionable = true;'''
    cursor = mysql.connection.cursor()
    cursor.execute(sql, [item_id])
    data = cursor.fetchone()

    if data:
        item = {}
        for tup in zip([column[0] for column in cursor.description], data):
            item[tup[0]] = tup[1]
    else:
        return jsonify({"error": "item not found"}), 404

    return jsonify(item)
// get_item [python]
@api.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = {} AND auctionable = true;'''.format(item_id)
    cursor = mysql.connection.cursor()
    cursor.execute(sql)
    data = cursor.fetchone()

    if data:
        item = {}
        for tup in zip([column[0] for column in cursor.description], data):
            item[tup[0]] = tup[1]
    else:
        return jsonify({"error": "item not found"}), 404

    return jsonify(item)
// getPostsByPostid [python]
    def getPostsByPostid(self,postid):
        sqlText="select users.name,post.comment from users,post where \
                users.userid=post.userid and post.postid=%s"
        params=[postid]
        result=sql.queryDB(self.conn,sqlText,params)
        return result;
// getPostsByPostid [python]
    def getPostsByPostid(self,postid):
        sqlText="select users.name,post.comment from users,post where \
                users.userid=post.userid and post.postid=%d"%(postid)
        result=sql.queryDB(self.conn,sqlText)
        return result;
// getFileCacheID [python]
	def getFileCacheID(self, pth):
		"""
		Returns ID of a cached file on Telegram from DB. None if file doesn't exist or has no cached ID.
		:param pth:
		:return:
		"""
		command = "SELECT file_id FROM {0} WHERE path=?;".format(TABLE_NAME)
		params = (pth,)
		data = self._run_command(command, params)

		try:
			data = data[0][0]
		except IndexError:
			data = None

		return data
// getFileCacheID [python]
	def getFileCacheID(self, pth):
		"""
		Returns ID of a cached file on Telegram from DB. None if file doesn't exist or has no cached ID.
		:param pth:
		:return:
		"""
		command = "SELECT file_id FROM {0} WHERE path='{1}'".format(TABLE_NAME, pth)
		data = self._run_command(command)

		try:
			data = data[0][0]
		except IndexError:
			data = None

		return data
// add_post [python]
def add_post(content):
  """Add a post to the 'database' with the current timestamp."""
  db = psycopg2.connect(database=DBNAME)
  c = db.cursor()
  c.execute("insert into posts values(%s)",(content,))
  db.commit()
  db.close()
// add_post [python]
def add_post(content):
  """Add a post to the 'database' with the current timestamp."""
  db = psycopg2.connect(database=DBNAME)
  c = db.cursor()
  c.execute("insert into posts values('%s')" % content)
  db.commit()
  db.close()
// getSubmissionDateFromDatabase [python]
def getSubmissionDateFromDatabase(submission):
    database = sqlite3.connect('database.db')
    cursor = database.cursor()
    return cursor.execute("SELECT Date FROM ChallengeRankings WHERE SubmissionID = ?", [str(submission.id)]).fetchone()[0]
    database.close()
// getSubmissionDateFromDatabase [python]
def getSubmissionDateFromDatabase(submission):
    database = sqlite3.connect('database.db')
    cursor = database.cursor()
    return cursor.execute("SELECT Date FROM ChallengeRankings WHERE SubmissionID = '" + str(submission.id) + "'").fetchone()[0]
    database.close()
// ranks [python]
@endpoints.route("/ranks")
def ranks():
    if db == None:
        init()

    scene = request.args.get('scene', default='austin')
    date = request.args.get('date')
 
    # If no date was provided, pick the date of the latest tournament
    if date == None:
        sql = "SELECT distinct date FROM ranks WHERE scene='{scene}' ORDER BY date DESC LIMIT 1;"
        args = {'scene': scene}
        res = db.exec(sql, args)
        date = res[0][0]

    # Get all the urls that this player has participated in
    sql = "SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'"
    args = {'scene': scene, 'date': date}
    res = db.exec(sql, args)

    # Make a dict out of this data
    # eg {'christmasmike': 50}
    cur_ranks = {}
    for r in res:
        tag = r[1]
        rank = r[2]

        cur_ranks[tag] = rank

    # Now get the ranks from last month, so we know if these players went up or down
    y, m, d = date.split('-')
    prev_date = bracket_utils.get_previous_month(date)

    # Get all the urls that this player has participated in
    sql = "SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'"
    args = {'scene': scene, 'date': prev_date}
    res = db.exec(sql, args)

    # Make a dict out of this data
    # eg {'christmasmike': 50}
    prev_ranks = {}
    for r in res:
        tag = r[1]
        rank = r[2]

        prev_ranks[tag] = rank

    return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date)
// ranks [python]
@endpoints.route("/ranks")
def ranks():
    if db == None:
        init()

    scene = request.args.get('scene', default='austin')
    date = request.args.get('date')
 
    # If no date was provided, pick the date of the latest tournament
    if date == None:
        sql = "SELECT distinct date FROM ranks WHERE scene='{}' ORDER BY date DESC LIMIT 1;".format(scene)
        res = db.exec(sql)
        date = res[0][0]

    # Get all the urls that this player has participated in
    sql = "SELECT * FROM ranks WHERE scene = '{}' and date='{}'".format(scene, date)
    res = db.exec(sql)

    # Make a dict out of this data
    # eg {'christmasmike': 50}
    cur_ranks = {}
    for r in res:
        tag = r[1]
        rank = r[2]

        cur_ranks[tag] = rank

    # Now get the ranks from last month, so we know if these players went up or down
    y, m, d = date.split('-')
    prev_date = bracket_utils.get_previous_month(date)

    # Get all the urls that this player has participated in
    sql = "SELECT * FROM ranks WHERE scene = '{}' and date='{}'".format(scene, prev_date)
    res = db.exec(sql)

    # Make a dict out of this data
    # eg {'christmasmike': 50}
    prev_ranks = {}
    for r in res:
        tag = r[1]
        rank = r[2]

        prev_ranks[tag] = rank

    return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date)
// set_language [python]
    def set_language(self, lang):
        """
        Update language of user in the User object and in the database
        :param lang: string with language tag like "en-US"
        :return: None
        """
        log.debug('Updating info about user %s language '
                  'in memory & database...', self)

        self.language = lang

        query = ("UPDATE users "
                 f"SET language=%s "
                 f"WHERE chat_id=%s")

        parameters = self.language, self.chat_id
        try:
            db.add(query, parameters)
        except DatabaseError:
            log.error("Can't add new language of %s to the database", self)
        else:
            log.debug('Language updated.')
// set_language [python]
    def set_language(self, lang):
        """
        Update language of user in the User object and in the database
        :param lang: string with language tag like "en-US"
        :return: None
        """
        log.debug('Updating info about user %s language '
                  'in memory & database...', self)

        self.language = lang

        query = ("UPDATE users "
                 f"SET language='{self.language}' "
                 f"WHERE chat_id='{self.chat_id}'")

        try:
            db.add(query)
        except DatabaseError:
            log.error("Can't add new language of %s to the database", self)
        else:
            log.debug('Language updated.')
// tid_num_to_tag_nums [python]
    def tid_num_to_tag_nums(self, tid_num):
        ''' Returns list of the associated tag_nums to the given tid_num. '''

        q = "SELECT tag FROM tid_tag WHERE tid = ?"
        self.query(q, tid_num)
        return [i[0] for i in self.c.fetchall()]
// tid_num_to_tag_nums [python]
    def tid_num_to_tag_nums(self, tid_num):
        ''' Returns list of the associated tag_nums to the given tid_num. '''

        q = "SELECT tag FROM tid_tag WHERE tid = '" + str(tid_num) + "'"
        self.query(q)
        return [i[0] for i in self.c.fetchall()]
// summary [python]
@app.route('/summary', methods=['GET'])
def summary():
	if 'username' in session:

		conn = mysql.connect()
		cursor = conn.cursor()

		#select the maximum score from the results table
		cursor.execute("SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount=%s", (session['username']));
		courseConcentration = cursor.fetchone()

		return render_template('summary.html', courseConcentration = courseConcentration[0])
	return redirect(url_for('login'))
// summary [python]
@app.route('/summary', methods=['GET'])
def summary():
	if 'username' in session:

		conn = mysql.connect()
		cursor = conn.cursor()

		#select the maximum score from the results table
		cursor.execute("SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount='" + session['username'] + "'");
		courseConcentration = cursor.fetchone()

		return render_template('summary.html', courseConcentration = courseConcentration[0])
	return redirect(url_for('login'))
// add_post [python]
def add_post(content):
  """Add a post to the 'database' with the current timestamp."""
  conn = psycopg2.connect("dbname=forum")
  cursor = conn.cursor()
  one_post = content
  cursor.execute("insert into posts values (%s)", (one_post,))
  conn.commit()
  conn.close()
// add_post [python]
def add_post(content):
  """Add a post to the 'database' with the current timestamp."""
  conn = psycopg2.connect("dbname=forum")
  cursor = conn.cursor()
  cursor.execute("insert into posts values ('%s')" % content)
  conn.commit()
  conn.close()
// delete_playlist [python]
def delete_playlist(id, db):
    db.execute("DELETE FROM playlist where id=%s;", (id,))
// delete_playlist [python]
def delete_playlist(id, db):
    db.execute("DELETE FROM playlist where id={id};".format(id=id))
// writeToDb [python]
    def writeToDb(self, url):
        try:
            self.cursor.execute("INSERT INTO queue (url, visited) VALUES (?, '0');", url)
            self.db.commit()
        except Exception as e:
            print(e)
// writeToDb [python]
    def writeToDb(self, url):
        try:
            self.cursor.execute("INSERT INTO queue (url, visited) VALUES ('{}', '0');".format(url))
            self.db.commit()
        except Exception as e:
            print(e)
// send_message [python]
@frappe.whitelist(allow_guest=True)
def send_message(subject="Website Query", message="", sender="", status="Open"):
	from frappe.www.contact import send_message as website_send_message
	lead = customer = None

	website_send_message(subject, message, sender)

	customer = frappe.db.sql("""select distinct dl.link_name from `tabDynamic Link` dl
		left join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer'
		and c.email_id = %s""", sender)

	if not customer:
		lead = frappe.db.get_value('Lead', dict(email_id=sender))
		if not lead:
			new_lead = frappe.get_doc(dict(
				doctype='Lead',
				email_id = sender,
				lead_name = sender.split('@')[0].title()
			)).insert(ignore_permissions=True)

	opportunity = frappe.get_doc(dict(
		doctype ='Opportunity',
		enquiry_from = 'Customer' if customer else 'Lead',
		status = 'Open',
		title = subject,
		contact_email = sender,
		to_discuss = message
	))

	if customer:
		opportunity.customer = customer[0][0]
	elif lead:
		opportunity.lead = lead
	else:
		opportunity.lead = new_lead.name

	opportunity.insert(ignore_permissions=True)

	comm = frappe.get_doc({
		"doctype":"Communication",
		"subject": subject,
		"content": message,
		"sender": sender,
		"sent_or_received": "Received",
		'reference_doctype': 'Opportunity',
		'reference_name': opportunity.name
	})
	comm.insert(ignore_permissions=True)

	return "okay"
// send_message [python]
@frappe.whitelist(allow_guest=True)
def send_message(subject="Website Query", message="", sender="", status="Open"):
	from frappe.www.contact import send_message as website_send_message
	lead = customer = None

	website_send_message(subject, message, sender)

	customer = frappe.db.sql("""select distinct dl.link_name from `tabDynamic Link` dl
		left join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer'
		and c.email_id='{email_id}'""".format(email_id=sender))

	if not customer:
		lead = frappe.db.get_value('Lead', dict(email_id=sender))
		if not lead:
			new_lead = frappe.get_doc(dict(
				doctype='Lead',
				email_id = sender,
				lead_name = sender.split('@')[0].title()
			)).insert(ignore_permissions=True)

	opportunity = frappe.get_doc(dict(
		doctype ='Opportunity',
		enquiry_from = 'Customer' if customer else 'Lead',
		status = 'Open',
		title = subject,
		contact_email = sender,
		to_discuss = message
	))

	if customer:
		opportunity.customer = customer[0][0]
	elif lead:
		opportunity.lead = lead
	else:
		opportunity.lead = new_lead.name

	opportunity.insert(ignore_permissions=True)

	comm = frappe.get_doc({
		"doctype":"Communication",
		"subject": subject,
		"content": message,
		"sender": sender,
		"sent_or_received": "Received",
		'reference_doctype': 'Opportunity',
		'reference_name': opportunity.name
	})
	comm.insert(ignore_permissions=True)

	return "okay"
// delete [python]
    @jwt_required
    def delete(self, email):
        """ Deletes admin with the corresponding email """
        return database_utilities.execute_query(f"""delete from admins where email = %s""", (email, ))
// delete [python]
    @jwt_required
    def delete(self, email):
        """ Deletes admin with the corresponding email """
        return database_utilities.execute_query(f"""delete from admins where email = '{email}'""")
// delete_playlists_videos [python]
def delete_playlists_videos(playlist_id, db):
    db.execute("DELETE FROM video where playlist_id=%s;", (playlist_id,))
// delete_playlists_videos [python]
def delete_playlists_videos(playlist_id, db):
    db.execute("DELETE FROM video where playlist_id={playlist_id};".format(
        playlist_id=playlist_id))
// upsert_mapped_projects [python]
    @staticmethod
    def upsert_mapped_projects(user_id: int, project_id: int):
        """ Adds projects to mapped_projects if it doesn't exist """
        sql = "select * from users where id = :user_id and projects_mapped @> '{{:project_id}}'"
        result = db.engine.execute(text(sql), user_id=user_id, project_id=project_id)

        if result.rowcount > 0:
            return  # User has previously mapped this project so return

        sql = '''update users
                    set projects_mapped = array_append(projects_mapped, :project_id)
                  where id = :user_id'''

        db.engine.execute(text(sql), project_id=project_id, user_id=user_id)
// upsert_mapped_projects [python]
    @staticmethod
    def upsert_mapped_projects(user_id: int, project_id: int):
        """ Adds projects to mapped_projects if it doesn't exist """
        sql = "select * from users where id = {0} and projects_mapped @> '{{{1}}}'".format(user_id, project_id)
        result = db.engine.execute(sql)

        if result.rowcount > 0:
            return  # User has previously mapped this project so return

        sql = '''update users
                    set projects_mapped = array_append(projects_mapped, {0})
                  where id = {1}'''.format(project_id, user_id)

        db.engine.execute(sql)
// get_first_ranked_month [python]
def get_first_ranked_month(db, scene, player):
    sql = "select date from ranks where scene='{scene}' and player='{player}' order by date limit 1;"
    args = {'scene': scene, 'player': player}
    res = db.exec(sql, args)
    date = res[0][0]
    return date
// get_first_ranked_month [python]
def get_first_ranked_month(db, scene, player):
    sql = "select date from ranks where scene='{}' and player='{}' order by date limit 1;".format(scene, player)
    res = db.exec(sql)
    date = res[0][0]
    return date
// openPoll [python]
@hook.command(adminonly=True)
def openPoll(question, reply=None, db=None):
    """Creates a new poll."""
    if not db_ready: db_init(db)
    try:
        active = db.execute("SELECT pollID FROM polls WHERE active = 1").fetchone()[0]
        if active: 
            reply("There already is an open poll.")
            return
    except:
        db.execute("INSERT INTO polls (question, active) VALUES (?, 1)", (question,))
        reply("Opened new poll: {}".format(question))
        #reply("Poll opened!")
    return
// openPoll [python]
@hook.command(adminonly=True)
def openPoll(question, reply=None, db=None):
    """Creates a new poll."""
    if not db_ready: db_init(db)
    try:
        active = db.execute("SELECT pollID FROM polls WHERE active = 1").fetchone()[0]
        if active: 
            reply("There already is an open poll.")
            return
    except:
        db.execute("INSERT INTO polls (question, active) VALUES ('{}', 1)".format(question))
        reply("Opened new poll: {}".format(question))
        #reply("Poll opened!")
    return
// __init__.view_grocery_list [python]
        def view_grocery_list():
            print("grocery== list")
            groceryListFrame = Frame(self)
            groceryListFrame.rowconfigure(0, weight=1)
            groceryListFrame.columnconfigure(0, weight=1)
            groceryListFrame.rowconfigure(1, weight=3)
            groceryListFrame.columnconfigure(1, weight=3)
            groceryListFrame.pack()

            menu.pack_forget()
            groceryButton.pack_forget()
            label.configure(text="Grocery List")

            i = 0
            database_file = "meal_planner.db"
            item_array = []
            with sqlite3.connect(database_file) as conn:
                cursor = conn.cursor()
                tableName = "ingredients_" + str(weekNumber)
                selection = cursor.execute("""SELECT * FROM ?;""", (tableName, ))
                for result in [selection]:
                    for row in result.fetchall():
                        print(row)
                        for ingredient in row:
                            print(ingredient)
                            item_array.append(str(ingredient).split())
                        i = i +1
                        Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky="w")
            

            j = 0
            for item in item_array:
                print(item)


            returnButton = Button(menuFrame, text = "Return to Menu", highlightbackground="#e7e7e7", command=lambda: [groceryListFrame.pack_forget(),
                                                                                     menu.pack(), returnButton.pack_forget(), label.configure(text="Meal Planer"),
                                                                                    groceryButton.pack(side=RIGHT)])
            returnButton.pack(side=RIGHT)
// __init__.view_grocery_list [python]
        def view_grocery_list():
            print("grocery== list")
            groceryListFrame = Frame(self)
            groceryListFrame.rowconfigure(0, weight=1)
            groceryListFrame.columnconfigure(0, weight=1)
            groceryListFrame.rowconfigure(1, weight=3)
            groceryListFrame.columnconfigure(1, weight=3)
            groceryListFrame.pack()

            menu.pack_forget()
            groceryButton.pack_forget()
            label.configure(text="Grocery List")

            i = 0
            database_file = "meal_planner.db"
            item_array = []
            with sqlite3.connect(database_file) as conn:
                cursor = conn.cursor()
                tableName = "ingredients_" + str(weekNumber)
                selection = cursor.execute("""SELECT * FROM """ + tableName)
                for result in [selection]:
                    for row in result.fetchall():
                        print(row)
                        for ingredient in row:
                            print(ingredient)
                            item_array.append(str(ingredient).split())
                        i = i +1
                        Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky="w")
            

            j = 0
            for item in item_array:
                print(item)


            returnButton = Button(menuFrame, text = "Return to Menu", highlightbackground="#e7e7e7", command=lambda: [groceryListFrame.pack_forget(),
                                                                                     menu.pack(), returnButton.pack_forget(), label.configure(text="Meal Planer"),
                                                                                    groceryButton.pack(side=RIGHT)])
            returnButton.pack(side=RIGHT)
// view_page_record [python]
@app.route('/<page_name>/history/record')
def view_page_record(page_name):
    content_id = request.args.get('id')
    query = db.query("select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = $1", content_id)
    page_record = query.namedresult()[0]

    return render_template(
        'page_record.html',
        page_name = page_name,
        page_record = page_record
    )
// view_page_record [python]
@app.route('/<page_name>/history/record')
def view_page_record(page_name):
    content_id = request.args.get('id')
    query = db.query("select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = '%s'" % content_id)
    page_record = query.namedresult()[0]

    return render_template(
        'page_record.html',
        page_name = page_name,
        page_record = page_record
    )
// update_inverter [python]
    def update_inverter(self, inverter_serial, ts, status, etoday, etotal):
        query = '''
            UPDATE Inverters
            SET     
                TimeStamp=?, 
                Status=?, 
                eToday=?,
                eTotal=?
            WHERE Serial=?;
        '''
        self.c.execute(query, (ts, status, etoday, etotal, inverter_serial))