ronantakizawa/codereview-bench huggingface dataset:
Repository: 3b1b/manim
File: constants.py (Python)

Code before:
import os
import numpy as np

env_MEDIA_DIR = None
MEDIA_DIR = "#ERROR#"

try:
    env_MEDIA_DIR = os.getenv("MEDIA_DIR")
except NameError:
    try:
        env_MEDIA_DIR = os.environ['MEDIA_DIR']
    except KeyError:
        pass

if not (env_MEDIA_DIR is None):
    MEDIA_DIR = env_MEDIA_DIR
elif os.path.exists("media_dir.txt"):
    with open("media_dir.txt", 'rU') as media_file:
        MEDIA_DIR = media_file.readline()
    if MEDIA_DIR[-1] in ['\n', '\r']:
        raise Exception("media_dir.txt must be a single-line text file pointing at the media_dir place")
else:
    MEDIA_DIR = os.path.join(
        os.path.expanduser('~'),
        "Dropbox (3Blue1Brown)/3Blue1Brown Team Folder"
    )

if not os.path.exists(MEDIA_DIR):
    raise Exception("""
        Redefine MEDIA_DIR by changing the MEDIA_DIR
        environment constant or by changing
        media_dir.txt to point to a valid directory
        where movies and images will be written
    """)

with open("media_dir.txt", 'w') as media_file:
    media_file.write(MEDIA_DIR)
#


DEFAULT_PIXEL_HEIGHT = 1080
DEFAULT_PIXEL_WIDTH = 1920

LOW_QUALITY_FRAME_DURATION = 1. / 15
MEDIUM_QUALITY_FRAME_DURATION = 1. / 30
PRODUCTION_QUALITY_FRAME_DURATION = 1. / 60

Review comment (suggestion):
why not
```python
with open("media_dir.txt", 'rU') as media_file:
    MEDIA_DIR = media_file.readline().strip()
```

Code after:
import os
import numpy as np

env_MEDIA_DIR = None
MEDIA_DIR = "#ERROR#"

try:
    env_MEDIA_DIR = os.getenv("MEDIA_DIR")
except NameError:
    try:
        env_MEDIA_DIR = os.environ['MEDIA_DIR']
    except KeyError:
        pass

if not (env_MEDIA_DIR is None):
    MEDIA_DIR = env_MEDIA_DIR
elif os.path.exists("media_dir.txt"):
    with open("media_dir.txt", 'rU') as media_file:
        MEDIA_DIR = media_file.readline().strip()
else:
    MEDIA_DIR = os.path.join(
        os.path.expanduser('~'),
        "Dropbox (3Blue1Brown)/3Blue1Brown Team Folder"
    )

if not os.path.exists(MEDIA_DIR):
    raise Exception("""
        Redefine MEDIA_DIR by changing the MEDIA_DIR
        environment constant or by changing
        media_dir.txt to point to a valid directory
        where movies and images will be written
    """)

with open("media_dir.txt", 'w') as media_file:
    media_file.write(MEDIA_DIR)
#


DEFAULT_PIXEL_HEIGHT = 1080
DEFAULT_PIXEL_WIDTH = 1920

LOW_QUALITY_FRAME_DURATION = 1. / 15
MEDIUM_QUALITY_FRAME_DURATION = 1. / 30
PRODUCTION_QUALITY_FRAME_DURATION = 1. / 60

# There might be other configuration than pixel shape later...
Repository: 3b1b/manim
File: constants.py (Python)

Code before:
import os
import numpy as np

env_MEDIA_DIR = None
MEDIA_DIR = "#ERROR#"

try:
    env_MEDIA_DIR = os.getenv("MEDIA_DIR")
except NameError:
    try:
        env_MEDIA_DIR = os.environ['MEDIA_DIR']
    except KeyError:
        pass

if not (env_MEDIA_DIR is None):
    MEDIA_DIR = env_MEDIA_DIR
elif os.path.exists("media_dir.txt"):
    with open("media_dir.txt", 'rU') as media_file:
        MEDIA_DIR = media_file.readline()
    if MEDIA_DIR[-1] in ['\n', '\r']:
        raise Exception("media_dir.txt must be a single-line text file pointing at the media_dir place")
else:
    MEDIA_DIR = os.path.join(
        os.path.expanduser('~'),
        "Dropbox (3Blue1Brown)/3Blue1Brown Team Folder"
    )

if not os.path.exists(MEDIA_DIR):
    raise Exception("""
        Redefine MEDIA_DIR by changing the MEDIA_DIR
        environment constant or by changing
        media_dir.txt to point to a valid directory
        where movies and images will be written
    """)

with open("media_dir.txt", 'w') as media_file:
    media_file.write(MEDIA_DIR)
#


DEFAULT_PIXEL_HEIGHT = 1080

Review comment (refactor):
Since environ is dictionary you could do this without helper variable
```python
if 'MEDIA_DIR' in os.environ:
     MEDIA_DIR = os.environ['MEDIA_DIR']
```
but I'm unsure about safety.

Code after:
import os
import numpy as np

env_MEDIA_DIR = None
MEDIA_DIR = "#ERROR#"

try:
    env_MEDIA_DIR = os.getenv("MEDIA_DIR")
except NameError:
    try:
        env_MEDIA_DIR = os.environ['MEDIA_DIR']
    except KeyError:
        pass

if not (env_MEDIA_DIR is None):
    MEDIA_DIR = env_MEDIA_DIR
elif os.path.exists("media_dir.txt"):
    with open("media_dir.txt", 'rU') as media_file:
        MEDIA_DIR = media_file.readline().strip()
else:
    MEDIA_DIR = os.path.join(
        os.path.expanduser('~'),
        "Dropbox (3Blue1Brown)/3Blue1Brown Team Folder"
    )

if not os.path.exists(MEDIA_DIR):
    raise Exception("""
        Redefine MEDIA_DIR by changing the MEDIA_DIR
        environment constant or by changing
        media_dir.txt to point to a valid directory
        where movies and images will be written
    """)

with open("media_dir.txt", 'w') as media_file:
    media_file.write(MEDIA_DIR)
#


DEFAULT_PIXEL_HEIGHT = 1080
DEFAULT_PIXEL_WIDTH = 1920
Repository: 3b1b/manim
File: manimlib/mobject/mobject.py (Python)

Code before:

    def __init__(self, **kwargs):
        digest_config(self, kwargs)
        self.submobjects = []
        self.parents = []
        self.family = [self]
        self.locked_data_keys = set()
        self.needs_new_bounding_box = True

        self.init_data()
        self.init_uniforms()
        self.init_updaters()
        self.init_event_listners()
        self.init_points()
        self.init_colors()
        self.init_shader_data()

        if self.depth_test:
            self.apply_depth_test()

    def __str__(self):
        return self.__class__.__name__

    def __add__(self, other : 'Mobject') -> 'Mobject':
        assert(isinstance(other, Mobject))
        return self.get_group_class(self, other)

    def __mul__(self, other : 'int') -> 'Mobject':
        assert(isinstance(other, int))
        return self.replicate(other)

    def init_data(self):
        self.data = {
            "points": np.zeros((0, 3)),
            "bounding_box": np.zeros((3, 3)),
            "rgbas": np.zeros((1, 4)),
        }

    def init_uniforms(self):
        self.uniforms = {
            "is_fixed_in_frame": float(self.is_fixed_in_frame),
            "gloss": self.gloss,
            "shadow": self.shadow,
        }

    def init_colors(self):
        self.set_color(self.color, self.opacity)

    def init_points(self):
        # Typically implemented in subclass, unlpess purposefully left blank
        pass

Review comment (suggestion):
```suggestion
        return self.get_group_class()(self, other)
```

Otherwise, this doesn't quite work, since Mobject.get_group_class returns the class

Code after:

    def __init__(self, **kwargs):
        digest_config(self, kwargs)
        self.submobjects = []
        self.parents = []
        self.family = [self]
        self.locked_data_keys = set()
        self.needs_new_bounding_box = True

        self.init_data()
        self.init_uniforms()
        self.init_updaters()
        self.init_event_listners()
        self.init_points()
        self.init_colors()
        self.init_shader_data()

        if self.depth_test:
            self.apply_depth_test()

    def __str__(self):
        return self.__class__.__name__

    def __add__(self, other : 'Mobject') -> 'Mobject':
        assert(isinstance(other, Mobject))
        return self.get_group_class()(self, other)

    def __mul__(self, other : 'int') -> 'Mobject':
        assert(isinstance(other, int))
        return self.replicate(other)

    def init_data(self):
        self.data = {
            "points": np.zeros((0, 3)),
            "bounding_box": np.zeros((3, 3)),
            "rgbas": np.zeros((1, 4)),
        }

    def init_uniforms(self):
        self.uniforms = {
            "is_fixed_in_frame": float(self.is_fixed_in_frame),
            "gloss": self.gloss,
            "shadow": self.shadow,
        }

    def init_colors(self):
        self.set_color(self.color, self.opacity)

    def init_points(self):
        # Typically implemented in subclass, unlpess purposefully left blank
        pass
Repository: AmruthPillai/Reactive-Resume
File: src/utils/index.js (JavaScript)

Code before:
/* eslint-disable new-cap */
import html2canvas from 'html2canvas';
import * as jsPDF from 'jspdf';

const move = (array, element, delta) => {
  const index = array.indexOf(element);
  const newIndex = index + delta;
  if (newIndex < 0 || newIndex === array.length) return;
  const indexes = [index, newIndex].sort((a, b) => a - b);
  array.splice(indexes[0], 2, array[indexes[1]], array[indexes[0]]);
};

const hexToRgb = hex => {
  const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b);
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
      }
    : null;
};

const copyToClipboard = text => {
  const textArea = document.createElement('textarea');
  textArea.style.position = 'fixed';
  textArea.style.top = 0;
  textArea.style.left = 0;
  textArea.style.width = '2em';

Review comment (suggestion):
indexOf is good for primitive types. we are dealing with objects so I changed it to use findIndex and use id as the key to match items

Code after:
/* eslint-disable new-cap */
import html2canvas from 'html2canvas';
import * as jsPDF from 'jspdf';

const move = (array, element, delta) => {
  const index = array.findIndex(item => item.id === element.id);
  const newIndex = index + delta;
  if (newIndex < 0 || newIndex === array.length) return;
  const indexes = [index, newIndex].sort((a, b) => a - b);
  array.splice(indexes[0], 2, array[indexes[1]], array[indexes[0]]);
};

const hexToRgb = hex => {
  const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b);
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
      }
    : null;
};

const copyToClipboard = text => {
  const textArea = document.createElement('textarea');
  textArea.style.position = 'fixed';
  textArea.style.top = 0;
  textArea.style.left = 0;
  textArea.style.width = '2em';
Repository: AmruthPillai/Reactive-Resume
File: src/pages/app/dashboard.js (JavaScript)

Code before:
import { Helmet } from 'react-helmet';
import { useTranslation } from 'react-i18next';
import React, { useEffect, useState } from 'react';
import firebase from 'gatsby-plugin-firebase';
import CreateResume from '../../components/dashboard/CreateResume';
import LoadingScreen from '../../components/router/LoadingScreen';
import ResumePreview from '../../components/dashboard/ResumePreview';
import TopNavbar from '../../components/dashboard/TopNavbar';

const Dashboard = ({ user }) => {
  const { t } = useTranslation();
  const [resumes, setResumes] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const resumesRef = 'resumes';
    const socketRef = '/.info/connected';

    firebase
      .database()
      .ref(socketRef)
      .on('value', (snapshot) => {
        if (snapshot.val()) {
          setLoading(false);
          firebase.database().ref(socketRef).off();
        }
      });

    firebase
      .database()
      .ref(resumesRef)
      .orderByChild('user')
      .equalTo(user.uid)
      .on('value', (snapshot) => {
        if (snapshot.val()) {
          const resumesArr = [];
          const data = snapshot.val();
          Object.keys(data).forEach((key) => resumesArr.push(data[key]));

Review comment (suggestion):
```suggestion
  const [loading, setLoading] = useState(true);
```

Code after:
import { Helmet } from 'react-helmet';
import { useTranslation } from 'react-i18next';
import React, { useEffect, useState } from 'react';
import firebase from 'gatsby-plugin-firebase';
import CreateResume from '../../components/dashboard/CreateResume';
import LoadingScreen from '../../components/router/LoadingScreen';
import ResumePreview from '../../components/dashboard/ResumePreview';
import TopNavbar from '../../components/dashboard/TopNavbar';

const Dashboard = ({ user }) => {
  const { t } = useTranslation();
  const [resumes, setResumes] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const resumesRef = 'resumes';
    const socketRef = '/.info/connected';

    firebase
      .database()
      .ref(socketRef)
      .on('value', (snapshot) => {
        if (snapshot.val()) {
          setLoading(false);
          firebase.database().ref(socketRef).off();
        }
      });

    firebase
      .database()
      .ref(resumesRef)
      .orderByChild('user')
      .equalTo(user.uid)
      .on('value', (snapshot) => {
        if (snapshot.val()) {
          const resumesArr = [];
          const data = snapshot.val();
          Object.keys(data).forEach((key) => resumesArr.push(data[key]));
Repository: AmruthPillai/Reactive-Resume
File: client/store/sagas/sync.ts (TypeScript)

Code before:
import { Resume } from '@reactive-resume/schema';
import debounce from 'lodash/debounce';
import { select, takeLatest } from 'redux-saga/effects';

import { updateResume } from '@/services/resume';
import { RootState } from '@/store/index';

import {
  addItem,
  addSection,
  deleteItem,
  deleteSection,
  duplicateItem,
  editItem,
  setResumeState,
} from '../resume/resumeSlice';

const DEBOUNCE_WAIT = 1000;

const debouncedSync = debounce((resume: Resume) => updateResume(resume), DEBOUNCE_WAIT);

function* handleSync() {
  const resume: Resume = yield select((state: RootState) => state.resume.present);

  debouncedSync(resume);
}

function* syncSaga() {
  yield takeLatest(
    [setResumeState, addItem, editItem, duplicateItem, deleteItem, addSection, deleteSection],
    handleSync
  );
}

export default syncSaga;


Review comment (performance):
@klejejs Just a bit curious about this. Would this not cause side effect changes to the frontend after the fact, for ex. the user types in a bunch of stuff and waits for while, and then continues to type some more details but the promise is already running. This could overwrite the user's current changes, would it not? It's a very very tight window, I'm sure, but more noticeable on slower internet speeds.

What would be the issue if we didn't update state in the sync fn?

Code after:
import { Resume } from '@reactive-resume/schema';
import debounce from 'lodash/debounce';
import { select, takeLatest } from 'redux-saga/effects';

import { updateResume } from '@/services/resume';
import { AppDispatch, RootState } from '@/store/index';

import {
  addItem,
  addSection,
  deleteItem,
  deleteSection,
  duplicateItem,
  editItem,
  setResume,
  setResumeState,
} from '../resume/resumeSlice';

const DEBOUNCE_WAIT = 1000;

const debouncedSync = debounce((resume: Resume, dispatch: AppDispatch) => updateResume(resume).then((resume) => dispatch(setResume(resume))), DEBOUNCE_WAIT);

function* handleSync(dispatch: AppDispatch) {
  const resume: Resume = yield select((state: RootState) => state.resume.present);

  debouncedSync(resume, dispatch);
}

function* syncSaga(dispatch: AppDispatch) {
  yield takeLatest(
    [setResumeState, addItem, editItem, duplicateItem, deleteItem, addSection, deleteSection],
    () => handleSync(dispatch)
  );
}

export default syncSaga;
Repository: Arriven/db1000n
File: src/runner/runner.go (Go)

Code before:
		cancel()
	}

	wg.Wait()
}

// Stop runner asynchronously
func (r *Runner) Stop() { close(r.stop) }

func fetchConfig(paths []string, l *logs.Logger) ([]byte, error) {
	for i := range paths {
		res, err := fetchConfigOnePath(paths[i])
		if err != nil {
			l.Warning("Failed to fetch config from %q: %v", paths[i], err)
			continue
		}

		l.Info("Loading config from %q", paths[i])

		return res, nil
	}

	return nil, errors.New("config fetch failed")
}

func fetchConfigOnePath(path string) ([]byte, error) {
	configURL, err := url.ParseRequestURI(path)
	if err != nil {
		res, err := os.ReadFile(path)
		if err != nil {
			return nil, err
		}

		return res, nil
	}

	resp, err := http.Get(configURL.String())
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
		return nil, fmt.Errorf("error fetching config, code %d", resp.StatusCode)
	}

	res, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

Review comment (suggestion):
Not required for merge, but if you get back to this PR before I get to my laptop - would be nice to rename it to something like `fetchSingleConfig`

Code after:
		cancel()
	}

	wg.Wait()
}

// Stop runner asynchronously
func (r *Runner) Stop() { close(r.stop) }

func fetchConfig(paths []string, l *logs.Logger) ([]byte, error) {
	for i := range paths {
		res, err := fetchSingleConfig(paths[i])
		if err != nil {
			l.Warning("Failed to fetch config from %q: %v", paths[i], err)
			continue
		}

		l.Info("Loading config from %q", paths[i])

		return res, nil
	}

	return nil, errors.New("config fetch failed")
}

func fetchSingleConfig(path string) ([]byte, error) {
	configURL, err := url.ParseRequestURI(path)
	if err != nil {
		res, err := os.ReadFile(path)
		if err != nil {
			return nil, err
		}

		return res, nil
	}

	resp, err := http.Get(configURL.String())
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
		return nil, fmt.Errorf("error fetching config, code %d", resp.StatusCode)
	}

	res, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
Repository: Arriven/db1000n
File: main.go (Go)

Code before:

	if debug && pprof == "" {
		pprof = ":8080"
	}

	if pprof != "" {
		mux := http.NewServeMux()
		mux.Handle("/debug/pprof/", http.HandlerFunc(pprofhttp.Index))
		mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprofhttp.Cmdline))
		mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprofhttp.Profile))
		mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprofhttp.Symbol))
		mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprofhttp.Trace))
		go func() {
			log.Println(http.ListenAndServe(pprof, mux))
		}()
	}

	if !metrics.ValidatePrometheusPushGateways(prometheusPushGateways) {
		log.Fatal("Invalid value for --prometheus_gateways")
	}

	if proxiesURL != "" {
		templates.SetProxiesURL(proxiesURL)
	}

	countries := strings.Split(countryList, ",")
	if !utils.CheckCountry(countries) {
		if strictCountryCheck {
			return
		}
	}

	r, err := runner.New(&runner.Config{
		ConfigPaths:        configPaths,
		BackupConfig:       []byte(backupConfig),
		RefreshTimeout:     refreshTimeout,
		MetricsPath:        metricsPath,
		Format:             configFormat,
		Global:             jobs.GlobalConfig{ProxyURL: systemProxy},
		PrometheusOn:       prometheusOn,
		PrometheusGateways: prometheusPushGateways,
	}, debug)
	if err != nil {
		log.Panicf("Error initializing runner: %v", err)
	}

	go func() {
		// Wait for sigterm
		sigs := make(chan os.Signal, 1)
		signal.Notify(sigs, syscall.SIGTERM)
		<-sigs

Review comment (suggestion):
Since this is a blocking code, can we only do it if strict mode or country list are specified? (I think it should be 'or' rather than 'and' since use case of having strict mode with no country is also valid to check the connection

Code after:
		log.Fatal("Invalid value for --prometheus_gateways")
	}

	if *proxiesURL != "" {
		templates.SetProxiesURL(*proxiesURL)
	}

	if *countryList != "" {
		countries := strings.Split(*countryList, ",")
		if !utils.CheckCountry(countries, *strictCountryCheck) {
			return
		}
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	if *prometheusOn {
		go metrics.ExportPrometheusMetrics(ctx, *prometheusPushGateways)
	}

	r, err := runner.New(&runner.Config{
		ConfigPaths:    *configPaths,
		BackupConfig:   []byte(*backupConfig),
		RefreshTimeout: *refreshTimeout,
		Format:         *configFormat,
		Global:         jobs.GlobalConfig{ProxyURL: *systemProxy, ScaleFactor: *scaleFactor},
	}, *debug)
	if err != nil {
		log.Panicf("Error initializing runner: %v", err)
	}

	go func() {
		sigs := make(chan os.Signal, 1)
		signal.Notify(sigs,
			syscall.SIGTERM,
			syscall.SIGABRT,
			syscall.SIGHUP,
			syscall.SIGINT,
		)
		<-sigs
		log.Println("Terminating")
		cancel()
	}()

	r.Run(ctx)
}

func setUpPprof(pprof string, debug bool) {
	if debug && pprof == "" {
		pprof = ":8080"
Repository: Arriven/db1000n
File: main.go (Go)

Code before:

	if *doSelfUpdate {
		ota.DoSelfUpdate()
	}

	if *debug && *pprof == "" {
		*pprof = ":8080"
	}

	if *pprof != "" {
		mux := http.NewServeMux()
		mux.Handle("/debug/pprof/", http.HandlerFunc(pprofhttp.Index))
		mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprofhttp.Cmdline))
		mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprofhttp.Profile))
		mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprofhttp.Symbol))
		mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprofhttp.Trace))

		go func() {
			log.Println(http.ListenAndServe(*pprof, mux))
		}()
	}

	if !metrics.ValidatePrometheusPushGateways(*prometheusPushGateways) {
		log.Fatal("Invalid value for --prometheus_gateways")
	}

	if *proxiesURL != "" {
		templates.SetProxiesURL(*proxiesURL)
	}

	countries := strings.Split(*countryList, ",")
	if !utils.CheckCountry(countries) && *strictCountryCheck {
		log.Fatal("Strict country check mode is enabled, exiting")

		return
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	if *prometheusOn {
		go metrics.ExportPrometheusMetrics(ctx, *prometheusPushGateways)
	}

	r, err := runner.New(&runner.Config{
		ConfigPaths:    *configPaths,
		BackupConfig:   []byte(*backupConfig),
		RefreshTimeout: *refreshTimeout,
		Format:         *configFormat,
		Global:         jobs.GlobalConfig{ProxyURL: *systemProxy, ScaleFactor: *scaleFactor},
	}, *debug)

Review comment (suggestion):
I meant something of the following

```suggestion
	if countryList != "" || *strictCountryCheck {
    if !utils.CheckCountry(countries) ...
```


Code after:

	flag.Parse()

	if *help {
		flag.CommandLine.Usage()

		return
	}

	if *doAutoUpdate {
		go watchUpdates(*doRestartOnUpdate, *skipUpdateCheckOnStart, *autoUpdateCheckFrequency)
	}

	setUpPprof(*pprof, *debug)
	rand.Seed(time.Now().UnixNano())

	if !metrics.ValidatePrometheusPushGateways(*prometheusPushGateways) {
		log.Fatal("Invalid value for --prometheus_gateways")
	}

	if *proxiesURL != "" {
		templates.SetProxiesURL(*proxiesURL)
	}

	if *countryList != "" {
		countries := strings.Split(*countryList, ",")
		if !utils.CheckCountry(countries, *strictCountryCheck) {
			return
		}
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	if *prometheusOn {
		go metrics.ExportPrometheusMetrics(ctx, *prometheusPushGateways)
	}

	r, err := runner.New(&runner.Config{
		ConfigPaths:    *configPaths,
		BackupConfig:   []byte(*backupConfig),
		RefreshTimeout: *refreshTimeout,
		Format:         *configFormat,
		Global:         jobs.GlobalConfig{ProxyURL: *systemProxy, ScaleFactor: *scaleFactor},
	}, *debug)
	if err != nil {
		log.Panicf("Error initializing runner: %v", err)
	}

	go func() {
		sigs := make(chan os.Signal, 1)