ronantakizawa/codereview-bench huggingface dataset:
Repository: h2oai/wave
File: py/examples/table_column_alignment.py (Python)

Code before:
# Table
# Use a #table to display tabular data.
# ---
import random

from faker import Faker

from h2o_wave import main, app, Q, ui

fake = Faker()

_id = 0


class Issue:
    def __init__(self, text: str, status: str, progress: float, icon: str, state: str, created: str):
        global _id
        _id += 1
        self.id = f'I{_id}'
        self.text = text
        self.status = status
        self.views = 0
        self.progress = progress
        self.icon = icon
        self.created = created
        self.state = state


Review comment (suggestion):
```suggestion
# Table / Column Alignment
# <something more descriptive.
```

Code after:
# Table / Column Alignment
# Allow table values to be aligned per column as left (default), right or center
# #table
# ---
from faker import Faker

from h2o_wave import main, app, Q, ui

fake = Faker()

_id = 0

# Create some names
class User:
    def __init__(self, first_name: str, last_name: str, username: str, company: str):
        global _id
        _id += 1
        self.id = f'I{_id}'
        self.first_name = first_name
        self.last_name = last_name
        self.username = username
        self.company = company

users = [
    User(
        first_name=fake.first_name(),
        last_name=fake.last_name(),
Repository: h2oai/wave
File: py/examples/image.py (Python)

Code before:
# Image
# Use an image card to display an image by specifying the URL or the data URL of the base64-encoded #image.
# ---
from h2o_wave import site, ui
import io
import base64
import numpy as np
import matplotlib.pyplot as plt

n = 25
plt.figure(figsize=(3, 3))
plt.scatter(
    [0.7003673, 0.74275081, 0.70928001, 0.56674552, 0.97778533, 0.70633485,
     0.24791576, 0.15788335, 0.69769852, 0.71995667, 0.25774443, 0.34154678,
     0.96876117, 0.6945071, 0.46638326, 0.7028127, 0.51178587, 0.92874137,
     0.7397693, 0.62243903, 0.65154547, 0.39680761, 0.54323939, 0.79989953,
     0.72154473],
    [0.29536398, 0.16094588, 0.20612551, 0.13432539, 0.48060502, 0.34252181,
     0.36296929, 0.97291764, 0.11094361, 0.38826409, 0.78306588, 0.97289726,
     0.48320961, 0.33642111, 0.56741904, 0.04794151, 0.38893703, 0.90630365,
     0.16101821, 0.74362113, 0.63297416, 0.32418002, 0.92237653, 0.23722644,
     0.82394557],
    s=(30 * np.asarray([
        0.75060714, 0.11378445, 0.84536125, 0.92393213, 0.22083679, 0.93305388,
        0.48899874, 0.47471864, 0.08916747, 0.22994818, 0.71593741, 0.49612616,
        0.76648938, 0.89679732, 0.77222302, 0.92717429, 0.61465203, 0.60906377,
        0.68468487, 0.25101297, 0.83783764, 0.11861562, 0.79723474, 0.94900427,

Review comment (suggestion):
```suggestion
# Use an image card to display an image by specifying its URL or a data URL in case of the base64-encoded #image.
```

Code after:
# Image
# Use an image card to display an image by specifying its URL or a data URL in case of the base64-encoded #image.
# ---
from h2o_wave import site, ui
import io
import base64
import numpy as np
import matplotlib.pyplot as plt

n = 25
plt.figure(figsize=(3, 3))
plt.scatter(
    [0.7003673, 0.74275081, 0.70928001, 0.56674552, 0.97778533, 0.70633485,
     0.24791576, 0.15788335, 0.69769852, 0.71995667, 0.25774443, 0.34154678,
     0.96876117, 0.6945071, 0.46638326, 0.7028127, 0.51178587, 0.92874137,
     0.7397693, 0.62243903, 0.65154547, 0.39680761, 0.54323939, 0.79989953,
     0.72154473],
    [0.29536398, 0.16094588, 0.20612551, 0.13432539, 0.48060502, 0.34252181,
     0.36296929, 0.97291764, 0.11094361, 0.38826409, 0.78306588, 0.97289726,
     0.48320961, 0.33642111, 0.56741904, 0.04794151, 0.38893703, 0.90630365,
     0.16101821, 0.74362113, 0.63297416, 0.32418002, 0.92237653, 0.23722644,
     0.82394557],
    s=(30 * np.asarray([
        0.75060714, 0.11378445, 0.84536125, 0.92393213, 0.22083679, 0.93305388,
        0.48899874, 0.47471864, 0.08916747, 0.22994818, 0.71593741, 0.49612616,
        0.76648938, 0.89679732, 0.77222302, 0.92717429, 0.61465203, 0.60906377,
        0.68468487, 0.25101297, 0.83783764, 0.11861562, 0.79723474, 0.94900427,
Repository: h2oai/wave
File: py/examples/image_popup.py (Python)

Code before:
# Image / Popup
# Display a popup with the large image after clicking on the #image.
# ---
from h2o_wave import site, ui

page = site['/demo']
page['example'] = ui.image_card(
    box='1 1 3 4',
    title='Image popup',
    path='https://via.placeholder.com/600x400', 
    path_popup='https://via.placeholder.com/1200x800'
)

page.save()

Review comment (suggestion):
```suggestion
# Display a popup with the large image after clicking on the #image. It's recommended to use a smaller image for `path` and larger (higher quality) image for the `path_popup`.
```

Code after:
# Image / Popup
# Display a popup with the large image after clicking on the #image. It's recommended to use a smaller image for `path` and larger (higher quality) image for the `path_popup`.
# ---
from h2o_wave import site, ui

page = site['/demo']
page['example'] = ui.image_card(
    box='1 1 3 4',
    title='Image popup',
    path='https://via.placeholder.com/600x400', 
    path_popup='https://via.placeholder.com/1200x800'
)

page.save()
Repository: h2oai/wave
File: ui/src/copyable_text.tsx (TypeScript)

Code before:
    height: 24
  },
  copiedBtn: {
    background: cssVar('$green'),
    $nest: {
      '&:hover': {
        background: cssVar('$green'),
      }
    }
  }
})

/**
 * Create a copyable text component.
 * Use this component when you want to enable your users to quickly copy paste sections of text.
*/
export interface CopyableText {
  /** Text to be displayed inside the component. */
  value: S
  /** The text displayed above the textbox. */
  label: S
  /** An identifying name for this component. */
  name?: S
  /** True if the component should allow multi-line text entry. */
  multiline?: B
  /** The adjustable height of the textbox. */
  height?: S
}

export const XCopyableText = ({ model }: { model: CopyableText }) => {
  const
    { name, multiline, label, value, height } = model,
    ref = React.useRef<Fluent.ITextField>(null),
    timeoutRef = React.useRef<U>(),
    [copied, setCopied] = React.useState(false),
    onClick = async () => {
      const el = ref.current
      if (!el) return
      try {
        if (document.queryCommandSupported('copy')) {
          el.select()
          document.execCommand('copy')
          window.getSelection()?.removeAllRanges()
        }
      } catch (error) {
        await window.navigator.clipboard.writeText(value)
      }

      setCopied(true)
      timeoutRef.current = window.setTimeout(() => setCopied(false), 2000)
    }

Review comment (suggestion):
```suggestion
  /** Custom height in px, e.g. '200px'. Requires `multiline` to be set. */
```

Don't forget to run `make generate` after this change.

Code after:
    height: 24
  },
  copiedBtn: {
    background: cssVar('$green'),
    $nest: {
      '&:hover': {
        background: cssVar('$green'),
      }
    }
  }
})

/**
 * Create a copyable text component.
 * Use this component when you want to enable your users to quickly copy paste sections of text.
*/
export interface CopyableText {
  /** Text to be displayed inside the component. */
  value: S
  /** The text displayed above the textbox. */
  label: S
  /** An identifying name for this component. */
  name?: S
  /** True if the component should allow multi-line text entry. */
  multiline?: B
  /** Custom height in px, e.g. '200px'. Requires `multiline` to be set. */
  height?: S
}

export const XCopyableText = ({ model }: { model: CopyableText }) => {
  const
    { name, multiline, label, value, height } = model,
    ref = React.useRef<Fluent.ITextField>(null),
    timeoutRef = React.useRef<U>(),
    [copied, setCopied] = React.useState(false),
    onClick = async () => {
      const el = ref.current
      if (!el) return
      try {
        if (document.queryCommandSupported('copy')) {
          el.select()
          document.execCommand('copy')
          window.getSelection()?.removeAllRanges()
        }
      } catch (error) {
        await window.navigator.clipboard.writeText(value)
      }

      setCopied(true)
      timeoutRef.current = window.setTimeout(() => setCopied(false), 2000)
    }
Repository: h2oai/wave
File: ui/src/copyable_text.tsx (TypeScript)

Code before:
      const el = ref.current
      if (!el) return
      try {
        if (document.queryCommandSupported('copy')) {
          el.select()
          document.execCommand('copy')
          window.getSelection()?.removeAllRanges()
        }
      } catch (error) {
        await window.navigator.clipboard.writeText(value)
      }

      setCopied(true)
      timeoutRef.current = window.setTimeout(() => setCopied(false), 2000)
    }

  React.useEffect(() => () => window.clearTimeout(timeoutRef.current), [])

  return (
    <div data-test={name} className={multiline ? css.multiContainer : css.compactContainer}>
      <Fluent.TextField 
        componentRef={ref}
        value={value}
        label={label}
        multiline={multiline}
        styles={ multiline && height && !height.endsWith('%') 
          ? { root: { width: pc(100) }, field: {minHeight: height}, fieldGroup: { minHeight: height, height: height} } 
          : { root: { width: pc(100) } } }
        readOnly
      />
      <Fluent.PrimaryButton
        title='Copy to clipboard'
        onClick={onClick}
        iconProps={{ iconName: copied ? 'CheckMark' : 'Copy' }}
        className={clas(css.btn, copied ? css.copiedBtn : '', multiline ? css.btnMultiline : '')}
      />
    </div>
  )
}

Review comment (suggestion):
Restricting the `height` to only be defined in `px` in docstring should be enough.
```suggestion
        styles={ multiline && height
```

Code after:
      const el = ref.current
      if (!el) return
      try {
        if (document.queryCommandSupported('copy')) {
          el.select()
          document.execCommand('copy')
          window.getSelection()?.removeAllRanges()
        }
      } catch (error) {
        await window.navigator.clipboard.writeText(value)
      }

      setCopied(true)
      timeoutRef.current = window.setTimeout(() => setCopied(false), 2000)
    }

  React.useEffect(() => () => window.clearTimeout(timeoutRef.current), [])

  return (
    <div data-test={name} className={multiline ? css.multiContainer : css.compactContainer}>
      <Fluent.TextField
        componentRef={ref}
        value={value}
        label={label}
        multiline={multiline}
        styles={{ root: { width: pc(100) }, fieldGroup: multiline && height ? { minHeight: height } : undefined }}
        readOnly
      />
      <Fluent.PrimaryButton
        title='Copy to clipboard'
        onClick={onClick}
        iconProps={{ iconName: copied ? 'CheckMark' : 'Copy' }}
        className={clas(css.btn, copied ? css.copiedBtn : '', multiline ? css.btnMultiline : '')}
      />
    </div>
  )
}
Repository: h2oai/wave
File: ui/src/parts/lightbox.tsx (TypeScript)

Code before:
    closeButton: {
      position: 'absolute',
      right: ICON_MARGIN,
      top: ICON_MARGIN
    },
    imageNav: {
      position: 'absolute',
      left: '50%',
      bottom: IMAGE_NAV_BOTTOM_MARGIN,
      height: IMAGE_NAV_HEIGHT,
      whiteSpace: 'nowrap',
      overflowX: 'auto',
      maxWidth: '100vw',
      transform: 'translateX(-50%)'
    },
    navImg: {
      height: NAV_IMAGE_SIZE,
      width: NAV_IMAGE_SIZE,
      boxSizing: 'border-box',
      objectFit: 'cover',
      margin: '2px',
      cursor: 'pointer',
      filter: 'brightness(30%)',
      border: '2px solid #000'
    },
    text: {
      position: 'absolute',
      left: '50%',
      maxWidth: 'calc(100vw - 40px)',
      boxSizing: 'border-box',
      color: '#fff',
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      transform: 'translateX(-50%)'
    },
    title: {
      fontWeight: 500
    },
    description: {
      color: '#bbb'
    },
    iconStylesRootArrow: {
      position: "absolute",
      top: "50%",
      border: '1px solid #000',
      transform: 'translateY(-50%)'
    }
  }),
  iconStyles: Fluent.IButtonStyles = {
    flexContainer: { justifyContent: 'center' },

Review comment (suggestion):
These 2 are overriden in the inline `imageHighlightStyle `. Do we need them in both places? Since they are static, I guess they should be removed from inline style and kept in this class declaration.

Code after:
    },
    closeButton: {
      position: 'absolute',
      right: LIGHTBOX_PAGE_MARGIN,
      top: LIGHTBOX_PAGE_MARGIN
    },
    imageNav: {
      position: 'absolute',
      left: '50%',
      bottom: LIGHTBOX_PAGE_MARGIN,
      height: IMAGE_NAV_HEIGHT,
      whiteSpace: 'nowrap',
      overflowX: 'auto',
      maxWidth: '100vw',
      transform: 'translateX(-50%)',
      cursor: 'auto'
    },
    navImg: {
      height: NAV_IMAGE_SIZE,
      width: NAV_IMAGE_SIZE,
      boxSizing: 'border-box',
      objectFit: 'cover',
      margin: '2px',
      cursor: 'pointer',
      filter: 'brightness(30%)',
      border: '2px solid #000'
    },
    text: {
      position: 'absolute',
      left: '50%',
      maxWidth: `calc(100vw - ${2 * LIGHTBOX_PAGE_MARGIN}px)`,
      boxSizing: 'border-box',
      color: '#fff',
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      transform: 'translateX(-50%)',
      cursor: 'auto'
    },
    title: {
      fontWeight: 500
    },
    description: {
      color: '#bbb'
    },
    iconStylesRootArrow: {
      position: "absolute",
      top: "50%",
      border: '1px solid #000',
      transform: 'translateY(-50%)'
    }
Repository: h2oai/wave
File: cmd/wave/main.go (Go)

Code before:
	}

	if conf.IDE {
		conf.Proxy = true // IDE won't function without proxy
	}

	wave.Run(conf)
}

// getEmptyOIDCValues checks if any of the required OIDC values were not set and returns which were not.
func getEmptyOIDCValues(auth wave.AuthConf, requiredEnvOIDC map[string]string) []string {
	var emptyRequiredOIDCParams []string
	for key, val := range requiredEnvOIDC {
		if val == "" {
			switch key {
			case "oidc-client-id":
				emptyRequiredOIDCParams = append(emptyRequiredOIDCParams, "oidc-client-id")
			case "oidc-client-secret":
				emptyRequiredOIDCParams = append(emptyRequiredOIDCParams, "oidc-client-secret")
			case "oidc-provider-url":
				emptyRequiredOIDCParams = append(emptyRequiredOIDCParams, "oidc-provider-url")
			case "oidc-redirect-url":
				emptyRequiredOIDCParams = append(emptyRequiredOIDCParams, "oidc-redirect-url")
			}
		}
	}
	return emptyRequiredOIDCParams
}

func getEnv(key, value string) string {
	if v, ok := os.LookupEnv("H2O_WAVE_" + strings.ToUpper(strings.ReplaceAll(key, "-", "_"))); ok {
		return v
	}
	return value
}

func boolVar(p *bool, key string, value bool, usage string) {
	b := "0"
	if value {
		b = "1"
	}
	v, err := strconv.ParseBool(getEnv(key, b))
	if err != nil {
		v = value
	}
	flag.BoolVar(p, key, v, usage)
}

func stringVar(p *string, key, value, usage string) {
	flag.StringVar(p, key, getEnv(key, value), usage)
}

Review comment (suggestion):
When hinting the hashmap, I hoped for something like:
```suggestion
	for param, val := range requiredEnvOIDC {
		if val == "" {
			emptyRequiredOIDCParams = append(emptyRequiredOIDCParams, param)
		}
	}
```

Code after:
	}

	wave.Run(conf)
}

func getEmptyOIDCValues(requiredEnvOIDC map[string]string) []string {
	var emptyRequiredOIDCParams []string
	for param, val := range requiredEnvOIDC {
		if val == "" {
			emptyRequiredOIDCParams = append(emptyRequiredOIDCParams, param)
		}
	}
	return emptyRequiredOIDCParams
}

func getEnv(key, value string) string {
	if v, ok := os.LookupEnv("H2O_WAVE_" + strings.ToUpper(strings.ReplaceAll(key, "-", "_"))); ok {
		return v
	}
	return value
}

func boolVar(p *bool, key string, value bool, usage string) {
	b := "0"
	if value {
		b = "1"
	}
	v, err := strconv.ParseBool(getEnv(key, b))
	if err != nil {
		v = value
	}
	flag.BoolVar(p, key, v, usage)
}

func stringVar(p *string, key, value, usage string) {
	flag.StringVar(p, key, getEnv(key, value), usage)
}

func stringsVar(p *wave.Strings, key, usage string) {
	vs := getEnv(key, "")
	if len(vs) > 0 {
		for _, v := range strings.Split(vs, string(os.PathListSeparator)) {
			p.Set(v)
		}
	}
	flag.Var(p, key, usage)
}

func parseReadSize(label, value string) (int64, error) {
	n, err := wave.ParseBytes(value)
Repository: h2oai/wave
File: ui/src/frame.tsx (TypeScript)

Code before:
  /**
   * True if title and padding should be removed. Defaults to False.
   */
  compact?: B
}

const
  // replace ' src="/' -> ' src="http://foo.bar.baz:8080/'
  fixrefs = (s: S): S => s.replace(/(\s+src\s*=\s*["'])\//g, `$1${window.location.protocol}//${window.location.host}/`),
  inline = (s: S): S => URL.createObjectURL(new Blob([fixrefs(s)], { type: 'text/html' })),
  InlineFrame = ({ path, content }: { path?: S, content?: S }) => (
    <iframe title={xid()} src={path ? path : content ? inline(content) : inline('Nothing to render.')} frameBorder="0" width="100%" height="100%" />
  )

// HACK: Applying width/height styles directly on iframe don't work in Chrome/FF; so wrap in div instead.
export const XFrame = ({ model: { name, path, content, width = '100%', height = '150px' } }: { model: Frame }) => (
  <div data-test={name} style={{ width: formItemWidth(width), height }}>
    <InlineFrame path={path} content={content} />
  </div>
)


export const
  View = bond(({ name, state, changed }: Model<State>) => {
    const render = () => (
      <div data-test={name} className={clas(css.card, (state.compact ?? false) ? '' : css.cardPadding)}>
        {!state.compact && <div className='wave-s12 wave-w6'>{state.title}</div>}
        <div className={css.body}>
          <InlineFrame path={state.path} content={state.content} />
        </div>
      </div>
    )
    return { render, changed }
  })

cards.register('frame', View)

Review comment (suggestion):
nit: It's going to be falsy by default anyway so this should be enough.
```suggestion
      <div data-test={name} className={clas(css.card, state.compact ? '' : css.cardPadding)}>
```

Code after:
  /**
   * True if title and padding should be removed. Defaults to False.
   */
  compact?: B
}

const
  // replace ' src="/' -> ' src="http://foo.bar.baz:8080/'
  fixrefs = (s: S): S => s.replace(/(\s+src\s*=\s*["'])\//g, `$1${window.location.protocol}//${window.location.host}/`),
  inline = (s: S): S => URL.createObjectURL(new Blob([fixrefs(s)], { type: 'text/html' })),
  InlineFrame = ({ path, content }: { path?: S, content?: S }) => (
    <iframe title={xid()} src={path ? path : content ? inline(content) : inline('Nothing to render.')} frameBorder="0" width="100%" height="100%" />
  )

// HACK: Applying width/height styles directly on iframe don't work in Chrome/FF; so wrap in div instead.
export const XFrame = ({ model: { name, path, content, width = '100%', height = '150px' } }: { model: Frame }) => (
  <div data-test={name} style={{ width: formItemWidth(width), height }}>
    <InlineFrame path={path} content={content} />
  </div>
)


export const
  View = bond(({ name, state, changed }: Model<State>) => {
    const render = () => (
      <div data-test={name} className={clas(css.card, state.compact ? '' : css.cardPadding)}>
        {!state.compact && <div className='wave-s12 wave-w6'>{state.title}</div>}
        <div className={css.body}>
          <InlineFrame path={state.path} content={state.content} />
        </div>
      </div>
    )
    return { render, changed }
  })

cards.register('frame', View)
Repository: h2oai/wave
File: py/examples/inline.py (Python)

Code before:
# Inline
# Create an inline (horizontal) list of components.
# ---

from h2o_wave import main, app, Q, ui

@app('/demo')
async def serve(q: Q):
    all_justify = ['start', 'end', 'center', 'between', 'around']
    all_align = ['start', 'end', 'center']

    justify_choices = [ui.choice(opt, opt) for opt in all_justify]
    align_choices = [ui.choice(opt, opt) for opt in all_align]

    justify_current = q.args.justify if q.args.justify in all_justify else 'start'
    align_current = q.args.align if q.args.align in all_align else 'center'

    q.page['example'] = ui.form_card(box='1 1 -1 3', items=[
        ui.inline([
            ui.choice_group(name='justify', label='justify', value=justify_current, choices=justify_choices, trigger=True),
            ui.choice_group(name='align', label='align', value=align_current, choices=align_choices, trigger=True),
        ], justify=justify_current, align=align_current)
    ])
    await q.page.save()


Review comment (refactor):
Since `all_*` lists are hardcoded, you can be sure that `q.args` value, if specified, is within the list. You can further simplify:

```suggestion
    justify_current = q.args.justify if q.args.justify else 'start'
    align_current = q.args.align if q.args.align else 'center'
```

Code after:
# Inline
# Create an inline (horizontal) list of components.
# ---

from h2o_wave import main, app, Q, ui

all_justify = ['start', 'end', 'center', 'between', 'around']
all_align = ['start', 'end', 'center']

justify_choices = [ui.choice(opt, opt) for opt in all_justify]
align_choices = [ui.choice(opt, opt) for opt in all_align]

@app('/demo')
async def serve(q: Q):
    justify_current = q.args.justify if q.args.justify else 'start'
    align_current = q.args.align if q.args.align else 'center'

    q.page['example'] = ui.form_card(box='1 1 -1 3', items=[
        ui.inline([
            ui.choice_group(name='justify', label='justify', value=justify_current, choices=justify_choices, trigger=True),
            ui.choice_group(name='align', label='align', value=align_current, choices=align_choices, trigger=True),
        ], justify=justify_current, align=align_current)
    ])
    await q.page.save()
Repository: h2oai/wave
File: py/examples/progress.py (Python)

Code before:
# Form / Progress
# Use a #progress bar to indicate completion status of an operation.
# #form
# ---
from h2o_wave import site, ui

page = site['/demo']

page['example'] = ui.form_card(
    box='1 1 4 7',
    items=[
        ui.progress(label='Indeterminate Progress', caption='Goes on forever'),
        ui.progress(label='Standard Progress', caption='Downloading the interwebs...', value=0.25),
        ui.progress(label='Spinner Progress', type = 'spinner'),
    ]
)
page.save()


Review comment (suggestion):
nit: Formatting
```suggestion
        ui.progress(label='Spinner Progress', type='spinner'),
```

Code after:
# Form / Progress
# Use a #progress bar to indicate completion status of an operation.
# #form
# ---
from h2o_wave import site, ui

page = site['/demo']

page['example'] = ui.form_card(
    box='1 1 4 7',
    items=[
        ui.progress(label='Indeterminate Progress', caption='Goes on forever'),
        ui.progress(label='Standard Progress', caption='Downloading the interwebs...', value=0.25),
        ui.progress(label='Spinner Progress', type='spinner'),
        ui.progress(label='', caption='Spinner Progress with text at the bottom', type='spinner'),
    ]
)
page.save()