The following issues were found

android/pytorch_android/src/androidTest/java/org/pytorch/PytorchHostTests.java
5 issues
In J2EE, getClassLoader() might not work as expected. Use Thread.currentThread().getContextClassLoader() instead.
Error

Line: 16

                protected String assetFilePath(String assetName) throws IOException {
    Path tempFile = Files.createTempFile("test", ".pt");
    try (InputStream resource =
        Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("test.pt"))) {
      Files.copy(resource, tempFile, StandardCopyOption.REPLACE_EXISTING);
    }
    return tempFile.toAbsolutePath().toString();
  }
}

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 16

                protected String assetFilePath(String assetName) throws IOException {
    Path tempFile = Files.createTempFile("test", ".pt");
    try (InputStream resource =
        Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("test.pt"))) {
      Files.copy(resource, tempFile, StandardCopyOption.REPLACE_EXISTING);
    }
    return tempFile.toAbsolutePath().toString();
  }
}

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 16

                protected String assetFilePath(String assetName) throws IOException {
    Path tempFile = Files.createTempFile("test", ".pt");
    try (InputStream resource =
        Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("test.pt"))) {
      Files.copy(resource, tempFile, StandardCopyOption.REPLACE_EXISTING);
    }
    return tempFile.toAbsolutePath().toString();
  }
}

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 19

                      Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("test.pt"))) {
      Files.copy(resource, tempFile, StandardCopyOption.REPLACE_EXISTING);
    }
    return tempFile.toAbsolutePath().toString();
  }
}

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 19

                      Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("test.pt"))) {
      Files.copy(resource, tempFile, StandardCopyOption.REPLACE_EXISTING);
    }
    return tempFile.toAbsolutePath().toString();
  }
}

            

Reported by PMD.

.circleci/cimodel/data/simple/macos_definitions.py
5 issues
Missing module docstring
Error

Line: 1 Column: 1

              class MacOsJob:
    def __init__(self, os_version, is_build=False, is_test=False, extra_props=tuple()):
        # extra_props is tuple type, because mutable data structures for argument defaults
        # is not recommended.
        self.os_version = os_version
        self.is_build = is_build
        self.is_test = is_test
        self.extra_props = dict(extra_props)


            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 1 Column: 1

              class MacOsJob:
    def __init__(self, os_version, is_build=False, is_test=False, extra_props=tuple()):
        # extra_props is tuple type, because mutable data structures for argument defaults
        # is not recommended.
        self.os_version = os_version
        self.is_build = is_build
        self.is_test = is_test
        self.extra_props = dict(extra_props)


            

Reported by Pylint.

Missing class docstring
Error

Line: 1 Column: 1

              class MacOsJob:
    def __init__(self, os_version, is_build=False, is_test=False, extra_props=tuple()):
        # extra_props is tuple type, because mutable data structures for argument defaults
        # is not recommended.
        self.os_version = os_version
        self.is_build = is_build
        self.is_test = is_test
        self.extra_props = dict(extra_props)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 10 Column: 5

                      self.is_test = is_test
        self.extra_props = dict(extra_props)

    def gen_tree(self):
        non_phase_parts = ["pytorch", "macos", self.os_version, "py3"]

        extra_name_list = [name for name, exist in self.extra_props.items() if exist]
        full_job_name_list = non_phase_parts + extra_name_list + [
            'build' if self.is_build else None,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 51 Column: 1

              ]


def get_workflow_jobs():
    return [item.gen_tree() for item in WORKFLOW_DATA]

            

Reported by Pylint.

caffe2/python/layers/bucket_weighted.py
5 issues
Missing module docstring
Error

Line: 1 Column: 1

              ## @package bucket_weighted
# Module caffe2.python.layers.bucket_weighted





import logging
import numpy as np

            

Reported by Pylint.

Missing class docstring
Error

Line: 22 Column: 1

              logger = logging.getLogger(__name__)


class BucketWeighted(ModelLayer):
    def __init__(self, model, input_record, max_score=0, bucket_boundaries=None,
                 hash_buckets=True, weight_optim=None, name="bucket_weighted"):
        super(BucketWeighted, self).__init__(model, name, input_record)

        assert isinstance(input_record, schema.List), "Incorrect input type"

            

Reported by Pylint.

Too many arguments (8/5)
Error

Line: 23 Column: 5

              

class BucketWeighted(ModelLayer):
    def __init__(self, model, input_record, max_score=0, bucket_boundaries=None,
                 hash_buckets=True, weight_optim=None, name="bucket_weighted"):
        super(BucketWeighted, self).__init__(model, name, input_record)

        assert isinstance(input_record, schema.List), "Incorrect input type"
        self.bucket_boundaries = bucket_boundaries

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 25 Column: 9

              class BucketWeighted(ModelLayer):
    def __init__(self, model, input_record, max_score=0, bucket_boundaries=None,
                 hash_buckets=True, weight_optim=None, name="bucket_weighted"):
        super(BucketWeighted, self).__init__(model, name, input_record)

        assert isinstance(input_record, schema.List), "Incorrect input type"
        self.bucket_boundaries = bucket_boundaries
        self.hash_buckets = hash_buckets
        if bucket_boundaries is not None:

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 27
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                               hash_buckets=True, weight_optim=None, name="bucket_weighted"):
        super(BucketWeighted, self).__init__(model, name, input_record)

        assert isinstance(input_record, schema.List), "Incorrect input type"
        self.bucket_boundaries = bucket_boundaries
        self.hash_buckets = hash_buckets
        if bucket_boundaries is not None:
            self.shape = len(bucket_boundaries) + 1
        elif max_score > 0:

            

Reported by Bandit.

caffe2/contrib/opencl/OpenCL/cl.hpp
5 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 513 Column: 17 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      if( size > 0 ) {
            str_ = new char[size_+1];
            if (str_ != NULL) {
                memcpy(str_, str, size_  * sizeof(char));
                str_[size_] = '\0';
            }
            else {
                size_ = 0;
            }

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 537 Column: 17 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      if( size_ > 0 ) {
            str_ = new char[size_ + 1];
            if (str_ != NULL) {
                memcpy(str_, str, (size_ + 1) * sizeof(char));
            }
        }
    }

    void resize( ::size_t n )

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 563 Column: 17 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                          size_ = n;
            
            if(str_) {
                memcpy(newString, str_, (copySize + 1) * sizeof(char));
            }
            if( copySize < size_ ) {
                memset(newString + copySize, 0, size_ - copySize);
            }
            newString[size_] = '\0';

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 612 Column: 17 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                          size_ = rhs.size_;
            
            if (str_ != NULL) {
                memcpy(str_, rhs.str_, (size_ + 1) * sizeof(char));
            }
            else {
                size_ = 0;
            }
        }

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 532 Column: 22 CWE codes: 126

                      str_(NULL)
    {
        if( str ) {
            size_= ::strlen(str);
        }
        if( size_ > 0 ) {
            str_ = new char[size_ + 1];
            if (str_ != NULL) {
                memcpy(str_, str, (size_ + 1) * sizeof(char));

            

Reported by FlawFinder.

aten/src/ATen/test/math_kernel_test.cpp
5 issues
atol - Unless checked, the resulting number can exceed the expected range
Security

Line: 14 Column: 38 CWE codes: 190
Suggestion: If source untrusted, check both minimum and maximum, even if the input had no minus sign (large numbers can roll over into negative number; consider saving to an unsigned value if that is intended)

                    << t1.sizes() << " v.s. " << t2.sizes() << std::endl;
    return false;
  }
  bool equal = t1.allclose(t2, rtol, atol);
  if (!equal) {
    std::cerr << "Difference in tensor value: \nFirst tensor:\n"
        << t1 << "\nSecond tensor:\n" << t2 << std::endl;
  }
  return equal;

            

Reported by FlawFinder.

atol - Unless checked, the resulting number can exceed the expected range
Security

Line: 22 Column: 50 CWE codes: 190
Suggestion: If source untrusted, check both minimum and maximum, even if the input had no minus sign (large numbers can roll over into negative number; consider saving to an unsigned value if that is intended)

                return equal;
}

#define ASSERT_ALLCLOSE_TOLERANCES(t1, t2, rtol, atol) \
  ASSERT_TRUE(allClose(t1, t2, rtol, atol));

// Ideally we want to test both forward and backward on math kernels but I
// haven't found an easy way to do it.  Currently we only test forward here
// and rely on backward tests of each at:: function used in math kernels.

            

Reported by FlawFinder.

atol - Unless checked, the resulting number can exceed the expected range
Security

Line: 23 Column: 38 CWE codes: 190
Suggestion: If source untrusted, check both minimum and maximum, even if the input had no minus sign (large numbers can roll over into negative number; consider saving to an unsigned value if that is intended)

              }

#define ASSERT_ALLCLOSE_TOLERANCES(t1, t2, rtol, atol) \
  ASSERT_TRUE(allClose(t1, t2, rtol, atol));

// Ideally we want to test both forward and backward on math kernels but I
// haven't found an easy way to do it.  Currently we only test forward here
// and rely on backward tests of each at:: function used in math kernels.
TEST(MathKernelTest, NativeGroupNorm) {

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 15 Column: 8 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                  return false;
  }
  bool equal = t1.allclose(t2, rtol, atol);
  if (!equal) {
    std::cerr << "Difference in tensor value: \nFirst tensor:\n"
        << t1 << "\nSecond tensor:\n" << t2 << std::endl;
  }
  return equal;
}

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 19 Column: 10 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                  std::cerr << "Difference in tensor value: \nFirst tensor:\n"
        << t1 << "\nSecond tensor:\n" << t2 << std::endl;
  }
  return equal;
}

#define ASSERT_ALLCLOSE_TOLERANCES(t1, t2, rtol, atol) \
  ASSERT_TRUE(allClose(t1, t2, rtol, atol));


            

Reported by FlawFinder.

aten/src/ATen/cpu/vec/vec256/vec256_qint.h
5 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 247 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

              
    void store(void* ptr, int count = size()) const {
      if (count != size()) {
        memcpy(ptr, &vals, count * sizeof(value_type));
      } else {
        _mm256_storeu_si256((__m256i*)ptr, vals);
      }
    }


            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 427 Column: 13 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

              
    void store(void* ptr, int count = size()) const {
        if (count != size()) {
            memcpy(ptr, &vals, count * sizeof(value_type));
        } else {
            _mm256_storeu_si256((__m256i*)ptr, vals);
        }
    }


            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 593 Column: 13 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

              
    void store(void* ptr, int count = size()) const {
        if (count != size()) {
            memcpy(ptr, &vals, count * sizeof(value_type));
        } else {
            _mm256_storeu_si256((__m256i*)ptr, vals);
        }
    }


            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 765 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                }

  VectorizedQuantizedConverter(const void* ptr) {
    memcpy(vals.data(), ptr, sizeof(value_type) * size());
  }

  void store(void* ptr, int count = size()) const {
    memcpy(ptr, vals.data(), count * sizeof(value_type));
  }

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 769 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                }

  void store(void* ptr, int count = size()) const {
    memcpy(ptr, vals.data(), count * sizeof(value_type));
  }

  float_vec_return_type dequantize(
      Vectorized<float> scale,
      Vectorized<float> zero_point,

            

Reported by FlawFinder.

caffe2/mobile/contrib/libopencl-stub/include/CL/cl.hpp
5 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 507 Column: 17 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      if( size > 0 ) {
            str_ = new char[size_+1];
            if (str_ != NULL) {
                memcpy(str_, str, size_  * sizeof(char));
                str_[size_] = '\0';
            }
            else {
                size_ = 0;
            }

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 531 Column: 17 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      if( size_ > 0 ) {
            str_ = new char[size_ + 1];
            if (str_ != NULL) {
                memcpy(str_, str, (size_ + 1) * sizeof(char));
            }
        }
    }

    void resize( ::size_t n )

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 557 Column: 17 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                          size_ = n;
            
            if(str_) {
                memcpy(newString, str_, (copySize + 1) * sizeof(char));
            }
            if( copySize < size_ ) {
                memset(newString + copySize, 0, size_ - copySize);
            }
            newString[size_] = '\0';

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 606 Column: 17 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                          size_ = rhs.size_;
            
            if (str_ != NULL) {
                memcpy(str_, rhs.str_, (size_ + 1) * sizeof(char));
            }
            else {
                size_ = 0;
            }
        }

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 526 Column: 22 CWE codes: 126

                      str_(NULL)
    {
        if( str ) {
            size_= ::strlen(str);
        }
        if( size_ > 0 ) {
            str_ = new char[size_ + 1];
            if (str_ != NULL) {
                memcpy(str_, str, (size_ + 1) * sizeof(char));

            

Reported by FlawFinder.

caffe2/python/layers/constant_weight.py
5 issues
self.output_schema is not callable
Error

Line: 43 Column: 13

                  def add_ops(self, net):
        net.WeightedSum(
            [b for x_w_pair in zip(self.data, self.weights) for b in x_w_pair],
            self.output_schema()
        )

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # @package constant_weight
# Module caffe2.fb.python.layers.constant_weight





from caffe2.python import schema
from caffe2.python.layers.layers import ModelLayer

            

Reported by Pylint.

Missing class docstring
Error

Line: 13 Column: 1

              import numpy as np


class ConstantWeight(ModelLayer):
    def __init__(
        self,
        model,
        input_record,
        weights=None,

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 22 Column: 9

                      name='constant_weight',
        **kwargs
    ):
        super(ConstantWeight,
              self).__init__(model, name, input_record, **kwargs)
        self.output_schema = schema.Scalar(
            np.float32, self.get_next_blob_reference('constant_weight')
        )
        self.data = self.input_record.field_blobs()

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 33
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                          weights if weights is not None else
            [1. / self.num for _ in range(self.num)]
        )
        assert len(weights) == self.num
        self.weights = [
            self.model.add_global_constant(
                '%s_weight_%d' % (self.name, i), float(weights[i])
            ) for i in range(self.num)
        ]

            

Reported by Bandit.

.circleci/cimodel/lib/miniutils.py
5 issues
Missing module docstring
Error

Line: 1 Column: 1

              def quote(s):
    return sandwich('"', s)


def sandwich(bread, jam):
    return bread + jam + bread


def override(word, substitutions):

            

Reported by Pylint.

Argument name "s" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              def quote(s):
    return sandwich('"', s)


def sandwich(bread, jam):
    return bread + jam + bread


def override(word, substitutions):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 1 Column: 1

              def quote(s):
    return sandwich('"', s)


def sandwich(bread, jam):
    return bread + jam + bread


def override(word, substitutions):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 5 Column: 1

                  return sandwich('"', s)


def sandwich(bread, jam):
    return bread + jam + bread


def override(word, substitutions):
    return substitutions.get(word, word)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 9 Column: 1

                  return bread + jam + bread


def override(word, substitutions):
    return substitutions.get(word, word)

            

Reported by Pylint.

caffe2/contrib/prof/cuda_profile_ops_test.py
5 issues
Probable insecure usage of temp file/directory.
Security

Line: 17
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b108_hardcoded_tmp_directory.html

                  @unittest.skipIf(workspace.NumCudaDevices() < 1, "Need at least 1 GPU")
    def test_run(self):
        net = core.Net("net")
        net.CudaProfileInitialize([], [], output="/tmp/cuda_profile_test")
        net.CudaProfileStart([], [])
        with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 0)):
            net.ConstantFill([], ["out"], shape=[1, 3, 244, 244])
        net.CudaProfileStop([], [])


            

Reported by Bandit.

Missing module docstring
Error

Line: 1 Column: 1

              




import unittest
from caffe2.proto import caffe2_pb2
from caffe2.python import core, dyndep, workspace


            

Reported by Pylint.

Missing class docstring
Error

Line: 13 Column: 1

              dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/prof:cuda_profile_ops")


class CudaProfileOpsTest(unittest.TestCase):
    @unittest.skipIf(workspace.NumCudaDevices() < 1, "Need at least 1 GPU")
    def test_run(self):
        net = core.Net("net")
        net.CudaProfileInitialize([], [], output="/tmp/cuda_profile_test")
        net.CudaProfileStart([], [])

            

Reported by Pylint.

Method could be a function
Error

Line: 15 Column: 5

              
class CudaProfileOpsTest(unittest.TestCase):
    @unittest.skipIf(workspace.NumCudaDevices() < 1, "Need at least 1 GPU")
    def test_run(self):
        net = core.Net("net")
        net.CudaProfileInitialize([], [], output="/tmp/cuda_profile_test")
        net.CudaProfileStart([], [])
        with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 0)):
            net.ConstantFill([], ["out"], shape=[1, 3, 244, 244])

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 15 Column: 5

              
class CudaProfileOpsTest(unittest.TestCase):
    @unittest.skipIf(workspace.NumCudaDevices() < 1, "Need at least 1 GPU")
    def test_run(self):
        net = core.Net("net")
        net.CudaProfileInitialize([], [], output="/tmp/cuda_profile_test")
        net.CudaProfileStart([], [])
        with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 0)):
            net.ConstantFill([], ["out"], shape=[1, 3, 244, 244])

            

Reported by Pylint.