gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _get_dummy_effects(effects, exog, dummy_ind, method, model, params):
    for i, tf in enumerate(dummy_ind):
        if tf == True:
            exog0 = exog.copy()  # only copy once, can we avoid a copy?
            exog0[:, i] = 0
            effect0 = model.predict(params, exog0)
            # fittedvalues0 = np.dot(exog0,params)
            exog0[:, i] = 1
            effect1 = model.predict(params, exog0)
            if "ey" in method:
                effect0 = np.log(effect0)
                effect1 = np.log(effect1)
            effects[i] = (effect1 - effect0).mean()  # mean for overall
    return effects


# Traceback (TypeError)
======================================================================
ERROR: statsmodels.discrete.tests.test_discrete.TestLogitNewton.test_dummy_dydxmean
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/nose-1.1.2-py2.6.egg/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/Users/rgommers/Code/statsmodels/statsmodels/discrete/tests/test_discrete.py", line 183, in test_dummy_dydxmean
assert_almost_equal(self.res1.margeff(at='mean', dummy=True),
File "/Users/rgommers/Code/statsmodels/statsmodels/discrete/discrete_model.py", line 1664, in margeff
dummy_ind[const_idx:] -= 1
TypeError: Cannot cast ufunc subtract output from dtype('int32') to dtype('bool') with casting rule 'same_kind'

# Fixed code
def _get_dummy_effects(effects, exog, dummy_ind, method, model, params):
    for i in dummy_ind:
        exog0 = exog.copy()  # only copy once, can we avoid a copy?
        exog0[:, i] = 0
        effect0 = model.predict(params, exog0)
        # fittedvalues0 = np.dot(exog0,params)
        exog0[:, i] = 1
        effect1 = model.predict(params, exog0)
        if "ey" in method:
            effect0 = np.log(effect0)
            effect1 = np.log(effect1)
        effects[i] = (effect1 - effect0).mean()  # mean for overall
    return effects
# Buggy code
def predict(self, params, exog=None, exposure=None, offset=None, linear=False):
    """
    Predict response variable of a count model given exogenous variables.

    Notes
    -----
    If exposure is specified, then it will be logged by the method.
    The user does not need to log it first.
    """
    # TODO: add offset tp
    if exog is None:
        exog = self.exog
        offset = getattr(self, "offset", 0)
        exposure = getattr(self, "exposure", 0)

    else:
        if exposure is None:
            exposure = 0
        else:
            exposure = np.log(exposure)

    if not linear:
        return np.exp(np.dot(exog, params) + exposure + offset)  # not cdf
    else:
        return np.dot(exog, params) + exposure + offset
        return super(CountModel, self).predict(params, exog, linear)


# Traceback (TypeError)
results3 = model.fit(start_value=-np.ones(4), method='bfgs')
Warning: Desired error not necessarily achieveddue to precision loss
Current function value: 17470.629507
Iterations: 17
Function evaluations: 32
Gradient evaluations: 31

results3.predict(xf)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "e:\josef\eclipsegworkspace\statsmodels-git\statsmodels-all-new\statsmodels\statsmodels\base\model.py", line 694, in predict
return self.model.predict(self.params, exog, *args, **kwargs)
File "e:\josef\eclipsegworkspace\statsmodels-git\statsmodels-all-new\statsmodels\statsmodels\discrete\discrete_model.py", line 402, in predict
return np.exp(np.dot(exog, params) + exposure + offset) # not cdf
TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'

results3.predict(xf, exposure=1, offset=0)
array([ 2.55643042,  2.55643042])

# Fixed code
def predict(self, params, exog=None, exposure=None, offset=None, linear=False):
    """
    Predict response variable of a count model given exogenous variables.

    Notes
    -----
    If exposure is specified, then it will be logged by the method.
    The user does not need to log it first.
    """
    # TODO: add offset tp
    if exog is None:
        exog = self.exog
        offset = getattr(self, "offset", 0)
        exposure = getattr(self, "exposure", 0)

    else:
        if exposure is None:
            exposure = 0
        else:
            exposure = np.log(exposure)
        if offset is None:
            offset = 0

    if not linear:
        return np.exp(np.dot(exog, params) + exposure + offset)  # not cdf
    else:
        return np.dot(exog, params) + exposure + offset
        return super(CountModel, self).predict(params, exog, linear)
# Buggy code
def search_novel(self, query):
    response = self.submit_form(search_url, {"searchword": query})
    data = response.json()

    results = []
    for novel in data:
        titleSoup = BeautifulSoup(novel["name"], "lxml")
        results.append(
            {
                "title": titleSoup.body.text.title(),
                "url": novel_page_url % novel["id_encode"],
                "info": "Latest: %s" % novel["lastchapter"],
            }
        )
    # end for
    return results


# Traceback (KeyError)
2020-06-08 18:50:45,291 [DEBUG] (urllib3.connectionpool)
https://www.mtlnovel.com:443 "GET /wp-admin/admin-ajax.php?action=autosuggest&amp;q=strongest%20sword%20god HTTP/1.1" 200 None
2020-06-08 18:50:45,297 [DEBUG] (SEARCH_NOVEL)
Traceback (most recent call last):
File "./src/core/novel_search.py", line 22, in get_search_result
results = instance.search_novel(user_input)
File "./src/sources/mtlnovel.py", line 23, in search_novel
url = self.absolute_url("https://www.mtlnovel.com/?p=%s" % item['id'])
KeyError: 'id'

# Fixed code
def search_novel(self, query):
    response = self.submit_form(search_url, {"searchword": query})
    data = response.json()

    results = []
    for novel in data:
        titleSoup = BeautifulSoup(novel["name"], "lxml")
        results.append(
            {
                "title": titleSoup.body.text.title(),
                "url": novel_page_url % novel["nameunsigned"],
                "info": "Latest: %s" % novel["lastchapter"],
            }
        )
    # end for
    return results
# Buggy code
def search_novel(self, query):
    query = query.lower().replace(" ", "%20")
    # soup = self.get_soup(search_url % query)

    list_url = search_url % query
    data = self.get_json(list_url)["items"][0]["results"]

    results = []
    for item in data:
        url = self.absolute_url("https://es.mtlnovel.com/?p=%s" % item["id"])
        results.append(
            {
                "url": url,
                "title": item["title"],
                "info": self.search_novel_info(url),
            }
        )
    # end for

    return results


# Traceback (KeyError)
2020-06-08 18:50:45,291 [DEBUG] (urllib3.connectionpool)
https://www.mtlnovel.com:443 "GET /wp-admin/admin-ajax.php?action=autosuggest&amp;q=strongest%20sword%20god HTTP/1.1" 200 None
2020-06-08 18:50:45,297 [DEBUG] (SEARCH_NOVEL)
Traceback (most recent call last):
File "./src/core/novel_search.py", line 22, in get_search_result
results = instance.search_novel(user_input)
File "./src/sources/mtlnovel.py", line 23, in search_novel
url = self.absolute_url("https://www.mtlnovel.com/?p=%s" % item['id'])
KeyError: 'id'

# Fixed code
def search_novel(self, query):
    query = query.lower().replace(" ", "%20")
    # soup = self.get_soup(search_url % query)

    list_url = search_url % query
    data = self.get_json(list_url)["items"][0]["results"]

    results = []
    for item in data:
        url = item["permalink"]
        results.append(
            {
                "url": url,
                "title": item["title"],
                "info": self.search_novel_info(url),
            }
        )
    # end for

    return results
# Buggy code
def search_novel(self, query):
    query = query.lower().replace(" ", "%20")
    # soup = self.get_soup(search_url % query)

    list_url = search_url % query
    data = self.get_json(list_url)["items"][0]["results"]

    results = []
    for item in data:
        url = self.absolute_url("https://fr.mtlnovel.com/?p=%s" % item["id"])
        results.append(
            {
                "url": url,
                "title": item["title"],
                "info": self.search_novel_info(url),
            }
        )
    # end for

    return results


# Traceback (KeyError)
2020-06-08 18:50:45,291 [DEBUG] (urllib3.connectionpool)
https://www.mtlnovel.com:443 "GET /wp-admin/admin-ajax.php?action=autosuggest&amp;q=strongest%20sword%20god HTTP/1.1" 200 None
2020-06-08 18:50:45,297 [DEBUG] (SEARCH_NOVEL)
Traceback (most recent call last):
File "./src/core/novel_search.py", line 22, in get_search_result
results = instance.search_novel(user_input)
File "./src/sources/mtlnovel.py", line 23, in search_novel
url = self.absolute_url("https://www.mtlnovel.com/?p=%s" % item['id'])
KeyError: 'id'

# Fixed code
def search_novel(self, query):
    query = query.lower().replace(" ", "%20")
    # soup = self.get_soup(search_url % query)

    list_url = search_url % query
    data = self.get_json(list_url)["items"][0]["results"]

    results = []
    for item in data:
        url = item["permalink"]
        results.append(
            {
                "url": url,
                "title": item["title"],
                "info": self.search_novel_info(url),
            }
        )
    # end for

    return results
# Buggy code
def search_novel(self, query):
    query = query.lower().replace(" ", "%20")
    # soup = self.get_soup(search_url % query)

    list_url = search_url % query
    data = self.get_json(list_url)["items"][0]["results"]

    results = []
    for item in data:
        url = self.absolute_url("https://id.mtlnovel.com/?p=%s" % item["id"])
        results.append(
            {
                "url": url,
                "title": item["title"],
                "info": self.search_novel_info(url),
            }
        )
    # end for

    return results


# Traceback (KeyError)
2020-06-08 18:50:45,291 [DEBUG] (urllib3.connectionpool)
https://www.mtlnovel.com:443 "GET /wp-admin/admin-ajax.php?action=autosuggest&amp;q=strongest%20sword%20god HTTP/1.1" 200 None
2020-06-08 18:50:45,297 [DEBUG] (SEARCH_NOVEL)
Traceback (most recent call last):
File "./src/core/novel_search.py", line 22, in get_search_result
results = instance.search_novel(user_input)
File "./src/sources/mtlnovel.py", line 23, in search_novel
url = self.absolute_url("https://www.mtlnovel.com/?p=%s" % item['id'])
KeyError: 'id'

# Fixed code
def search_novel(self, query):
    query = query.lower().replace(" ", "%20")
    # soup = self.get_soup(search_url % query)

    list_url = search_url % query
    data = self.get_json(list_url)["items"][0]["results"]

    results = []
    for item in data:
        url = item["permalink"]
        results.append(
            {
                "url": url,
                "title": item["title"],
                "info": self.search_novel_info(url),
            }
        )
    # end for

    return results
# Buggy code
def search_novel(self, query):
    query = query.lower().replace(" ", "+")
    soup = self.get_soup(search_url % query)

    results = []
    for tr in soup.select("tr"):
        a = tr.select("td a")
        results.append(
            {
                "title": a[0].text.strip(),
                "url": self.absolute_url(a[0]["href"]),
                "info": a[1].text.strip(),
            }
        )
    # end for

    return results


# Traceback (KeyError)
2020-06-08 18:50:45,291 [DEBUG] (urllib3.connectionpool)
https://www.mtlnovel.com:443 "GET /wp-admin/admin-ajax.php?action=autosuggest&amp;q=strongest%20sword%20god HTTP/1.1" 200 None
2020-06-08 18:50:45,297 [DEBUG] (SEARCH_NOVEL)
Traceback (most recent call last):
File "./src/core/novel_search.py", line 22, in get_search_result
results = instance.search_novel(user_input)
File "./src/sources/mtlnovel.py", line 23, in search_novel
url = self.absolute_url("https://www.mtlnovel.com/?p=%s" % item['id'])
KeyError: 'id'

# Fixed code
def search_novel(self, query):
    query = query.lower().replace(" ", "+")
    soup = self.get_soup(search_url % query)
    results = []

    if soup.get_text(strip=True) == "Sorry! No novel founded!":
        return results
    # end if
    for tr in soup.select("tr"):
        a = tr.select("td a")
        results.append(
            {
                "title": a[0].text.strip(),
                "url": self.absolute_url(a[0]["href"]),
                "info": a[1].text.strip(),
            }
        )
    # end for

    return results
# Buggy code
def search_novel(self, query):
    url = search_url % quote(query.lower())
    logger.debug("Visiting: %s", url)
    soup = self.get_soup(url)

    results = []
    for li in soup.select(".book-list-info li"):
        results.append(
            {
                "title": li.select_one("a h4 b").text.strip(),
                "url": self.absolute_url(li.select_one(".book-img a")["href"]),
                "info": li.select_one(".update-info").text.strip(),
            }
        )
    # end for
    return results


# Traceback (KeyError)
2020-06-08 18:50:45,291 [DEBUG] (urllib3.connectionpool)
https://www.mtlnovel.com:443 "GET /wp-admin/admin-ajax.php?action=autosuggest&amp;q=strongest%20sword%20god HTTP/1.1" 200 None
2020-06-08 18:50:45,297 [DEBUG] (SEARCH_NOVEL)
Traceback (most recent call last):
File "./src/core/novel_search.py", line 22, in get_search_result
results = instance.search_novel(user_input)
File "./src/sources/mtlnovel.py", line 23, in search_novel
url = self.absolute_url("https://www.mtlnovel.com/?p=%s" % item['id'])
KeyError: 'id'

# Fixed code
def search_novel(self, query):
    url = search_url % quote(query.lower())
    logger.debug("Visiting: %s", url)
    soup = self.get_soup(url)

    results = []
    for li in soup.select(".book-list-info > ul > li"):
        results.append(
            {
                "title": li.select_one("a h4 b").text.strip(),
                "url": self.absolute_url(li.select_one(".book-img a")["href"]),
                "info": li.select_one(".update-info").text.strip(),
            }
        )
    # end for
    return results
# Buggy code
def search_novel(self, query):
    query = query.lower().replace(" ", "%20")
    # soup = self.get_soup(search_url % query)

    list_url = search_url % query
    data = self.get_json(list_url)["items"][0]["results"]

    results = []
    for item in data:
        url = self.absolute_url("https://www.mtlnovel.com/?p=%s" % item["id"])
        results.append(
            {
                "url": url,
                "title": item["title"],
                "info": self.search_novel_info(url),
            }
        )
    # end for

    return results


# Traceback (KeyError)
2020-06-08 18:50:45,291 [DEBUG] (urllib3.connectionpool)
https://www.mtlnovel.com:443 "GET /wp-admin/admin-ajax.php?action=autosuggest&amp;q=strongest%20sword%20god HTTP/1.1" 200 None
2020-06-08 18:50:45,297 [DEBUG] (SEARCH_NOVEL)
Traceback (most recent call last):
File "./src/core/novel_search.py", line 22, in get_search_result
results = instance.search_novel(user_input)
File "./src/sources/mtlnovel.py", line 23, in search_novel
url = self.absolute_url("https://www.mtlnovel.com/?p=%s" % item['id'])
KeyError: 'id'

# Fixed code
def search_novel(self, query):
    query = query.lower().replace(" ", "%20")
    # soup = self.get_soup(search_url % query)

    list_url = search_url % query
    data = self.get_json(list_url)["items"][0]["results"]

    results = []
    for item in data:
        url = item["permalink"]
        results.append(
            {
                "url": url,
                "title": item["title"],
                "info": self.search_novel_info(url),
            }
        )
    # end for

    return results
# Buggy code
def read_novel_info(self):
    # to get cookies and session info
    self.parse_content_css(self.home_url)

    # Determine cannonical novel name
    path_fragments = urlparse(self.novel_url).path.split("/")
    if path_fragments[1] == "books":
        self.novel_hash = path_fragments[2]
    else:
        self.novel_hash = path_fragments[-1]
    # end if
    self.novel_url = novel_page_url % self.novel_hash
    logger.info("Canonical name: %s", self.novel_hash)

    logger.debug("Visiting %s", self.novel_url)
    data = self.get_json(self.novel_url)

    self.novel_id = data["data"]["id"]
    logger.info("Novel ID: %s", self.novel_id)

    self.novel_title = data["data"]["name"]
    logger.info("Novel title: %s", self.novel_title)

    self.novel_cover = data["data"]["cover"]
    logger.info("Novel cover: %s", self.novel_cover)

    chapter_count = int(data["data"]["chapterCount"])
    self.get_list_of_chapters(chapter_count)


# Traceback (IndexError)
Fail to get bad selectors
Traceback (most recent call last):
File "c:\python38\lib\site-packages\lncrawl\sources\babelnovel.py", line 125, in parse_content_css
data = json.loads(unquote(content[0]))
IndexError: list index out of range

! Error: 'chapterCount'

# Fixed code
def read_novel_info(self):
    # to get cookies and session info
    self.parse_content_css(self.home_url)

    # Determine cannonical novel name
    path_fragments = urlparse(self.novel_url).path.split("/")
    if path_fragments[1] == "books":
        self.novel_hash = path_fragments[2]
    else:
        self.novel_hash = path_fragments[-1]
    # end if
    self.novel_url = novel_page_url % self.novel_hash
    logger.info("Canonical name: %s", self.novel_hash)

    logger.debug("Visiting %s", self.novel_url)
    data = self.get_json(self.novel_url)

    self.novel_id = data["data"]["id"]
    logger.info("Novel ID: %s", self.novel_id)

    self.novel_title = data["data"]["name"]
    logger.info("Novel title: %s", self.novel_title)

    self.novel_cover = data["data"]["cover"]
    logger.info("Novel cover: %s", self.novel_cover)

    chapter_count = int(data["data"]["releasedChapterCount"])
    self.get_list_of_chapters(chapter_count)
# Buggy code
def __init__(self, classifier):
    """
    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    """
    self.classifier = classifier


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def __init__(self, classifier, expectation=None):
    """
    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param expectation: An expectation over transformations to be applied when computing
                        classifier gradients and predictions.
    :type expectation: :class:`ExpectationOverTransformations`
    """
    self.classifier = classifier
    self.expectation = expectation
# Buggy code
def _loss(self, x_adv, target):
    """
    Compute the objective function value.

    :param x_adv: An array with the adversarial input.
    :type x_adv: `np.ndarray`
    :param target: An array with the target class (one-hot encoded).
    :type target: `np.ndarray`
    :return: A tuple holding the current logits and overall loss.
    :rtype: `(float, float)`
    """
    z = self.classifier.predict(np.array(x_adv, dtype=NUMPY_DTYPE), logits=True)
    z_target = np.sum(z * target, axis=1)
    z_other = np.max(
        z * (1 - target) + (np.min(z, axis=1) - 1)[:, np.newaxis] * target, axis=1
    )

    if self.targeted:
        # if targeted, optimize for making the target class most likely
        loss = np.maximum(
            z_other - z_target + self.confidence, np.zeros(x_adv.shape[0])
        )
    else:
        # if untargeted, optimize for making any other class most likely
        loss = np.maximum(
            z_target - z_other + self.confidence, np.zeros(x_adv.shape[0])
        )

    return z, loss


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def _loss(self, x_adv, target):
    """
    Compute the objective function value.

    :param x_adv: An array with the adversarial input.
    :type x_adv: `np.ndarray`
    :param target: An array with the target class (one-hot encoded).
    :type target: `np.ndarray`
    :return: A tuple holding the current logits and overall loss.
    :rtype: `(float, float)`
    """
    z = self._predict(np.array(x_adv, dtype=NUMPY_DTYPE), logits=True)
    z_target = np.sum(z * target, axis=1)
    z_other = np.max(
        z * (1 - target) + (np.min(z, axis=1) - 1)[:, np.newaxis] * target, axis=1
    )

    if self.targeted:
        # if targeted, optimize for making the target class most likely
        loss = np.maximum(
            z_other - z_target + self.confidence, np.zeros(x_adv.shape[0])
        )
    else:
        # if untargeted, optimize for making any other class most likely
        loss = np.maximum(
            z_target - z_other + self.confidence, np.zeros(x_adv.shape[0])
        )

    return z, loss
# Buggy code
def __init__(self, classifier, max_iter=100, epsilon=1e-6):
    """
    Create a DeepFool attack instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param max_iter: The maximum number of iterations.
    :type max_iter: `int`
    :param epsilon: Overshoot parameter.
    :type epsilon: `float`
    """
    super(DeepFool, self).__init__(classifier)
    params = {"max_iter": max_iter, "epsilon": epsilon}
    self.set_params(**params)


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def __init__(
    self,
    classifier,
    max_iter=100,
    epsilon=1e-6,
    nb_grads=10,
    batch_size=128,
    expectation=None,
):
    """
    Create a DeepFool attack instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param max_iter: The maximum number of iterations.
    :type max_iter: `int`
    :param epsilon: Overshoot parameter.
    :type epsilon: `float`
    :param nb_grads: The number of class gradients (top nb_grads w.r.t. prediction) to compute. This way only the
                     most likely classes are considered, speeding up the computation.
    :type nb_grads: `int`
    :param batch_size: Batch size
    :type batch_size: `int`
    :param expectation: An expectation over transformations to be applied when computing
                        classifier gradients and predictions.
    :type expectation: :class:`ExpectationOverTransformations`
    """
    super(DeepFool, self).__init__(classifier=classifier, expectation=expectation)
    params = {
        "max_iter": max_iter,
        "epsilon": epsilon,
        "nb_grads": nb_grads,
        "batch_size": batch_size,
    }
    self.set_params(**params)
# Buggy code
def set_params(self, **kwargs):
    """Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.

    :param max_iter: The maximum number of iterations.
    :type max_iter: `int`
    """
    # Save attack-specific parameters
    super(DeepFool, self).set_params(**kwargs)

    if not isinstance(self.max_iter, (int, np.int)) or self.max_iter <= 0:
        raise ValueError("The number of iterations must be a positive integer.")

    if self.epsilon < 0:
        raise ValueError("The overshoot parameter must not be negative.")

    return True


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def set_params(self, **kwargs):
    """
    Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.

    :param max_iter: The maximum number of iterations.
    :type max_iter: `int`
    :param epsilon: Overshoot parameter.
    :type epsilon: `float`
    :param nb_grads: The number of class gradients (top nb_grads w.r.t. prediction) to compute. This way only the
                     most likely classes are considered, speeding up the computation.
    :type nb_grads: `int`
    :param batch_size: Internal size of batches on which adversarial samples are generated.
    :type batch_size: `int`
    :param expectation: An expectation over transformations to be applied when computing
                        classifier gradients and predictions.
    :type expectation: :class:`ExpectationOverTransformations`
    """
    # Save attack-specific parameters
    super(DeepFool, self).set_params(**kwargs)

    if not isinstance(self.max_iter, (int, np.int)) or self.max_iter <= 0:
        raise ValueError("The number of iterations must be a positive integer.")

    if not isinstance(self.nb_grads, (int, np.int)) or self.nb_grads <= 0:
        raise ValueError(
            "The number of class gradients to compute must be a positive integer."
        )

    if self.epsilon < 0:
        raise ValueError("The overshoot parameter must not be negative.")

    if self.batch_size <= 0:
        raise ValueError("The batch size `batch_size` has to be positive.")

    return True
# Buggy code
def __init__(
    self,
    classifier,
    norm=np.inf,
    eps=0.3,
    targeted=False,
    random_init=False,
    batch_size=128,
):
    """
    Create a :class:`FastGradientMethod` instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param norm: Order of the norm. Possible values: np.inf, 1 or 2.
    :type norm: `int`
    :param eps: Attack step size (input variation)
    :type eps: `float`
    :param targeted: Should the attack target one specific class
    :type targeted: `bool`
    :param random_init: Whether to start at the original input or a random point within the epsilon ball
    :type random_init: `bool`
    :param batch_size: Batch size
    :type batch_size: `int`
    """
    super(FastGradientMethod, self).__init__(classifier)

    self.norm = norm
    self.eps = eps
    self.targeted = targeted
    self.random_init = random_init
    self.batch_size = batch_size


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def __init__(
    self,
    classifier,
    norm=np.inf,
    eps=0.3,
    targeted=False,
    random_init=False,
    batch_size=128,
    expectation=None,
):
    """
    Create a :class:`FastGradientMethod` instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param norm: Order of the norm. Possible values: np.inf, 1 or 2.
    :type norm: `int`
    :param eps: Attack step size (input variation)
    :type eps: `float`
    :param targeted: Should the attack target one specific class
    :type targeted: `bool`
    :param random_init: Whether to start at the original input or a random point within the epsilon ball
    :type random_init: `bool`
    :param batch_size: Batch size
    :type batch_size: `int`
    :param expectation: An expectation over transformations to be applied when computing
                        classifier gradients and predictions.
    :type expectation: :class:`ExpectationOverTransformations`
    """
    super(FastGradientMethod, self).__init__(classifier, expectation=expectation)

    self.norm = norm
    self.eps = eps
    self.targeted = targeted
    self.random_init = random_init
    self.batch_size = batch_size
# Buggy code
def _compute_perturbation(self, batch, batch_labels):
    # Pick a small scalar to avoid division by 0
    tol = 10e-8

    # Get gradient wrt loss; invert it if attack is targeted
    grad = self.classifier.loss_gradient(batch, batch_labels) * (
        1 - 2 * int(self.targeted)
    )

    # Apply norm bound
    if self.norm == np.inf:
        grad = np.sign(grad)
    elif self.norm == 1:
        ind = tuple(range(1, len(batch.shape)))
        grad = grad / (np.sum(np.abs(grad), axis=ind, keepdims=True) + tol)
    elif self.norm == 2:
        ind = tuple(range(1, len(batch.shape)))
        grad = grad / (np.sqrt(np.sum(np.square(grad), axis=ind, keepdims=True)) + tol)
    assert batch.shape == grad.shape

    return grad


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def _compute_perturbation(self, batch, batch_labels):
    # Pick a small scalar to avoid division by 0
    tol = 10e-8

    # Get gradient wrt loss; invert it if attack is targeted
    grad = self._loss_gradient(batch, batch_labels) * (1 - 2 * int(self.targeted))

    # Apply norm bound
    if self.norm == np.inf:
        grad = np.sign(grad)
    elif self.norm == 1:
        ind = tuple(range(1, len(batch.shape)))
        grad = grad / (np.sum(np.abs(grad), axis=ind, keepdims=True) + tol)
    elif self.norm == 2:
        ind = tuple(range(1, len(batch.shape)))
        grad = grad / (np.sqrt(np.sum(np.square(grad), axis=ind, keepdims=True)) + tol)
    assert batch.shape == grad.shape

    return grad
# Buggy code
def set_params(self, **kwargs):
    """
    Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.

    :param norm: Order of the norm. Possible values: np.inf, 1 or 2.
    :type norm: `int`
    :param eps: Maximum perturbation that the attacker can introduce.
    :type eps: `float`
    :param eps_step: Attack step size (input variation) at each iteration.
    :type eps_step: `float`
    """
    # Save attack-specific parameters
    super(BasicIterativeMethod, self).set_params(**kwargs)

    if self.eps_step > self.eps:
        raise ValueError(
            "The iteration step `eps_step` has to be smaller than the total attack `eps`."
        )

    if self.max_iter <= 0:
        raise ValueError(
            "The number of iterations `max_iter` has to be a positive integer."
        )

    return True


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def set_params(self, **kwargs):
    """
    Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.

    :param norm: Order of the norm. Possible values: np.inf, 1 or 2.
    :type norm: `int`
    :param eps: Maximum perturbation that the attacker can introduce.
    :type eps: `float`
    :param eps_step: Attack step size (input variation) at each iteration.
    :type eps_step: `float`
    :param random_init: Whether to start at the original input or a random point within the epsilon ball
    :type random_init: `bool`
    :param batch_size: Batch size
    :type batch_size: `int`
    """
    # Save attack-specific parameters
    super(BasicIterativeMethod, self).set_params(**kwargs)

    if self.eps_step > self.eps:
        raise ValueError(
            "The iteration step `eps_step` has to be smaller than the total attack `eps`."
        )

    if self.max_iter <= 0:
        raise ValueError(
            "The number of iterations `max_iter` has to be a positive integer."
        )

    return True
# Buggy code
def __init__(self, classifier, max_iter=1000, eta=0.01, batch_size=128):
    """
    Create a NewtonFool attack instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param max_iter: The maximum number of iterations.
    :type max_iter: `int`
    :param eta: The eta coefficient.
    :type eta: `float`
    :param batch_size: Batch size
    :type batch_size: `int`
    """
    super(NewtonFool, self).__init__(classifier)
    params = {"max_iter": max_iter, "eta": eta, "batch_size": batch_size}
    self.set_params(**params)


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def __init__(
    self, classifier, max_iter=1000, eta=0.01, batch_size=128, expectation=None
):
    """
    Create a NewtonFool attack instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param max_iter: The maximum number of iterations.
    :type max_iter: `int`
    :param eta: The eta coefficient.
    :type eta: `float`
    :param batch_size: Batch size
    :type batch_size: `int`
    :param expectation: An expectation over transformations to be applied when computing
                        classifier gradients and predictions.
    :type expectation: :class:`ExpectationOverTransformations`
    """
    super(NewtonFool, self).__init__(classifier)
    params = {
        "max_iter": max_iter,
        "eta": eta,
        "batch_size": batch_size,
        "expectation": expectation,
    }
    self.set_params(**params)
# Buggy code
def set_params(self, **kwargs):
    """Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.

    :param max_iter: The maximum number of iterations.
    :type max_iter: `int`
    :param eta: The eta coefficient.
    :type eta: `float`
    """
    # Save attack-specific parameters
    super(NewtonFool, self).set_params(**kwargs)

    if not isinstance(self.max_iter, (int, np.int)) or self.max_iter <= 0:
        raise ValueError("The number of iterations must be a positive integer.")

    if not isinstance(self.eta, (float, int, np.int)) or self.eta <= 0:
        raise ValueError("The eta coefficient must be a positive float.")

    if self.batch_size <= 0:
        raise ValueError("The batch size `batch_size` has to be positive.")

    return True


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def set_params(self, **kwargs):
    """Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.

    :param max_iter: The maximum number of iterations.
    :type max_iter: `int`
    :param eta: The eta coefficient.
    :type eta: `float`
    :param batch_size: Internal size of batches on which adversarial samples are generated.
    :type batch_size: `int`
    """
    # Save attack-specific parameters
    super(NewtonFool, self).set_params(**kwargs)

    if not isinstance(self.max_iter, (int, np.int)) or self.max_iter <= 0:
        raise ValueError("The number of iterations must be a positive integer.")

    if not isinstance(self.eta, (float, int, np.int)) or self.eta <= 0:
        raise ValueError("The eta coefficient must be a positive float.")

    if self.batch_size <= 0:
        raise ValueError("The batch size `batch_size` has to be positive.")

    return True
# Buggy code
def __init__(
    self,
    classifier,
    norm=np.inf,
    eps=0.3,
    eps_step=0.1,
    max_iter=20,
    targeted=False,
    random_init=False,
):
    """
    Create a :class:`ProjectedGradientDescent` instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param norm: Order of the norm. Possible values: np.inf, 1 or 2.
    :type norm: `int`
    :param eps: Maximum perturbation that the attacker can introduce.
    :type eps: `float`
    :param eps_step: Attack step size (input variation) at each iteration.
    :type eps_step: `float`
    :param targeted: Should the attack target one specific class
    :type targeted: `bool`
    :param random_init: Whether to start at the original input or a random point within the epsilon ball
    :type random_init: `bool`
    """
    super(ProjectedGradientDescent, self).__init__(
        classifier,
        norm=norm,
        eps=eps,
        eps_step=eps_step,
        max_iter=max_iter,
        targeted=targeted,
        random_init=random_init,
    )

    self._project = True


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def __init__(
    self,
    classifier,
    norm=np.inf,
    eps=0.3,
    eps_step=0.1,
    max_iter=20,
    targeted=False,
    random_init=False,
    batch_size=128,
    expectation=None,
):
    """
    Create a :class:`ProjectedGradientDescent` instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param norm: Order of the norm. Possible values: np.inf, 1 or 2.
    :type norm: `int`
    :param eps: Maximum perturbation that the attacker can introduce.
    :type eps: `float`
    :param eps_step: Attack step size (input variation) at each iteration.
    :type eps_step: `float`
    :param targeted: Should the attack target one specific class
    :type targeted: `bool`
    :param random_init: Whether to start at the original input or a random point within the epsilon ball
    :type random_init: `bool`
    :param batch_size: Batch size
    :type batch_size: `int`
    :param expectation: An expectation over transformations to be applied when computing
                        classifier gradients and predictions.
    :type expectation: :class:`ExpectationOverTransformations`
    """
    super(ProjectedGradientDescent, self).__init__(
        classifier,
        norm=norm,
        eps=eps,
        eps_step=eps_step,
        max_iter=max_iter,
        targeted=targeted,
        random_init=random_init,
        batch_size=batch_size,
        expectation=expectation,
    )

    self._project = True
# Buggy code
def __init__(self, classifier, theta=0.1, gamma=1.0):
    """
    Create a SaliencyMapMethod instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param theta: Perturbation introduced to each modified feature per step (can be positive or negative).
    :type theta: `float`
    :param gamma: Maximum percentage of perturbed features (between 0 and 1).
    :type gamma: `float`
    """
    super(SaliencyMapMethod, self).__init__(classifier)
    kwargs = {"theta": theta, "gamma": gamma}
    self.set_params(**kwargs)


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def __init__(self, classifier, theta=0.1, gamma=1.0, batch_size=128, expectation=None):
    """
    Create a SaliencyMapMethod instance.

    :param classifier: A trained model.
    :type classifier: :class:`Classifier`
    :param theta: Perturbation introduced to each modified feature per step (can be positive or negative).
    :type theta: `float`
    :param gamma: Maximum percentage of perturbed features (between 0 and 1).
    :type gamma: `float`
    :param batch_size: Batch size
    :type batch_size: `int`
    :param expectation: An expectation over transformations to be applied when computing
                        classifier gradients and predictions.
    :type expectation: :class:`ExpectationOverTransformations`
    """
    super(SaliencyMapMethod, self).__init__(classifier)
    kwargs = {
        "theta": theta,
        "gamma": gamma,
        "batch_size": batch_size,
        "expectation": expectation,
    }
    self.set_params(**kwargs)
# Buggy code
def set_params(self, **kwargs):
    """
    Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.

    :param theta: Perturbation introduced to each modified feature per step (can be positive or negative)
    :type theta: `float`
    :param gamma: Maximum percentage of perturbed features (between 0 and 1)
    :type gamma: `float`
    """
    # Save attack-specific parameters
    super(SaliencyMapMethod, self).set_params(**kwargs)

    if self.gamma <= 0 or self.gamma > 1:
        raise ValueError(
            "The total perturbation percentage `gamma` must be between 0 and 1."
        )

    return True


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def set_params(self, **kwargs):
    """
    Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.

    :param theta: Perturbation introduced to each modified feature per step (can be positive or negative)
    :type theta: `float`
    :param gamma: Maximum percentage of perturbed features (between 0 and 1)
    :type gamma: `float`
    :param batch_size: Internal size of batches on which adversarial samples are generated.
    :type batch_size: `int`
    """
    # Save attack-specific parameters
    super(SaliencyMapMethod, self).set_params(**kwargs)

    if self.gamma <= 0 or self.gamma > 1:
        raise ValueError(
            "The total perturbation percentage `gamma` must be between 0 and 1."
        )

    if self.batch_size <= 0:
        raise ValueError("The batch size `batch_size` has to be positive.")

    return True
# Buggy code
def _saliency_map(self, x, target, search_space):
    """
    Compute the saliency map of `x`. Return the top 2 coefficients in `search_space` that maximize / minimize
    the saliency map.

    :param x: One input sample
    :type x: `np.ndarray`
    :param target: Target class for `x`
    :type target: `int`
    :param search_space: The set of valid pairs of feature indices to search
    :type search_space: `set(tuple)`
    :return: The top 2 coefficients in `search_space` that maximize / minimize the saliency map
    :rtype: `tuple`
    """
    grads = self.classifier.class_gradient(x, label=target, logits=False)
    grads = np.reshape(grads, (-1, self._nb_features))[0]

    # Remove gradients for already used features
    used_features = list(set(range(self._nb_features)) - search_space)
    coeff = 2 * int(self.theta > 0) - 1
    grads[used_features] = -np.inf * coeff

    if self.theta > 0:
        ind = np.argpartition(grads, -2)[-2:]
    else:
        ind = np.argpartition(-grads, -2)[-2:]

    return tuple(ind)


# Traceback (IndexError)
Traceback (most recent call last):
File "cw_pytorch.py", line 172, in <module>
x_test_adv = cl2m.generate(inputs, **params)
File "/home/weitian/anaconda3/envs/xnor/lib/python3.6/site-packages/art/attacks/carlini.py", line 380, in generate
x_adv_batch_tanh[active_and_update_adv] = x_adv_batch_tanh[update_adv] + \
IndexError: boolean index did not match indexed array along dimension 0; dimension is 18 but corresponding boolean dimension is 17

# Fixed code
def _saliency_map(self, x, target, search_space):
    """
    Compute the saliency map of `x`. Return the top 2 coefficients in `search_space` that maximize / minimize
    the saliency map.

    :param x: A batch of input samples
    :type x: `np.ndarray`
    :param target: Target class for `x`
    :type target: `np.ndarray`
    :param search_space: The set of valid pairs of feature indices to search
    :type search_space: `np.ndarray`
    :return: The top 2 coefficients in `search_space` that maximize / minimize the saliency map
    :rtype: `np.ndarray`
    """
    grads = self._class_gradient(x, label=target, logits=False)
    grads = np.reshape(grads, (-1, self._nb_features))

    # Remove gradients for already used features
    used_features = 1 - search_space
    coeff = 2 * int(self.theta > 0) - 1
    grads[used_features == 1] = -np.inf * coeff

    if self.theta > 0:
        ind = np.argpartition(grads, -2, axis=1)[:, -2:]
    else:
        ind = np.argpartition(-grads, -2, axis=1)[:, -2:]

    return ind