Search is not available for this dataset
repo stringlengths 2 152 ⌀ | file stringlengths 15 239 | code stringlengths 0 58.4M | file_length int64 0 58.4M | avg_line_length float64 0 1.81M | max_line_length int64 0 12.7M | extension_type stringclasses 364
values |
|---|---|---|---|---|---|---|
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/algos/test_vpg.py | """This script creates a test that fails when VPG performance is too low."""
import gym
import pytest
import torch
from garage.envs import GarageEnv
from garage.experiment import deterministic
from garage.experiment import LocalRunner
from garage.torch.algos import VPG
from garage.torch.policies import GaussianMLPPoli... | 3,494 | 33.264706 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/distributions/test_tanh_normal_dist.py | """Tests for the tanh transformed normal distribution."""
import torch
from garage.torch.distributions import TanhNormal
class TestBenchmarkTanhNormalDistribution:
"""Tests for the tanh normal distribution."""
def test_new_tanh_normal(self):
"""Tests the tanh_normal constructor."""
mean = to... | 2,539 | 33.324324 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/modules/test_gaussian_mlp_module.py | import pytest
import torch
from torch import nn
from garage.torch.modules.gaussian_mlp_module \
import GaussianMLPIndependentStdModule, GaussianMLPModule, \
GaussianMLPTwoHeadedModule
plain_settings = [
(1, 1, (1, )),
(1, 2, (2, )),
(1, 3, (3, )),
(1, 1, (1, 2)),
(1, 2, (2, 1)),
(1, 3,... | 11,989 | 38.966667 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/modules/test_mlp_module.py | """Test MLPModule."""
import pickle
import numpy as np
import pytest
import torch
import torch.nn as nn
from garage.torch.modules import MLPModule
class TestMLPModel:
"""Test MLPModule."""
# yapf: disable
@pytest.mark.parametrize('input_dim, output_dim, hidden_sizes', [
(5, 1, (1, )),
(... | 5,051 | 34.577465 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/modules/test_multi_headed_mlp_module.py | """Test Multi-headed MLPModule."""
import pytest
import torch
from torch import nn
from garage.torch.modules import MultiHeadedMLPModule
plain_settings = [
(1, (2, ), (2, ), (0, 1, 2), 3),
(5, (3, ), (4, 5), (0, 1, 2, 3, 5, 5), 6),
(1, (2, 3), (2, ), (0, 3), 2),
(2, (3, 6, 7), (3, ), (6, ), 3),
(5... | 6,812 | 39.796407 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/optimizers/test_differentiable_sgd.py | """Tests for DifferentialSGD optimizer."""
import torch
from garage.torch import update_module_params
from garage.torch.optimizers import DifferentiableSGD
def test_differentiable_sgd():
"""Test second order derivative after taking optimization step."""
policy = torch.nn.Linear(10, 10, bias=False)
lr = 0... | 980 | 27.852941 | 70 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/optimizers/test_torch_conjugate_gradient_optimizer.py | """Tests for garage.torch.optimizers.conjugateGradientOptimizer."""
import pickle
import numpy as np
import pytest
import torch
from garage.torch.optimizers.conjugate_gradient_optimizer import (
_build_hessian_vector_product, _conjugate_gradient,
ConjugateGradientOptimizer)
# pylint: disable=not-callable #h... | 8,346 | 33.491736 | 107 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/policies/test_context_conditioned_policy.py | """This is a script to test the ContextConditionedPolicy module."""
import akro
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F # NOQA
from garage import TimeStep
from garage.envs import EnvSpec
from garage.envs import GarageEnv
from garage.torch.embeddings import MLPEncode... | 5,359 | 39.606061 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/policies/test_deterministic_mlp_policy.py | import pickle
import numpy as np
import pytest
import torch
from torch import nn
from garage.envs import GarageEnv
from garage.torch.policies import DeterministicMLPPolicy
# yapf: Disable
from tests.fixtures.envs.dummy import DummyBoxEnv, DummyDictEnv # noqa: I202
# yapf: Enable
class TestDeterministicMLPPolicie... | 4,626 | 39.234783 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/policies/test_gaussian_mlp_policy.py | """Test Gaussian MLP Policy."""
import pickle
import numpy as np
import pytest
import torch
from torch import nn
from garage.envs import GarageEnv
from garage.torch.policies import GaussianMLPPolicy
# yapf: Disable
from tests.fixtures.envs.dummy import DummyBoxEnv, DummyDictEnv # noqa: I202
# yapf: Enable
class ... | 8,639 | 37.744395 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/policies/test_tanh_gaussian_mlp_policy.py | """Tests for tanh gaussian mlp policy."""
import pickle
import numpy as np
import pytest
import torch
from torch import nn
from garage.envs import GarageEnv
from garage.torch.policies import TanhGaussianMLPPolicy
# yapf: Disable
from tests.fixtures.envs.dummy import DummyBoxEnv, DummyDictEnv # noqa: I202
# yapf: E... | 8,472 | 40.945545 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/garage/torch/q_functions/test_continuous_mlp_q_function.py | import pickle
import numpy as np
import pytest
import torch
from torch import nn
from garage.envs import GarageEnv
from garage.torch.q_functions import ContinuousMLPQFunction
from tests.fixtures.envs.dummy import DummyBoxEnv
class TestContinuousNNQFunction:
# yapf: disable
@pytest.mark.parametrize('hidden_s... | 3,242 | 36.275862 | 69 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/integration_tests/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garaged/tests/integration_tests/test_examples.py | """Integration tests to make sure scripts in examples work."""
import os
import pathlib
import subprocess
import pytest
EXAMPLES_ROOT_DIR = pathlib.Path('examples/')
NON_ALGO_EXAMPLES = [
EXAMPLES_ROOT_DIR / 'torch/resume_training.py',
EXAMPLES_ROOT_DIR / 'tf/resume_training.py',
EXAMPLES_ROOT_DIR / 'sim_... | 14,662 | 32.249433 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garaged/tests/integration_tests/test_sigint.py | from enum import IntEnum
import itertools
from multiprocessing.connection import Listener
import os
import signal
import subprocess
import psutil
import pytest
scripts = [
'tests/fixtures/algos/nop_pendulum_instrumented.py',
'tests/fixtures/tf/trpo_pendulum_instrumented.py',
]
class ExpLifecycle(IntEnum):
... | 3,273 | 32.070707 | 76 | py |
CSD-locomotion | CSD-locomotion-master/garagei/__init__.py | from garagei._functions import log_performance_ex
__all__ = [
'log_performance_ex',
]
| 91 | 14.333333 | 49 | py |
CSD-locomotion | CSD-locomotion-master/garagei/_functions.py | import numpy as np
import global_context
import dowel_wrapper
from garage.misc.tensor_utils import discount_cumsum
from dowel import Histogram
def log_performance_ex(itr, batch, discount, additional_records=None, additional_prefix=''):
"""Evaluate the performance of an algorithm on a batch of trajectories.
A... | 2,830 | 35.294872 | 92 | py |
CSD-locomotion | CSD-locomotion-master/garagei/envs/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/envs/akro_wrapper.py | import akro
from garage.envs import EnvSpec
class AkroWrapperTrait:
@property
def spec(self):
return EnvSpec(action_space=akro.from_gym(self.action_space),
observation_space=akro.from_gym(self.observation_space))
| 255 | 22.272727 | 79 | py |
CSD-locomotion | CSD-locomotion-master/garagei/envs/consistent_normalized_env.py | """An environment wrapper that normalizes action, observation and reward."""
import akro
import gym
import gym.spaces
import gym.spaces.utils
import numpy as np
from garage.envs import EnvSpec
from garagei.envs.akro_wrapper import AkroWrapperTrait
class ConsistentNormalizedEnv(AkroWrapperTrait, gym.Wrapper):
def... | 2,932 | 33.104651 | 92 | py |
CSD-locomotion | CSD-locomotion-master/garagei/envs/normalized_env_ex.py | """An environment wrapper that normalizes action, observation and reward."""
import akro
import gym
import gym.spaces
import gym.spaces.utils
import numpy as np
from garage.envs import EnvSpec
from garagei.envs.akro_wrapper import AkroWrapperTrait
class NormalizedEnvEx(AkroWrapperTrait, gym.Wrapper):
"""An envir... | 7,692 | 36.34466 | 116 | py |
CSD-locomotion | CSD-locomotion-master/garagei/experiment/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/experiment/option_local_runner.py | import atexit
import copy
import os
import signal
import time
import torch
from dowel import logger, tabular, TextOutput, CsvOutput, StdOutput
import numpy as np
import psutil
from garage.experiment import LocalRunner
from garage.experiment.deterministic import get_seed, set_seed
from garage.experiment.local_runner i... | 19,606 | 39.678423 | 144 | py |
CSD-locomotion | CSD-locomotion-master/garagei/np/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/np/optimizers/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/np/optimizers/dict_minibatch_dataset.py | import numpy as np
class DictBatchDataset:
"""Use when the input is the dict type."""
def __init__(self, inputs, batch_size):
self._inputs = inputs
self._batch_size = batch_size
self._size = list(self._inputs.values())[0].shape[0]
if batch_size is not None:
self._id... | 1,155 | 29.421053 | 64 | py |
CSD-locomotion | CSD-locomotion-master/garagei/sampler/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/sampler/option_local_sampler.py | """Sampler that runs workers in the main process."""
import copy
from collections import defaultdict
from garage import TrajectoryBatch
from garage.sampler import LocalSampler
class OptionLocalSampler(LocalSampler):
def _update_workers(self, agent_update, env_update, worker_update):
"""Apply updates to t... | 2,352 | 41.781818 | 84 | py |
CSD-locomotion | CSD-locomotion-master/garagei/sampler/option_multiprocessing_sampler.py | """A multiprocessing sampler which avoids waiting as much as possible."""
import itertools
import torch.multiprocessing as mp
import multiprocessing.dummy as mpd
from collections import defaultdict
import click
import cloudpickle
import matplotlib
import setproctitle
from garage import TrajectoryBatch
from garage.samp... | 8,054 | 38.876238 | 106 | py |
CSD-locomotion | CSD-locomotion-master/garagei/sampler/option_worker.py | import functools
import numpy as np
from garage.experiment import deterministic
from garage.sampler import DefaultWorker
from iod.utils import get_np_concat_obs
class OptionWorker(DefaultWorker):
def __init__(
self,
*, # Require passing by keyword, since everything's an int.
... | 5,991 | 35.536585 | 129 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/torch/utils.py | from math import inf
import math
import numpy as np
import torch
from torch.distributions.transforms import AffineTransform
from torch.nn.init import _calculate_fan_in_and_fan_out, _no_grad_normal_
from garagei.torch.distributions.transformed_distribution_ex import TransformedDistributionEx
from garagei.torch.distribu... | 3,495 | 37.844444 | 128 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/distributions/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/torch/distributions/transformed_distribution_ex.py | import torch
from torch.distributions import Beta, Normal, TransformedDistribution
from torch.distributions.transforms import AffineTransform
class TransformedDistributionEx(TransformedDistribution):
def entropy(self):
"""
Returns entropy of distribution, batched over batch_shape.
Returns:... | 830 | 32.24 | 69 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/distributions/transforms_ex.py | from torch.distributions.transforms import AffineTransform, _InverseTransform
class NoWeakrefTrait(object):
def _inv_no_weakref(self):
"""
Returns the inverse :class:`Transform` of this transform.
This should satisfy ``t.inv.inv is t``.
"""
inv = None
if self._inv is... | 992 | 31.032258 | 77 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/categorical_mlp_module_ex.py | import abc
import torch
from torch import nn
from torch.distributions import Categorical, OneHotCategorical
from torch.distributions.independent import Independent
from garage.torch.distributions import TanhNormal
from garage.torch.modules.mlp_module import MLPModule
from garage.torch.modules.multi_headed_mlp_module ... | 7,450 | 40.859551 | 93 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/gaussian_mlp_module_ex.py | import torch
from garage.torch.distributions import TanhNormal
from garage.torch.modules import MultiHeadedMLPModule
from garage.torch.modules.gaussian_mlp_module import GaussianMLPModule, GaussianMLPIndependentStdModule, \
GaussianMLPTwoHeadedModule, GaussianMLPBaseModule
from garage.torch.modules.mlp_module impor... | 9,107 | 43.213592 | 142 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/multiplier.py | import numpy as np
import torch
from torch import nn
class Multiplier(nn.Module):
def __init__(self,
multiplicand,
requires_grad=False,
):
super().__init__()
self._multiplicand = nn.Parameter(multiplicand, requires_grad=requires_grad)
def fo... | 375 | 19.888889 | 84 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/normalizer.py | import numpy as np
import torch
from torch import nn
class Normalizer(nn.Module):
def __init__(
self,
shape,
alpha=0.001,
do_normalize=True,
):
super().__init__()
self.shape = shape
self.alpha = alpha
self.do_normalize = do_norma... | 1,859 | 28.52381 | 124 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/parallel_module.py | import numpy as np
import torch
from torch import nn
class ParallelModule(nn.Module):
def __init__(self,
input_dims,
parallel_modules,
post_parallel_module,
**kwargs):
super().__init__()
self._input_dims = input_dims
self.... | 2,017 | 32.633333 | 93 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/parameter_module.py | import torch
from torch import nn
class ParameterModule(nn.Module):
def __init__(
self,
init_value
):
super().__init__()
self.param = torch.nn.Parameter(init_value)
| 216 | 15.692308 | 51 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/reshape.py | import numpy as np
import torch
from torch import nn
class ReshapeModule(nn.Module):
def __init__(self, shape):
super().__init__()
self.shape = shape
def forward(self, x):
assert np.prod(x.shape[1:]) == np.prod(self.shape)
return x.reshape(-1, *self.shape)
class ViewModule(nn... | 542 | 20.72 | 58 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/seq_last_selector_module.py | import copy
import numpy as np
import torch
from torch import nn
import dowel_wrapper
from iod.utils import zip_dict
class SeqLastSelectorModule(nn.Module):
def __init__(self,
*,
inner_module,
input_dim=None,
use_delta=False,
om... | 3,113 | 32.12766 | 101 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/modules/spectral_norm.py | """
Spectral Normalization from https://arxiv.org/abs/1802.05957
"""
import torch
from torch.nn.functional import normalize
from typing import Any, Optional, TypeVar
from torch.nn import Module
class SpectralNorm:
# Invariant before and after each forward call:
# u = normalize(W @ v)
# NB: At initializa... | 13,869 | 44.625 | 143 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/optimizers/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/torch/optimizers/optimizer_group_wrapper.py | """A PyTorch optimizer wrapper that compute loss and optimize module."""
from garagei.np.optimizers.dict_minibatch_dataset import DictBatchDataset
class OptimizerGroupWrapper:
"""A wrapper class to handle torch.optim.optimizer.
"""
def __init__(self,
optimizers,
max_opti... | 1,859 | 31.631579 | 77 | py |
CSD-locomotion | CSD-locomotion-master/garagei/torch/policies/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/garagei/torch/policies/policy_ex.py | import akro
import numpy as np
import torch
from garage.torch import global_device
from garage.torch.distributions import TanhNormal
from garage.torch.policies.stochastic_policy import StochasticPolicy
from garagei.torch.modules.multiplier import Multiplier
class PolicyEx(StochasticPolicy):
def __init__(self,
... | 7,491 | 39.717391 | 103 | py |
CSD-locomotion | CSD-locomotion-master/iod/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/iod/iod.py | import copy
import gc
import numpy as np
import torch
from matplotlib import cm
import global_context
import dowel_wrapper
from dowel import Histogram
from garage import TrajectoryBatch
from garage.misc import tensor_utils
from garage.np.algos.rl_algorithm import RLAlgorithm
from garagei import log_performance_ex
fro... | 24,795 | 39.51634 | 169 | py |
CSD-locomotion | CSD-locomotion-master/iod/lsd.py | import numpy as np
import torch
import global_context
from garage import TrajectoryBatch
from garagei import log_performance_ex
from iod import sac_utils
from iod.iod import IOD
import copy
from iod.utils import get_torch_concat_obs, to_np_object_arr, FigManager, get_option_colors, record_video, \
draw_2d_gaussia... | 18,933 | 35.552124 | 164 | py |
CSD-locomotion | CSD-locomotion-master/iod/sac_utils.py | import torch
from torch.nn import functional as F
def _clip_actions(algo, actions):
epsilon = 1e-6
lower = torch.from_numpy(algo._env_spec.action_space.low).to(algo.device) + epsilon
upper = torch.from_numpy(algo._env_spec.action_space.high).to(algo.device) - epsilon
clip_up = (actions > upper).float... | 4,046 | 33.008403 | 137 | py |
CSD-locomotion | CSD-locomotion-master/iod/utils.py | import copy
import pathlib
import time
import dowel_wrapper
import akro
import numpy as np
import torch
import platform
from PIL import Image
if 'macOS' in platform.platform():
import os
os.environ["IMAGEIO_FFMPEG_EXE"] = '/opt/homebrew/bin/ffmpeg'
from moviepy import editor as mpy
from garage.envs import EnvS... | 19,058 | 35.302857 | 139 | py |
CSD-locomotion | CSD-locomotion-master/tests/__init__.py | 0 | 0 | 0 | py | |
CSD-locomotion | CSD-locomotion-master/tests/main.py | #!/usr/bin/env python3
import dowel_wrapper
assert dowel_wrapper is not None
import dowel
import argparse
import datetime
import functools
import os
import torch.multiprocessing as mp
import better_exceptions
import numpy as np
better_exceptions.hook()
import torch
from garage import wrap_experiment
from garage.... | 21,948 | 38.124777 | 167 | py |
CSD-locomotion | CSD-locomotion-master/tests/utils.py | import datetime
import os
import socket
from garage.experiment.experiment import get_metadata
import global_context
def get_run_env_dict():
d = {}
d['timestamp'] = datetime.datetime.now().timestamp()
d['hostname'] = socket.gethostname()
if 'SLURM_JOB_ID' in os.environ:
d['slurm_job_id'] = int... | 862 | 29.821429 | 93 | py |
null | IT-Defense-main/README.md | # IT-Defense
Our code for paper '[The art of defense: letting networks fool the attacker](https://arxiv.org/abs/2104.02963)'
## Introduction
Robust environment perception is critical for autonomous cars, and adversarial defenses are the most effective and widely studied ways to improve the robustness of environment p... | 2,247 | 40.62963 | 483 | md |
null | IT-Defense-main/it_defense.py | import torch.nn as nn
class Infer(nn.Module):
def __init__(self, model):
super(Infer, self).__init__()
self.model = model
for p in self.parameters():
p.requires_grad = False
def forward(self, x):
x.data = x[:, :, torch.randperm(x.size()[2])].data
x = self.mo... | 365 | 23.4 | 58 | py |
smartbugs | smartbugs-master/README.md | # SmartBugs: A Framework for Analysing Ethereum Smart Contracts

<a href="https://github.com/smartbugs/smartbugs/releases"><img alt="Smartbugs release" src="https://img.shields.io/github/release/smartbugs/smartbugs.svg"><... | 11,277 | 50.733945 | 454 | md |
smartbugs | smartbugs-master/site_cfg.yaml | #files: []
## $HOME or ${HOME} is replaced by the home dir of the current user
#
#runtime: false
#
#main: false
#
#tools: []
#
#runid: ${YEAR}${MONTH}${DAY}_${HOUR}${MIN}
## vars: YEAR, MONTH, DAY, HOUR, MIN, SEC, ZONE,
## HOME, PID, SBVERSION, SBHOME
#
#overwrite: false
#
#processes: 1
#
#timeout: 0 # [s] 0/null... | 832 | 21.513514 | 70 | yaml |
smartbugs | smartbugs-master/.github/github_results.sh | #!/bin/bash
# Run .github/github_results.sh from SmartBugs home directory
# Generates .github/results-ubuntu.csv, needed for the workflow ubuntu.yml
# as a reference for comparing the results of the workflow with
#rm -rf results/*/github-sol
./smartbugs -t all -f 'samples/SimpleDAO.sol' --runid github-sol --sarif --m... | 863 | 47 | 117 | sh |
smartbugs | smartbugs-master/.github/ISSUE_TEMPLATE/bug_report.md | ---
name: Bug report
about: Template for bug reports
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A description of what the bug is: what did you do, what did you expect, what did actually happen.
If applicable, add screenshots to help explain your problem.
**Platform**
Please provide information on t... | 655 | 26.333333 | 143 | md |
smartbugs | smartbugs-master/.github/ISSUE_TEMPLATE/feature_request.md | ---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and con... | 595 | 27.380952 | 92 | md |
smartbugs | smartbugs-master/.github/old/github_results.sh | #!/bin/bash
# Run .github/github_results.sh from SmartBugs home directory
# Generates .github/results-ubuntu.csv, needed for the workflow ubuntu.yml
# as a reference for comparing the results of the workflow with
rm -rf results/github
./smartbugs -t all -f 'samples/SimpleDAO.*' --runid github --json --main --timeout ... | 434 | 42.5 | 109 | sh |
smartbugs | smartbugs-master/.github/old/ubuntu.yml | name: SmartBugs tests # name displayed in badge
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
run-sb-ubuntu:
runs-on: ubuntu-20.04
#runs-on: ubuntu-latest
strategy:
matrix:
tool: ["all"]
contract: ["'samples/SimpleDAO.*'"]
python-vers... | 7,440 | 42.770588 | 120 | yml |
smartbugs | smartbugs-master/.github/workflows/ubuntu.yml | name: SmartBugs tests # name displayed in badge
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
run-sb-ubuntu-sol:
runs-on: ubuntu-20.04
strategy:
matrix:
tool: ["all"]
contract: ["'samples/SimpleDAO.sol'"]
python-version: ["3.6.9"]
st... | 3,081 | 38.012658 | 124 | yml |
smartbugs | smartbugs-master/install/setup-venv.sh | #!/bin/bash
# tested for python >= 3.6.9
# python < 3.10 will give an error when using the ':'-feature in input patterns
python3 -m venv venv
source venv/bin/activate
# avoid spurious errors/warnings; the next two lines could be omitted
pip install --upgrade pip
pip install wheel
# install the packages needed by sma... | 399 | 27.571429 | 79 | sh |
smartbugs | smartbugs-master/sb/__init__.py | 0 | 0 | 0 | py | |
smartbugs | smartbugs-master/sb/__main__.py | #!/usr/bin/env python3
"""SmartBugs: A framework to analyze smart contracts
http://github.com/smartbugs/smartbugs
"""
import sb.cli
if __name__ == "__main__":
sb.cli.main()
| 183 | 15.727273 | 52 | py |
smartbugs | smartbugs-master/sb/analysis.py | import multiprocessing, random, time, datetime, os, random
import sb.logging, sb.colors, sb.docker, sb.cfg, sb.io, sb.parsing, sb.sarif, sb.errors
def task_log_dict(task, start_time, duration, exit_code, log, output, docker_args):
return {
"filename": task.relfn,
"runid": task.settings.runid,
... | 6,961 | 37.043716 | 130 | py |
smartbugs | smartbugs-master/sb/cfg.py | import os, time, cpuinfo, platform
VERSION = "2.0.7"
HOME = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SITE_CFG = os.path.join(HOME,"site_cfg.yaml")
TASK_LOG = "smartbugs.json"
TOOLS_HOME = os.path.join(HOME,"tools")
TOOL_CONFIG = "config.yaml"
TOOL_FINDINGS = "findings.yaml"
TOOL_PARSER = "pa... | 698 | 25.884615 | 74 | py |
smartbugs | smartbugs-master/sb/cli.py | import argparse, sys, os
import sb.cfg, sb.colors, sb.smartbugs, sb.logging, sb.settings, sb.errors
def cli_args(defaults):
def fmt_default(defval):
formatted = (
"yes" if isinstance(defval, bool) and defval else
"no" if isinstance(defval, bool) and not defval else
str... | 5,222 | 33.589404 | 135 | py |
smartbugs | smartbugs-master/sb/colors.py | import colorama, re, sys
from colorama import Fore, Style
ANSIcolor = re.compile('\x1b\[[^m]*m')
def strip(s):
return ANSIcolor.sub('',str(s))
if sys.platform == "win32":
def color(col, s):
return s
else:
def color(col, s):
return f"{col}{s}{Style.RESET_ALL}"
def file(s):
return color... | 525 | 16.533333 | 43 | py |
smartbugs | smartbugs-master/sb/docker.py | import docker, os, shutil, tempfile, requests
import sb.io, sb.errors
_client = None
def client():
global _client
if not _client:
try:
_client = docker.from_env()
_client.info()
except Exception:
raise sb.errors.SmartBugsError("Docker: Cannot connect t... | 3,668 | 27.44186 | 109 | py |
smartbugs | smartbugs-master/sb/errors.py | class InternalError(Exception):
pass
class SmartBugsError(Exception):
pass
| 84 | 13.166667 | 32 | py |
smartbugs | smartbugs-master/sb/io.py | import yaml, json
import sb.errors
def read_yaml(fn):
try:
with open(fn, 'r', encoding='utf-8') as f:
# for an empty file, return empty dict, not NoneType
return yaml.safe_load(f) or {}
except Exception as e:
raise sb.errors.SmartBugsError(e)
def read_json(fn):
try:... | 1,560 | 25.457627 | 64 | py |
smartbugs | smartbugs-master/sb/logging.py | import multiprocessing, threading, os, sys, time, re
import sb.colors
def logger_process(logfn, overwrite, queue, prolog):
log_parent_folder = os.path.dirname(logfn)
if log_parent_folder:
os.makedirs(log_parent_folder, exist_ok=True)
mode = "w" if overwrite else "a"
with open(logfn, mode) as lo... | 1,041 | 23.809524 | 88 | py |
smartbugs | smartbugs-master/sb/parse_utils.py | '''Utilities for the output parsers'''
import re
DOCKER_CODES = {
125: "DOCKER_INVOCATION_PROBLEM",
126: "DOCKER_CMD_NOT_EXECUTABLE",
127: "DOCKER_CMD_NOT_FOUND",
137: "DOCKER_KILL_OOM", # container received KILL signal, manually or because out of memory
139: "DOCKER_SEGV", # segmentation violatio... | 2,528 | 29.841463 | 106 | py |
smartbugs | smartbugs-master/sb/parsing.py | import os, importlib.util
import sb.cfg, sb.errors
tool_parsers = {}
def get_parser(tool):
tid,tmode = tool["id"],tool["mode"]
key = (tid,tmode)
if key not in tool_parsers:
try:
modulename = f"tools.{tid}.{tmode}"
fn = os.path.join(sb.cfg.TOOLS_HOME, tid, tool["parser"])
... | 2,126 | 36.982143 | 109 | py |
smartbugs | smartbugs-master/sb/reparse.py | import os, argparse, multiprocessing, sys
import sb.cfg, sb.io, sb.parsing, sb.sarif, sb.errors
def reparser(taskqueue, sarif, verbose):
while True:
d = taskqueue.get()
if d is None:
break
fn_sbj = os.path.join(d, sb.cfg.TASK_LOG)
fn_log = os.path.join(d, sb.cfg.TOOL_... | 3,050 | 29.207921 | 116 | py |
smartbugs | smartbugs-master/sb/results2csv.py | import argparse, csv, os, sys
import sb.cfg, sb.io, sb.utils
FIELDS = (
"filename", "basename", "toolid", "toolmode", "parser_version", "runid",
"start", "duration", "exit_code", "findings", "infos", "errors", "fails")
def main():
argparser = argparse.ArgumentParser(
prog="results2csv",
d... | 3,783 | 31.904348 | 111 | py |
smartbugs | smartbugs-master/sb/sarif.py | import sb.tools, sb.utils
def sarify(tool, findings):
return {
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0",
"runs": [ run_info(tool, findings) ]
}
def run_info(tool, findings):
fnames = { finding["name"] for finding in findings }
return {
... | 5,054 | 27.885714 | 116 | py |
smartbugs | smartbugs-master/sb/settings.py | import os, string, time
import sb.io, sb.logging, sb.cfg, sb.errors
HOME = os.path.expanduser("~") # cross-plattform safe
NOW = time.gmtime() # only use in main process, value may be different in sub-processes
PID = os.getpid() # only use in main process, value may be different in sub-processes
class Settings:
... | 7,323 | 39.021858 | 127 | py |
smartbugs | smartbugs-master/sb/smartbugs.py | import glob, os, operator
import sb.tools, sb.solidity, sb.tasks, sb.docker, sb.analysis, sb.colors, sb.logging, sb.cfg, sb.io, sb.settings, sb.errors
def collect_files(patterns):
files = []
for root,spec in patterns:
if spec.endswith(".sbd"):
contracts = []
for sbdfile in glo... | 5,736 | 37.246667 | 124 | py |
smartbugs | smartbugs-master/sb/solidity.py | import os,re
from pathlib import Path
import solcx
# load binaries for Linux in Docker images, not for host platform
solcx.set_target_os("linux")
VOID_START = re.compile("//|/\*|\"|'")
QUOTE_END = re.compile("(?<!\\\\)'")
DQUOTE_END = re.compile('(?<!\\\\)"')
def remove_comments_strings(prg):
todo = "\n".join(... | 2,728 | 26.29 | 89 | py |
smartbugs | smartbugs-master/sb/tasks.py | class Task:
def __init__(self, absfn, relfn, rdir, solc_version, solc_path, tool, settings):
self.absfn = absfn # absolute normalized path
self.relfn = relfn # path within project
self.rdir = rdir # directory for results
self.solc_version = solc_version
self.solc_path = sol... | 512 | 35.642857 | 84 | py |
smartbugs | smartbugs-master/sb/tools.py | import os, string
import sb.io, sb.cfg, sb.errors
FIELDS = ("id","mode","image","name","origin","version","info","parser",
"output","bin","solc","cpu_quota","mem_limit","command","entrypoint")
class Tool():
def __init__(self, cfg):
for k in FIELDS:
v = cfg.get(k)
if v is not... | 5,861 | 35.867925 | 132 | py |
smartbugs | smartbugs-master/sb/utils.py | def str2label(s):
"""Convert string to label.
- leading non-letters are removed
- trailing characters that are neither letters nor digits ("other chars") are removed
- sequences of other chars within the string are replaced by a single underscore
"""
l = ""
separator = False
has_started... | 600 | 27.619048 | 89 | py |
smartbugs | smartbugs-master/solcx/__init__.py | from solcx.install import (
compile_solc,
get_compilable_solc_versions,
get_executable,
get_installable_solc_versions,
get_installed_solc_versions,
get_solcx_install_folder,
import_installed_solc,
install_solc,
install_solc_pragma,
set_target_os,
set_solc_version,
set_sol... | 464 | 20.136364 | 34 | py |
smartbugs | smartbugs-master/solcx/exceptions.py | from typing import Dict, List
class SolcError(Exception):
message = "An error occurred during execution"
def __init__(
self,
message: str = None,
command: List = None,
return_code: int = None,
stdin_data: str = None,
stdout_data: str = None,
stderr_data... | 1,502 | 19.875 | 70 | py |
smartbugs | smartbugs-master/solcx/install.py | """
Install solc
"""
import argparse
import logging
import os
import re
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import warnings
import zipfile
from base64 import b64encode
from io import BytesIO
from pathlib import Path
from typing import Dict, List, Optional, Union
import... | 23,707 | 33.210678 | 116 | py |
smartbugs | smartbugs-master/solcx/main.py | import json
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from semantic_version import Version
from solcx import wrapper
from solcx.exceptions import ContractsNotFound, SolcError
from solcx.install import get_executable
def get_solc_version(with_commit_hash: bool = False) -> Version:
... | 15,849 | 34.778781 | 100 | py |
smartbugs | smartbugs-master/solcx/wrapper.py | import re
import subprocess
from pathlib import Path
from typing import Any, Dict, List, Tuple, Union
from semantic_version import Version
from solcx import install
from solcx.exceptions import SolcError, UnknownOption, UnknownValue
# (major.minor.patch)(nightly)(commit)
VERSION_REGEX = r"(\d+\.\d+\.\d+)(?:-nightly.... | 5,704 | 33.161677 | 100 | py |
smartbugs | smartbugs-master/solcx/utils/__init__.py | 0 | 0 | 0 | py | |
smartbugs | smartbugs-master/solcx/utils/lock.py | import os
import sys
import tempfile
import threading
import getpass
from pathlib import Path
from typing import Any, Dict, Union
if sys.platform == "win32":
import msvcrt
OPEN_MODE = os.O_RDWR | os.O_CREAT | os.O_TRUNC
else:
import fcntl
NON_BLOCKING = fcntl.LOCK_EX | fcntl.LOCK_NB
BLOCKING = fc... | 2,554 | 26.771739 | 108 | py |
smartbugs | smartbugs-master/templates/scripts/example.py | # This is a sample file showing how to call SmartBugs
# from a Python script.
import sb.smartbugs, sb.settings, sb.exceptions
if __name__ == "__main__":
settings = sb.settings.Settings()
settings.update({
"tools": ["conkas"],
"files": ["samples/simple_dao.*"],
#"quiet": True # suppress ... | 480 | 29.0625 | 53 | py |
smartbugs | smartbugs-master/templates/tools/template/config.yaml | name: ToolName # optional
version: 0.3.14 # version number, commit id, ... (optional)
origin: where to find more on the tool, e.g. an URL # optional
info: Succinct description of your tool. # optional
image: smartbugs/toolname:0.3.14 # id of Docker image (mandatory)
bin: scripts # folder with programs that will be acce... | 831 | 47.941176 | 83 | yaml |
smartbugs | smartbugs-master/templates/tools/template/parser.py | import sb.parse_utils # for sb.parse_utils.init(...)
import io, tarfile # if the output parameter is used
import ... # any further imports
VERSION: str = ...
"""identify the version of the parser, e.g. '2022/08/15'"""
FINDINGS: set[str] = ...
"""set of strings: all possible findings, of which 'findings... | 3,454 | 38.712644 | 98 | py |
smartbugs | smartbugs-master/templates/tools/template/scripts/printContractNames.py | import sys, json
from subprocess import PIPE, Popen
filename = sys.argv[1]
cmd = ["solc", "--standard-json", "--allow-paths", ".,/"]
settings = {
"optimizer": {"enabled": False},
"outputSelection": {
"*": {
"*": [ "evm.deployedBytecode" ],
}
},
}
input_json = json.dumps(
{
... | 915 | 25.941176 | 69 | py |