ronantakizawa/codereview-bench huggingface dataset:
Repository: scipy/scipy
File: scipy/special/_add_newdocs.py (Python)

Code before:
    b : array_like
        `b` parameter values of ``gdtr(a, b, x)``. `b` is the "shape" parameter
        of the gamma distribution.
    p : array_like
        Probability values.
    out : ndarray, optional
        If a fourth argument is given, it must be a numpy.ndarray whose size
        matches the broadcast result of `a`, `b` and `x`. `out` is then the
        array returned by the function.

    Returns
    -------
    x : scalar or ndarray
        Values of the `x` parameter such that `p = gdtr(a, b, x)`.

    See Also
    --------
    gdtr : CDF of the gamma distribution.
    gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``.
    gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``.
    gammaincinv : Inverse of the incomplete regularized gamma function.

    Notes
    -----
    `gdtrix` is implemented in terms of the incomplete gamma inverse as
    `gdtrix(a, b, p)=gammaincinv(b, p)/a`.

    Examples
    --------
    First evaluate `gdtr`.

    >>> from scipy.special import gdtr, gdtrix
    >>> p = gdtr(1.2, 3.4, 5.6)
    >>> print(p)
    0.94378087442

    Verify the inverse.

    >>> gdtrix(1.2, 3.4, p)
    5.5999999999999996
    """)



add_newdoc("huber",
    r"""
    huber(delta, r, out=None)

    Huber loss function.

    .. math:: \text{huber}(\delta, r) = \begin{cases} \infty & \delta < 0  \\

Review comment (suggestion):
```suggestion
    ``gdtrix(a, b, p) = gammaincinv(b, p)/a `.
```

Code after:
    b : array_like
        `b` parameter values of ``gdtr(a, b, x)``. `b` is the "shape" parameter
        of the gamma distribution.
    p : array_like
        Probability values.
    out : ndarray, optional
        If a fourth argument is given, it must be a numpy.ndarray whose size
        matches the broadcast result of `a`, `b` and `x`. `out` is then the
        array returned by the function.

    Returns
    -------
    x : scalar or ndarray
        Values of the `x` parameter such that `p = gdtr(a, b, x)`.

    See Also
    --------
    gdtr : CDF of the gamma distribution.
    gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``.
    gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``.
    gammaincinv : Inverse of the incomplete regularized gamma function.

    Notes
    -----
    `gdtrix` is implemented in terms of the incomplete gamma inverse as
    ``gdtrix(a, b, p) = gammaincinv(b, p)/a``.

    Examples
    --------
    First evaluate `gdtr`.

    >>> from scipy.special import gdtr, gdtrix
    >>> p = gdtr(1.2, 3.4, 5.6)
    >>> print(p)
    0.94378087442

    Verify the inverse.

    >>> gdtrix(1.2, 3.4, p)
    5.6
    """)



add_newdoc("huber",
    r"""
    huber(delta, r, out=None)

    Huber loss function.

    .. math:: \text{huber}(\delta, r) = \begin{cases} \infty & \delta < 0  \\
Repository: scipy/scipy
File: scipy/linalg/src/_npymath.hh (C++)

Code before:
};


/*
 * Grab a real part of a possibly complex array.
 * This is for the work queries.
 */
inline float real_part(float value){ return value; }
inline double real_part(double value){ return value; }
inline float real_part(npy_complex64 value){ return npy_crealf(value); }
inline double real_part(npy_complex128 value){return npy_creal(value); }

// XXX: std::conj(double) -> complex(double)
inline float conj(float value){ return value; }
inline double conj(double value){ return value; }
inline npy_complex64 conj(npy_complex64 value){ return npy_cpackf(npy_crealf(value), -npy_cimagf(value)); }
inline npy_complex128 conj(npy_complex128 value){return npy_cpack(npy_creal(value), -npy_cimag(value)); }


// complex from two reals
inline npy_complex64 cpack(float re, float im) {return npy_cpackf(re, im);}
inline npy_complex128 cpack(double re, double im) {return npy_cpack(re, im);}


/*
 * Debug helper: print out a npy_{cfloat,cdouble} value
 */
std::ostream& operator<<(std::ostream& os, npy_complex64 x) {
    os << "(" << npy_crealf(x) << ", " << npy_cimagf(x) << ")";
    return os;
}
std::ostream& operator<<(std::ostream& os, npy_complex128 x) {
    os << "(" << npy_creal(x) << ", " << npy_cimag(x) << ")";
    return os;
}


Review comment (bug):
```suggestion
 * Debug helper: print out an npy_{cfloat,cdouble} value
```

Code after:
};


/*
 * Grab a real part of a possibly complex array.
 * This is for the work queries.
 */
inline float real_part(float value){ return value; }
inline double real_part(double value){ return value; }
inline float real_part(npy_complex64 value){ return npy_crealf(value); }
inline double real_part(npy_complex128 value){return npy_creal(value); }

// XXX: std::conj(double) -> complex(double)
inline float conj(float value){ return value; }
inline double conj(double value){ return value; }
inline npy_complex64 conj(npy_complex64 value){ return npy_cpackf(npy_crealf(value), -npy_cimagf(value)); }
inline npy_complex128 conj(npy_complex128 value){return npy_cpack(npy_creal(value), -npy_cimag(value)); }


// complex from two reals
inline npy_complex64 cpack(float re, float im) {return npy_cpackf(re, im);}
inline npy_complex128 cpack(double re, double im) {return npy_cpack(re, im);}


/*
 * Debug helper: print out an npy_{cfloat,cdouble} value
 */
std::ostream& operator<<(std::ostream& os, npy_complex64 x) {
    os << "(" << npy_crealf(x) << ", " << npy_cimagf(x) << ")";
    return os;
}
std::ostream& operator<<(std::ostream& os, npy_complex128 x) {
    os << "(" << npy_creal(x) << ", " << npy_cimag(x) << ")";
    return os;
}
Repository: scipy/scipy
File: scipy/special/tests/test_ufunc_signatures.py (Python)

Code before:


@pytest.mark.parametrize("ufunc", _multi_arg_public_ufuncs)
def test_nep50(ufunc):
    # Test that functions with multiple arguments respect nep50 promotion rules.
    rng = np.random.default_rng(1234)
    # As in test_ufunc_signatures, filter out signatures involving integers.
    types = set(sig for sig in ufunc.types
                if not ("l" in sig or "i" in sig or "q" in sig or "p" in sig))
    for sig in types:
        input_types, output_types = sig.split("->")
        # since we only care about dtypes and not values here, just use an appropriately
        # typed nan for each argument.
        args = [_get_nan_val(typecode) for typecode in input_types]
        # swap out a random one of the nans with an appropriately typed numpy scalar.
        idx = rng.choice(len(args))
        args[idx] = float("nan") if np.isrealobj(args[idx]) else complex("nan")
        result = ufunc(*args)
        result = [result] if len(output_types) == 1 else result
        result = np.asarray(result)
        
        # Test that the output is an appropriately typed nan. This also implicitly
        # tests that ufuncs propagate nans correctly.
        assert_equal(
            result, np.asarray([_get_nan_val(typecode) for typecode in output_types],
            strict=True)
        )


Review comment (suggestion):
```suggestion
            result, np.asarray([_get_nan_val(typecode) for typecode in output_types]),
            strict=True
```

Code after:


@pytest.mark.parametrize("ufunc", _multi_arg_public_ufuncs)
def test_nep50(ufunc):
    # Test that functions with multiple arguments respect nep50 promotion rules.
    rng = np.random.default_rng(1234)
    # As in test_ufunc_signatures, filter out signatures involving integers.
    types = set(sig for sig in ufunc.types
                if not ("l" in sig or "i" in sig or "q" in sig or "p" in sig))
    for sig in types:
        input_types, output_types = sig.split("->")
        # since we only care about dtypes and not values here, just use an appropriately
        # typed nan for each argument.
        args = [_get_nan_val(typecode) for typecode in input_types]
        # swap out a random one of the nans with an appropriately typed numpy scalar.
        idx = rng.choice(len(args))
        args[idx] = float("nan") if np.isrealobj(args[idx]) else complex("nan")
        result = ufunc(*args)
        result = [result] if len(output_types) == 1 else result
        result = np.asarray(result)
        
        # Test that the output is an appropriately typed nan. This also implicitly
        # tests that ufuncs propagate nans correctly.
        assert_equal(
            result, np.asarray([_get_nan_val(typecode) for typecode in output_types]),
            strict=True
        )
Repository: scipy/scipy
File: scipy/sparse/sparsetools/csr.h (C/C++)

Code before:
#ifndef __CSR_H__
#define __CSR_H__

#include <set>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>

#include "util.h"
#include "dense.h"

template <class I, class T>
struct csr_array {
    const I n_row;
    const I n_col;
    I *indptr;
    I *indices;
    T *data;
};

template <class I, class T>
struct const_csr_array {
    const I n_row;
    const I n_col;
    const I *indptr;
    const I *indices;
    const T *data;
};

/*
 * Extract k-th diagonal of CSR matrix A
 *
 * Input Arguments:
 *   I  k             - diagonal to extract
 *   I  n_row         - number of rows in A
 *   I  n_col         - number of columns in A
 *   I  Ap[n_row+1]   - row pointer
 *   I  Aj[nnz(A)]    - column indices
 *   T  Ax[n_col]     - nonzeros
 *
 * Output Arguments:
 *   T  Yx[min(n_row,n_col)] - diagonal entries
 *
 * Note:
 *   Output array Yx must be preallocated
 *
 *   Duplicate entries will be summed.

Review comment (suggestion):
One thought that just occurred to me now: we might be able to avoid the second struct here if we use `csr_array<const T>`. I haven't tried it, though.

Code after:
#ifndef __CSR_H__
#define __CSR_H__

#include <set>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>

#include "util.h"
#include "dense.h"

template <class I, class T>
struct csr_array {
    const I n_row;
    const I n_col;
    I *indptr;
    I *indices;
    T *data;
};

/*
 * Extract k-th diagonal of CSR matrix A
 *
 * Input Arguments:
 *   I  k             - diagonal to extract
 *   I  n_row         - number of rows in A
 *   I  n_col         - number of columns in A
 *   I  Ap[n_row+1]   - row pointer
 *   I  Aj[nnz(A)]    - column indices
 *   T  Ax[n_col]     - nonzeros
 *
 * Output Arguments:
 *   T  Yx[min(n_row,n_col)] - diagonal entries
 *
 * Note:
 *   Output array Yx must be preallocated
 *
 *   Duplicate entries will be summed.
 *
 *   Complexity: Linear.  Specifically O(nnz(A) + min(n_row,n_col))
 *
 */
template <class I, class T>
void csr_diagonal(const I k,
                  const I n_row,
                  const I n_col,
                  const I Ap[],
Repository: servo/servo
File: components/script/security_manager.rs (Rust)

Code before:

    fn process_response_chunk(&mut self, _: RequestId, chunk: Vec<u8>) {
        _ = chunk;
    }

    fn process_response_eof(
        &mut self,
        _: RequestId,
        response: Result<ResourceFetchTiming, NetworkError>,
    ) {
        _ = response;
    }

    fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming {
        &mut self.resource_timing
    }

    fn resource_timing(&self) -> &ResourceFetchTiming {
        &self.resource_timing
    }

    fn submit_resource_timing(&mut self) {
        submit_timing(self, CanGc::note())
    }

    fn process_csp_violations(&mut self, _request_id: RequestId, _violations: Vec<Violation>) {}
}

impl ResourceTimingListener for CSPReportUriFetchListener {
    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
        (InitiatorType::Other, self.endpoint.clone())
    }

    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
        self.global.root()
    }
}

impl PreInvoke for CSPReportUriFetchListener {
    fn should_invoke(&self) -> bool {
        true
    }
}


Review comment (bug):
I realized that trying to send CSP errors about an endpoint to send CSP errors to would result in an infinite loop. Given that we also don't send any for `report-to`, this seems like a footgun.

Code after:
        _ = fetch_metadata;
    }

    fn process_response_chunk(&mut self, _: RequestId, chunk: Vec<u8>) {
        _ = chunk;
    }

    fn process_response_eof(
        &mut self,
        _: RequestId,
        response: Result<ResourceFetchTiming, NetworkError>,
    ) {
        _ = response;
    }

    fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming {
        &mut self.resource_timing
    }

    fn resource_timing(&self) -> &ResourceFetchTiming {
        &self.resource_timing
    }

    fn submit_resource_timing(&mut self) {
        submit_timing(self, CanGc::note())
    }

    fn process_csp_violations(&mut self, _request_id: RequestId, _violations: Vec<Violation>) {}
}

impl ResourceTimingListener for CSPReportUriFetchListener {
    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
        (InitiatorType::Other, self.endpoint.clone())
    }

    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
        self.global.root()
    }
}

impl PreInvoke for CSPReportUriFetchListener {
    fn should_invoke(&self) -> bool {
        true
    }
}
Repository: servo/servo
File: components/shared/net/response.rs (Rust)

Code before:
            resource_timing: Arc::new(Mutex::new(ResourceFetchTiming::new(
                ResourceTimingType::Error,
            ))),
            range_requested: false,
            redirect_taint: Default::default(),
        }
    }

    pub fn url(&self) -> Option<&ServoUrl> {
        self.url.as_ref()
    }

    pub fn is_network_error(&self) -> bool {
        matches!(self.response_type, ResponseType::Error(..))
    }

    pub fn get_network_error(&self) -> Option<&NetworkError> {
        match self.response_type {
            ResponseType::Error(ref e) => Some(e),
            _ => None,
        }
    }

    pub fn set_network_error(&mut self, e: NetworkError) {
        self.response_type = ResponseType::Error(e);
    }

    pub fn actual_response(&self) -> &Response {
        if self.return_internal && self.internal_response.is_some() {
            self.internal_response.as_ref().unwrap()
        } else {
            self
        }
    }

    pub fn actual_response_mut(&mut self) -> &mut Response {
        if self.return_internal && self.internal_response.is_some() {
            self.internal_response.as_mut().unwrap()
        } else {
            self
        }
    }

    pub fn to_actual(self) -> Response {
        if self.return_internal && self.internal_response.is_some() {
            *self.internal_response.unwrap()
        } else {
            self
        }
    }


Review comment (suggestion):
```suggestion
    pub fn set_network_error(&mut self, network_error: NetworkError) {
        self.response_type = ResponseType::Error(network_error);
    }
```

Code after:
            resource_timing: Arc::new(Mutex::new(ResourceFetchTiming::new(
                ResourceTimingType::Error,
            ))),
            range_requested: false,
            redirect_taint: Default::default(),
        }
    }

    pub fn url(&self) -> Option<&ServoUrl> {
        self.url.as_ref()
    }

    pub fn is_network_error(&self) -> bool {
        matches!(self.response_type, ResponseType::Error(..))
    }

    pub fn get_network_error(&self) -> Option<&NetworkError> {
        match self.response_type {
            ResponseType::Error(ref e) => Some(e),
            _ => None,
        }
    }

    pub fn set_network_error(&mut self, network_error: NetworkError) {
        self.response_type = ResponseType::Error(network_error);
    }

    pub fn actual_response(&self) -> &Response {
        if self.return_internal && self.internal_response.is_some() {
            self.internal_response.as_ref().unwrap()
        } else {
            self
        }
    }

    pub fn actual_response_mut(&mut self) -> &mut Response {
        if self.return_internal && self.internal_response.is_some() {
            self.internal_response.as_mut().unwrap()
        } else {
            self
        }
    }

    pub fn to_actual(self) -> Response {
        if self.return_internal && self.internal_response.is_some() {
            *self.internal_response.unwrap()
        } else {
            self
        }
    }
Repository: servo/servo
File: components/script/dom/toggleevent.rs (Rust)

Code before:
    }

    /// <https://html.spec.whatwg.org/multipage/#dom-toggleevent-newstate>
    fn NewState(&self) -> DOMString {
        self.new_state.clone()
    }

    /// <https://html.spec.whatwg.org/multipage/#dom-toggleevent-source>
    fn GetSource(&self) -> Option<DomRoot<Element>> {
        // The source getter steps are to return the result of retargeting source against this's currentTarget.
        self.source.as_ref()?;

        if let Some(current_target) = self.event.GetCurrentTarget() {
            return self.source.as_ref().and_then(|source| {
                let retargeted = source.upcast::<EventTarget>().retarget(&current_target);
                retargeted.downcast::<Element>().map(DomRoot::from_ref)
            });
        }

        self.source.as_ref().and_then(|source| {
            let document = source.upcast::<Node>().GetOwnerDocument().unwrap();
            let retargeted = source
                .upcast::<EventTarget>()
                .retarget(document.upcast::<EventTarget>());
            retargeted.downcast::<Element>().map(DomRoot::from_ref)
        })
    }
}


Review comment (suggestion):
The spec doesn't state that we should use the owner document if `currentTarget` is `null`. Should we instead return `None` when that's the case? E.g. something like

```suggestion
        let source = self.source.as_ref()?;
        let current_target = self.event.GetCurrentTarget()?;
        let retargeted = source.upcast::<EventTarget>().retarget(&current_target);
        retargeted.downcast::<Element>().map(DomRoot::from_ref)
```

Code after:
    /// <https://html.spec.whatwg.org/multipage/#dom-toggleevent-oldstate>
    fn OldState(&self) -> DOMString {
        self.old_state.clone()
    }

    /// <https://html.spec.whatwg.org/multipage/#dom-toggleevent-newstate>
    fn NewState(&self) -> DOMString {
        self.new_state.clone()
    }

    /// <https://html.spec.whatwg.org/multipage/#dom-toggleevent-source>
    fn GetSource(&self) -> Option<DomRoot<Element>> {
        // The source getter steps are to return the result of retargeting source against this's currentTarget.
        let source = self.source.as_ref()?;

        if let Some(current_target) = self.event.GetCurrentTarget() {
            let retargeted = source.upcast::<EventTarget>().retarget(&current_target);
            return retargeted.downcast::<Element>().map(DomRoot::from_ref);
        }

        let document = source.upcast::<Node>().GetOwnerDocument().unwrap();
        let retargeted = source
            .upcast::<EventTarget>()
            .retarget(document.upcast::<EventTarget>());
        retargeted.downcast::<Element>().map(DomRoot::from_ref)
    }
}
Repository: servo/servo
File: components/profile/system_reporter.rs (Rust)

Code before:

    let mut f = File::open("/proc/self/statm").ok()?;
    let mut contents = String::new();
    f.read_to_string(&mut contents).ok()?;
    let s = contents.split_whitespace().nth(field)?;
    let npages = s.parse::<usize>().ok()?;
    Some(npages * page_size())
}

#[cfg(target_os = "linux")]
fn vsize() -> Option<usize> {
    proc_self_statm_field(0)
}

#[cfg(target_os = "linux")]
fn resident() -> Option<usize> {
    proc_self_statm_field(1)
}
#[cfg(target_os = "linux")]
fn pss() -> Option<usize> {
    use std::fs::File;
    use std::io::Read;
    let mut f = File::open("/proc/self/smaps_rollup").ok()?;
    let mut contents = String::new();
    f.read_to_string(&mut contents).ok()?;
    let pss_line = contents.split("\n").find(|s| s.contains("Pss:"))?;

    // String looks like: "Pss:                 227 kB"
    let pss_str = pss_line.split_whitespace().nth(1)?;
    pss_str.parse().ok()
}

#[cfg(not(target_os = "linux"))]
fn pss() -> Option<usize> {
    None
}

#[cfg(target_os = "macos")]
fn vsize() -> Option<usize> {
    virtual_size()
}

#[cfg(target_os = "macos")]
fn resident() -> Option<usize> {
    resident_size()
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn vsize() -> Option<usize> {
    None
}

Review comment (suggestion):
```suggestion
    let mut file = File::open("/proc/self/smaps_rollup").ok()?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).ok()?;
    let pss_line = contents.split("\n").find(|string| string.contains("Pss:"))?;
```

Code after:

    let mut f = File::open("/proc/self/statm").ok()?;
    let mut contents = String::new();
    f.read_to_string(&mut contents).ok()?;
    let s = contents.split_whitespace().nth(field)?;
    let npages = s.parse::<usize>().ok()?;
    Some(npages * page_size())
}

#[cfg(target_os = "linux")]
fn vsize() -> Option<usize> {
    proc_self_statm_field(0)
}

#[cfg(target_os = "linux")]
fn resident() -> Option<usize> {
    proc_self_statm_field(1)
}
#[cfg(target_os = "linux")]
fn proportional_set_size() -> Option<usize> {
    use std::fs::File;
    use std::io::Read;
    let mut file = File::open("/proc/self/smaps_rollup").ok()?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).ok()?;
    let pss_line = contents
        .split("\n")
        .find(|string| string.contains("Pss:"))?;

    // String looks like: "Pss:                 227 kB"
    let pss_str = pss_line.split_whitespace().nth(1)?;
    pss_str.parse().ok()
}

#[cfg(not(target_os = "linux"))]
fn proportional_set_size() -> Option<usize> {
    None
}

#[cfg(target_os = "macos")]
fn vsize() -> Option<usize> {
    virtual_size()
}

#[cfg(target_os = "macos")]
fn resident() -> Option<usize> {
    resident_size()
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn vsize() -> Option<usize> {