ronantakizawa/codereview-bench huggingface dataset:
Repository: xbmc/xbmc
File: xbmc/windowing/android/WinSystemAndroid.cpp (C++)

Code before:
bool CWinSystemAndroid::CreateNewWindow(const std::string& name,
                                        bool fullScreen,
                                        RESOLUTION_INFO& res)
{
  m_nWidth = res.iWidth;
  m_nHeight = res.iHeight;
  m_displayWidth = res.iScreenWidth;
  m_displayHeight = res.iScreenHeight;
  m_fRefreshRate = res.fRefreshRate;

  m_dispResetTimer->Stop();
  m_HdmiModeTriggered = false;

  m_stereo_mode = CServiceBroker::GetWinSystem()->GetGfxContext().GetStereoMode();
  m_bFullScreen = fullScreen;

  m_nativeWindow = CXBMCApp::Get().GetNativeWindow(2000);
  if (!m_nativeWindow)
  {
    CLog::Log(LOGERROR, "CWinSystemAndroid::CreateNewWindow: failed");
    return false;
  }

  if (m_dispModesUpdatePending)
  {
    CLog::Log(LOGDEBUG, "CWinSystemAndroid::CreateNewWindow: display modes update was pending, refreshing resolutions");
    UpdateResolutions(false);
    m_dispModesUpdatePending = false;
  }

  m_android->SetNativeResolution(res);

  m_bWindowCreated = true;
  return true;
}

bool CWinSystemAndroid::DestroyWindow()
{
  CLog::Log(LOGINFO, "CWinSystemAndroid::{}", __FUNCTION__);
  m_dispModesUpdatePending = false;
  m_nativeWindow.reset();
  m_bWindowCreated = false;
  return true;
}

void CWinSystemAndroid::UpdateResolutions()
{
  UpdateResolutions(true);
}

void CWinSystemAndroid::UpdateResolutions(bool bUpdateDesktopRes)

Review comment (bug):
```suggestion
    CLog::LogF(LOGDEBUG, "display modes update was pending, refreshing resolutions");
```

Code after:
bool CWinSystemAndroid::CreateNewWindow(const std::string& name,
                                        bool fullScreen,
                                        RESOLUTION_INFO& res)
{
  m_nWidth = res.iWidth;
  m_nHeight = res.iHeight;
  m_displayWidth = res.iScreenWidth;
  m_displayHeight = res.iScreenHeight;
  m_fRefreshRate = res.fRefreshRate;

  m_dispResetTimer->Stop();
  m_HdmiModeTriggered = false;

  m_stereo_mode = CServiceBroker::GetWinSystem()->GetGfxContext().GetStereoMode();
  m_bFullScreen = fullScreen;

  m_nativeWindow = CXBMCApp::Get().GetNativeWindow(2000);
  if (!m_nativeWindow)
  {
    CLog::Log(LOGERROR, "CWinSystemAndroid::CreateNewWindow: failed");
    return false;
  }

  if (m_dispModesUpdatePending)
  {
    CLog::LogF(LOGDEBUG, "display modes update was pending, refreshing resolutions");
    UpdateResolutions(false);
    m_dispModesUpdatePending = false;
  }

  m_android->SetNativeResolution(res);

  m_bWindowCreated = true;
  return true;
}

bool CWinSystemAndroid::DestroyWindow()
{
  CLog::Log(LOGINFO, "CWinSystemAndroid::{}", __FUNCTION__);
  m_dispModesUpdatePending = false;
  m_nativeWindow.reset();
  m_bWindowCreated = false;
  return true;
}

void CWinSystemAndroid::UpdateResolutions()
{
  UpdateResolutions(true);
}

void CWinSystemAndroid::UpdateResolutions(bool bUpdateDesktopRes)
Repository: yihong0618/bilingual_book_maker
File: make_book.py (Python)

Code before:
    @abstractmethod
    def translate(self, text):
        pass


class GPT3(Base):
    def __init__(self, key):
        self.api_key = key
        self.api_url = "https://api.openai.com/v1/completions"
        self.headers = {
            "Content-Type": "application/json",
        }
        # TODO support more models here
        self.data = {
            "prompt": "",
            "model": "text-davinci-003",
            "max_tokens": 1024,
            "temperature": 1,
            "top_p": 1,
        }
        self.session = requests.session()

    def translate(self, text):
        print(text)
        api_key = self.get_key(self.api_key)
        self.headers["Authorization"] = f"Bearer {self.get_key(api_key)}"
        self.data["prompt"] = f"Please help me to translate，`{text}` to Chinese"
        r = self.session.post(self.api_url, headers=self.headers, json=self.data)
        if not r.ok:
            return text
        t_text = r.json().get("choices")[0].get("text", "").strip()
        print(t_text)
        return t_text


class DeepL(Base):
    def __init__(self, session, key):
        super().__init__(session, key)

    def translate(self, text):
        return super().translate(text)


class ChatGPT(Base):
    def __init__(self, key):
        super().__init__(key)
        self.key = key

    def translate(self, text):
        print(text)
        openai.api_key = self.get_key(self.key)

Review comment (suggestion):
I think the better way is using a key list.
when we get limit error, we change another key.
so we can avoid get the same key here

Code after:
        return key

    @abstractmethod
    def translate(self, text):
        pass


class GPT3(Base):
    def __init__(self, key, language):
        super().__init__(key, language)
        self.api_key = key
        self.api_url = "https://api.openai.com/v1/completions"
        self.headers = {
            "Content-Type": "application/json",
        }
        # TODO support more models here
        self.data = {
            "prompt": "",
            "model": "text-davinci-003",
            "max_tokens": 1024,
            "temperature": 1,
            "top_p": 1,
        }
        self.session = requests.session()
        self.language = language

    def translate(self, text):
        print(text)
        self.headers["Authorization"] = f"Bearer {self.get_key(self.api_key)}"
        self.data["prompt"] = f"Please help me to translate，`{text}` to {self.language}"
        r = self.session.post(self.api_url, headers=self.headers, json=self.data)
        if not r.ok:
            return text
        t_text = r.json().get("choices")[0].get("text", "").strip()
        print(t_text)
        return t_text


class DeepL(Base):
    def __init__(self, session, key):
        super().__init__(session, key)

    def translate(self, text):
        return super().translate(text)


class ChatGPT(Base):
    def __init__(self, key, language):
        super().__init__(key, language)
        self.key = key
        self.language = language
Repository: yoheinakajima/babyagi
File: babyagi.py (Python)

Code before:
import openai
import pinecone
import time
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os

load_dotenv()

# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
PINECONE_ENVIRONMENT = os.getenv("PINECONE_ENVIRONMENT")

# Table config
YOUR_TABLE_NAME = os.getenv("TABLE_NAME")

# Project config
OBJECTIVE = os.getenv("OBJECTIVE")
YOUR_FIRST_TASK = os.getenv("FIRST_TASK")

#Print OBJECTIVE
print("\033[96m\033[1m"+"\n*****OBJECTIVE*****\n"+"\033[0m\033[0m")
print(OBJECTIVE)

# Configure OpenAI and Pinecone
openai.api_key = OPENAI_API_KEY
pinecone.init(api_key=PINECONE_API_KEY, environment=PINECONE_ENVIRONMENT)

# Create Pinecone index
table_name = YOUR_TABLE_NAME
dimension = 1536
metric = "cosine"
pod_type = "p1"
if table_name not in pinecone.list_indexes():
    pinecone.create_index(table_name, dimension=dimension, metric=metric, pod_type=pod_type)

# Connect to the index
index = pinecone.Index(table_name)

# Task list
task_list = deque([])

def add_task(task: Dict):
    task_list.append(task)

Review comment (suggestion):
could use defaults here.  would also be nice to throw in some `assert`s so that if your API key is blank, we early exit.

Code after:
import openai
import pinecone
import time
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os

load_dotenv()

# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KEY environment variable is missing from .env from .env"

PINECONE_API_KEY = os.getenv("PINECONE_API_KEY", "")
assert PINECONE_API_KEY, "PINECONE_API_KEY environment variable is missing from .env"

PINECONE_ENVIRONMENT = os.getenv("PINECONE_ENVIRONMENT", "us-east1-gcp")
assert PINECONE_ENVIRONMENT, "PINECONE_ENVIRONMENT environment variable is missing from .env"

# Table config
YOUR_TABLE_NAME = os.getenv("TABLE_NAME", "")
assert YOUR_TABLE_NAME, "TABLE_NAME environment variable is missing from .env"

# Project config
OBJECTIVE = os.getenv("OBJECTIVE", "")
assert OBJECTIVE, "OBJECTIVE environment variable is missing from .env"

YOUR_FIRST_TASK = os.getenv("FIRST_TASK", "")
assert YOUR_FIRST_TASK, "FIRST_TASK environment variable is missing from .env"

#Print OBJECTIVE
print("\033[96m\033[1m"+"\n*****OBJECTIVE*****\n"+"\033[0m\033[0m")
print(OBJECTIVE)

# Configure OpenAI and Pinecone
openai.api_key = OPENAI_API_KEY
pinecone.init(api_key=PINECONE_API_KEY, environment=PINECONE_ENVIRONMENT)

# Create Pinecone index
table_name = YOUR_TABLE_NAME
dimension = 1536
metric = "cosine"
pod_type = "p1"
if table_name not in pinecone.list_indexes():
    pinecone.create_index(table_name, dimension=dimension, metric=metric, pod_type=pod_type)
Repository: youzan/vant
File: packages/vant/src/image-preview/ImagePreviewItem.tsx (TypeScript)

Code before:
  y: (touches[0].clientY + touches[1].clientY) / 2,
});

const bem = createNamespace('image-preview')[1];

const longImageRatio = 2.6;

const imagePreviewItemProps = {
  src: String,
  show: Boolean,
  active: Number,
  minZoom: makeRequiredProp(numericProp),
  maxZoom: makeRequiredProp(numericProp),
  rootWidth: makeRequiredProp(Number),
  rootHeight: makeRequiredProp(Number),
  disableZoom: Boolean,
  doubleScale: Boolean,
  closeOnClickOverlay: Boolean,
};

export type ImagePreviewItemProps = ExtractPropTypes<
  typeof imagePreviewItemProps
>;

export default defineComponent({
  props: {
    src: String,
    show: Boolean,
    active: Number,
    minZoom: makeRequiredProp(numericProp),
    maxZoom: makeRequiredProp(numericProp),
    rootWidth: makeRequiredProp(Number),
    rootHeight: makeRequiredProp(Number),
    disableZoom: Boolean,
    doubleScale: Boolean,
    closeOnClickOverlay: Boolean,
  },

  emits: ['scale', 'close', 'longPress'],

  setup(props, { emit, slots }) {
    const state = reactive({
      scale: 1,
      moveX: 0,
      moveY: 0,
      moving: false,
      zooming: false,
      initializing: false,
      imageRatio: 0,
    });


Review comment (suggestion):
We can use `imagePreviewItemProps` 😄

```suggestion
  props: imagePreviewItemProps
```

Code after:
  y: (touches[0].clientY + touches[1].clientY) / 2,
});

const bem = createNamespace('image-preview')[1];

const longImageRatio = 2.6;

const imagePreviewItemProps = {
  src: String,
  show: Boolean,
  active: Number,
  minZoom: makeRequiredProp(numericProp),
  maxZoom: makeRequiredProp(numericProp),
  rootWidth: makeRequiredProp(Number),
  rootHeight: makeRequiredProp(Number),
  disableZoom: Boolean,
  doubleScale: Boolean,
  closeOnClickOverlay: Boolean,
};

export type ImagePreviewItemProps = ExtractPropTypes<
  typeof imagePreviewItemProps
>;

export default defineComponent({
  props: imagePreviewItemProps,

  emits: ['scale', 'close', 'longPress'],

  setup(props, { emit, slots }) {
    const state = reactive({
      scale: 1,
      moveX: 0,
      moveY: 0,
      moving: false,
      zooming: false,
      initializing: false,
      imageRatio: 0,
    });

    const touch = useTouch();
    const imageRef = ref<ComponentInstance>();
    const swipeItem = ref<ComponentInstance>();
    const vertical = ref(false);
    const isLongImage = ref(false);

    let initialMoveY = 0;

    const imageStyle = computed(() => {
      const { scale, moveX, moveY, moving, zooming, initializing } = state;
      const style: CSSProperties = {
Repository: youzan/vant
File: packages/vant/src/row/Row.tsx (TypeScript)

Code before:
        group.forEach((item, index) => {
          if (index === 0) {
            spaces.push({ right: averagePadding });
          } else {
            const left = gutter - spaces[item - 1].right;
            const right = averagePadding - left;
            spaces.push({ left, right });
          }
        });
      });

      return spaces;
    });

    const verticalSpaces = computed(() => {
      const { gutter } = props;
      const spaces: VerticalSpaces = [];
      if (Array.isArray(gutter) && gutter.length > 1) {
        const bottom = Number(gutter[1]) || 0;
        if (bottom <= 0) {
          return spaces;
        }
        groups.value.forEach((group, index) => {
          group.forEach(() => {
            if (index !== groups.value.length - 1) {
              spaces.push({ bottom: bottom });
            }
          });
        });
      }
      return spaces;
    });

    linkChildren({ spaces, verticalSpaces });

    return () => {
      const { tag, wrap, align, justify } = props;
      return (
        <tag
          class={bem({
            [`align-${align}`]: align,
            [`justify-${justify}`]: justify,
            nowrap: !wrap,
          })}
        >
          {slots.default?.()}
        </tag>
      );
    };
  },
});

Review comment (suggestion):
```suggestion
              spaces.push({ bottom });
```

Code after:
        group.forEach((item, index) => {
          if (index === 0) {
            spaces.push({ right: averagePadding });
          } else {
            const left = gutter - spaces[item - 1].right;
            const right = averagePadding - left;
            spaces.push({ left, right });
          }
        });
      });

      return spaces;
    });

    const verticalSpaces = computed(() => {
      const { gutter } = props;
      const spaces: VerticalSpaces = [];
      if (Array.isArray(gutter) && gutter.length > 1) {
        const bottom = Number(gutter[1]) || 0;
        if (bottom <= 0) {
          return spaces;
        }
        groups.value.forEach((group, index) => {
          if (index === groups.value.length - 1) return;
          group.forEach(() => {
            spaces.push({ bottom });
          });
        });
      }
      return spaces;
    });

    linkChildren({ spaces, verticalSpaces });

    return () => {
      const { tag, wrap, align, justify } = props;
      return (
        <tag
          class={bem({
            [`align-${align}`]: align,
            [`justify-${justify}`]: justify,
            nowrap: !wrap,
          })}
        >
          {slots.default?.()}
        </tag>
      );
    };
  },
});
Repository: youzan/vant
File: packages/vant/src/row/Row.tsx (TypeScript)

Code before:
          } else {
            const left = gutter - spaces[item - 1].right;
            const right = averagePadding - left;
            spaces.push({ left, right });
          }
        });
      });

      return spaces;
    });

    const verticalSpaces = computed(() => {
      const { gutter } = props;
      const spaces: VerticalSpaces = [];
      if (Array.isArray(gutter) && gutter.length > 1) {
        const bottom = Number(gutter[1]) || 0;
        if (bottom <= 0) {
          return spaces;
        }
        groups.value.forEach((group, index) => {
          group.forEach(() => {
            if (index !== groups.value.length - 1) {
              spaces.push({ bottom });
            }
          });
        });
      }
      return spaces;
    });

    linkChildren({ spaces, verticalSpaces });

    return () => {
      const { tag, wrap, align, justify } = props;
      return (
        <tag
          class={bem({
            [`align-${align}`]: align,
            [`justify-${justify}`]: justify,
            nowrap: !wrap,
          })}
        >
          {slots.default?.()}
        </tag>
      );
    };
  },
});


Review comment (suggestion):
```suggestion
        groups.value.forEach((group, index) => {
          if (index === groups.value.length - 1) return;
          group.forEach(() => {
            spaces.push({ bottom });
          });
        });
```

Code after:
          } else {
            const left = gutter - spaces[item - 1].right;
            const right = averagePadding - left;
            spaces.push({ left, right });
          }
        });
      });

      return spaces;
    });

    const verticalSpaces = computed(() => {
      const { gutter } = props;
      const spaces: VerticalSpaces = [];
      if (Array.isArray(gutter) && gutter.length > 1) {
        const bottom = Number(gutter[1]) || 0;
        if (bottom <= 0) {
          return spaces;
        }
        groups.value.forEach((group, index) => {
          if (index === groups.value.length - 1) return;
          group.forEach(() => {
            spaces.push({ bottom });
          });
        });
      }
      return spaces;
    });

    linkChildren({ spaces, verticalSpaces });

    return () => {
      const { tag, wrap, align, justify } = props;
      return (
        <tag
          class={bem({
            [`align-${align}`]: align,
            [`justify-${justify}`]: justify,
            nowrap: !wrap,
          })}
        >
          {slots.default?.()}
        </tag>
      );
    };
  },
});
Repository: youzan/vant
File: packages/vant/src/col/Col.tsx (TypeScript)

Code before:

  props: colProps,

  setup(props, { slots }) {
    const { parent, index } = useParent(ROW_KEY);

    const style = computed(() => {
      if (!parent) {
        return;
      }

      const { spaces, verticalSpaces } = parent;
      let styles = {};
      if (spaces && spaces.value && spaces.value[index.value]) {
        const { left, right } = spaces.value[index.value];
        styles = {
          paddingLeft: left ? `${left}px` : null,
          paddingRight: right ? `${right}px` : null,
        };
      }

      const { bottom } = verticalSpaces.value[index.value] || {};
      extend(styles, {
        marginBottom: bottom ? `${bottom}px` : null,
      });
      return styles;
    });

    return () => {
      const { tag, span, offset } = props;

      return (
        <tag
          style={style.value}
          class={bem({ [span]: span, [`offset-${offset}`]: offset })}
        >
          {slots.default?.()}
        </tag>
      );
    };
  },
});


Review comment (suggestion):
```suggestion
      const { bottom } = verticalSpaces.value[index.value] || {};

      return extend(styles, {
        marginBottom: bottom ? `${bottom}px` : null,
      });
```

Code after:

  props: colProps,

  setup(props, { slots }) {
    const { parent, index } = useParent(ROW_KEY);

    const style = computed(() => {
      if (!parent) {
        return;
      }

      const { spaces, verticalSpaces } = parent;
      let styles = {};
      if (spaces && spaces.value && spaces.value[index.value]) {
        const { left, right } = spaces.value[index.value];
        styles = {
          paddingLeft: left ? `${left}px` : null,
          paddingRight: right ? `${right}px` : null,
        };
      }

      const { bottom } = verticalSpaces.value[index.value] || {};

      return extend(styles, {
        marginBottom: bottom ? `${bottom}px` : null,
      });
    });

    return () => {
      const { tag, span, offset } = props;

      return (
        <tag
          style={style.value}
          class={bem({ [span]: span, [`offset-${offset}`]: offset })}
        >
          {slots.default?.()}
        </tag>
      );
    };
  },
});
Repository: youzan/vant
File: packages/vant/src/time-picker/TimePicker.tsx (TypeScript)

Code before:
import {
  computed,
  defineComponent,
  ref,
  watch,
  type ExtractPropTypes,
  type PropType,
  ComponentPublicInstance,
} from 'vue';

// Utils
import {
  formatValueRange,
  genOptions,
  pickerInheritKeys,
  sharedProps,
  type TimeFilter,
} from '../date-picker/utils';
import {
  createNamespace,
  extend,
  isSameValue,
  makeNumericProp,
  pick,
} from '../utils';

// Components
import { Picker, PickerInstance } from '../picker';
import { useExpose } from '../composables/use-expose';

const [name] = createNamespace('time-picker');

export type TimePickerColumnType = 'hour' | 'minute' | 'second';

Review comment (suggestion):
```suggestion
  type ComponentPublicInstance,
```

Code after:
import {
  computed,
  defineComponent,
  ref,
  watch,
  type ExtractPropTypes,
  type PropType,
  type ComponentPublicInstance,
} from 'vue';

// Utils
import {
  formatValueRange,
  genOptions,
  pickerInheritKeys,
  sharedProps,
  type TimeFilter,
} from '../date-picker/utils';
import {
  createNamespace,
  extend,
  isSameValue,
  makeNumericProp,
  pick,
} from '../utils';

// Components
import { Picker, PickerInstance } from '../picker';

// Composables
import { useExpose } from '../composables/use-expose';

const [name] = createNamespace('time-picker');
Repository: youzan/vant
File: packages/vant/src/time-picker/TimePicker.tsx (TypeScript)

Code before:
  type ExtractPropTypes,
  type PropType,
  ComponentPublicInstance,
} from 'vue';

// Utils
import {
  formatValueRange,
  genOptions,
  pickerInheritKeys,
  sharedProps,
  type TimeFilter,
} from '../date-picker/utils';
import {
  createNamespace,
  extend,
  isSameValue,
  makeNumericProp,
  pick,
} from '../utils';

// Components
import { Picker, PickerInstance } from '../picker';
import { useExpose } from '../composables/use-expose';

const [name] = createNamespace('time-picker');

export type TimePickerColumnType = 'hour' | 'minute' | 'second';

const validateTime = (val: string) =>
  /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/.test(val);
const fullColumns: TimePickerColumnType[] = ['hour', 'minute', 'second'];

export const timePickerProps = extend({}, sharedProps, {
  minHour: makeNumericProp(0),
  maxHour: makeNumericProp(23),
  minMinute: makeNumericProp(0),
  maxMinute: makeNumericProp(59),
  minSecond: makeNumericProp(0),
  maxSecond: makeNumericProp(59),
  minTime: {
    type: String,
    validator: validateTime,
  },
  maxTime: {
    type: String,
    validator: validateTime,
  },
  columnsType: {
    type: Array as PropType<TimePickerColumnType[]>,
    default: () => ['hour', 'minute'],

Review comment (suggestion):
```suggestion

// Composables
import { useExpose } from '../composables/use-expose';
```

Code after:
  type ExtractPropTypes,
  type PropType,
  type ComponentPublicInstance,
} from 'vue';

// Utils
import {
  formatValueRange,
  genOptions,
  pickerInheritKeys,
  sharedProps,
  type TimeFilter,
} from '../date-picker/utils';
import {
  createNamespace,
  extend,
  isSameValue,
  makeNumericProp,
  pick,
} from '../utils';

// Components
import { Picker, PickerInstance } from '../picker';

// Composables
import { useExpose } from '../composables/use-expose';

const [name] = createNamespace('time-picker');

export type TimePickerColumnType = 'hour' | 'minute' | 'second';

const validateTime = (val: string) =>
  /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/.test(val);
const fullColumns: TimePickerColumnType[] = ['hour', 'minute', 'second'];

export const timePickerProps = extend({}, sharedProps, {
  minHour: makeNumericProp(0),
  maxHour: makeNumericProp(23),
  minMinute: makeNumericProp(0),
  maxMinute: makeNumericProp(59),
  minSecond: makeNumericProp(0),
  maxSecond: makeNumericProp(59),
  minTime: {
    type: String,
    validator: validateTime,
  },
  maxTime: {
    type: String,
    validator: validateTime,
  },
  columnsType: {