Best Syzkaller code snippet using build.buildKernel
kernel_test.go
Source:kernel_test.go
1package kernel_test2import (3 "context"4 "fmt"5 "sync"6 "testing"7 "time"8 "github.com/justtrackio/gosoline/pkg/cfg"9 cfgMocks "github.com/justtrackio/gosoline/pkg/cfg/mocks"10 "github.com/justtrackio/gosoline/pkg/coffin"11 "github.com/justtrackio/gosoline/pkg/conc"12 "github.com/justtrackio/gosoline/pkg/kernel"13 kernelMocks "github.com/justtrackio/gosoline/pkg/kernel/mocks"14 "github.com/justtrackio/gosoline/pkg/log"15 logMocks "github.com/justtrackio/gosoline/pkg/log/mocks"16 "github.com/pkg/errors"17 "github.com/stretchr/testify/assert"18 "github.com/stretchr/testify/mock"19 "golang.org/x/sys/unix"20)21type FunctionModule func(ctx context.Context) error22func (m FunctionModule) Run(ctx context.Context) error {23 return m(ctx)24}25func TestKernelHangingModule(t *testing.T) {26 timeout(t, time.Second*3, func(t *testing.T) {27 config, _, _ := createMocks()28 logger := logMocks.NewLoggerMockedAll()29 options := []kernel.Option{30 mockExitHandler(t, kernel.ExitCodeErr),31 }32 options = append(options, kernel.WithModuleFactory("normal module", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {33 return FunctionModule(func(ctx context.Context) error {34 <-ctx.Done()35 return nil36 }), nil37 }, kernel.ModuleStage(kernel.StageApplication), kernel.ModuleType(kernel.TypeForeground)))38 serviceChannel := make(chan int)39 options = append(options, kernel.WithModuleFactory("service module", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {40 return FunctionModule(func(ctx context.Context) error {41 processed := 042 for {43 select {44 case <-ctx.Done():45 return nil46 case <-serviceChannel:47 processed++48 if processed > 3 {49 return fmt.Errorf("random fail")50 }51 }52 }53 }), nil54 }, kernel.ModuleStage(kernel.StageService), kernel.ModuleType(kernel.TypeBackground)))55 options = append(options, kernel.WithModuleFactory("hanging module", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {56 return FunctionModule(func(ctx context.Context) error {57 n := 058 for {59 select {60 case <-ctx.Done():61 return nil62 case serviceChannel <- n:63 n++64 }65 }66 }), nil67 }, kernel.ModuleStage(kernel.StageService), kernel.ModuleType(kernel.TypeForeground)))68 k, err := kernel.BuildKernel(context.Background(), config, logger, options)69 assert.NoError(t, err)70 k.Run()71 })72}73func timeout(t *testing.T, d time.Duration, f func(t *testing.T)) {74 done := make(chan struct{})75 cfn := coffin.New()76 cfn.Go(func() error {77 defer close(done)78 f(t)79 return nil80 })81 errChan := make(chan error)82 cfn.Go(func() error {83 timer := time.NewTimer(d)84 defer timer.Stop()85 defer close(errChan)86 select {87 case <-timer.C:88 errChan <- fmt.Errorf("test timed out after %v", d)89 case <-done:90 }91 return nil92 })93 if err := <-errChan; err != nil {94 assert.FailNow(t, err.Error())95 }96 assert.NoError(t, cfn.Wait())97}98func createMocks() (*cfgMocks.Config, *logMocks.Logger, *kernelMocks.FullModule) {99 config := new(cfgMocks.Config)100 config.On("AllSettings").Return(map[string]interface{}{})101 config.On("UnmarshalKey", "kernel", mock.AnythingOfType("*kernel.Settings")).Return(map[string]interface{}{})102 logger := new(logMocks.Logger)103 logger.On("WithChannel", mock.Anything).Return(logger)104 logger.On("WithFields", mock.Anything).Return(logger)105 logger.On("Info", mock.Anything)106 logger.On("Info", mock.Anything, mock.Anything, mock.Anything, mock.Anything)107 module := new(kernelMocks.FullModule)108 module.On("IsEssential").Return(false)109 module.On("IsBackground").Return(false)110 return config, logger, module111}112func mockExitHandler(t *testing.T, expectedCode int) kernel.Option {113 return kernel.WithExitHandler(func(actualCode int) {114 assert.Equal(t, expectedCode, actualCode, "exit code does not match")115 })116}117func TestKernelRunSuccess(t *testing.T) {118 config, logger, module := createMocks()119 module.On("GetStage").Return(kernel.StageApplication)120 module.On("Run", mock.Anything).Return(nil)121 assert.NotPanics(t, func() {122 k, err := kernel.BuildKernel(context.Background(), config, logger, []kernel.Option{123 kernel.WithModuleFactory("module", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {124 return module, nil125 }),126 kernel.WithKillTimeout(time.Second),127 mockExitHandler(t, kernel.ExitCodeOk),128 })129 assert.NoError(t, err)130 k.Run()131 })132 module.AssertCalled(t, "Run", mock.Anything)133}134func TestKernelRunFailure(t *testing.T) {135 config, logger, module := createMocks()136 logger.On("Error", "error during the execution of stage %d: %w", kernel.StageApplication, mock.Anything)137 module.On("GetStage").Return(kernel.StageApplication)138 module.On("Run", mock.Anything).Run(func(args mock.Arguments) {139 panic("panic")140 })141 assert.NotPanics(t, func() {142 k, err := kernel.BuildKernel(context.Background(), config, logger, []kernel.Option{143 kernel.WithModuleFactory("module", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {144 return module, nil145 }),146 kernel.WithKillTimeout(time.Second),147 mockExitHandler(t, kernel.ExitCodeErr),148 })149 assert.NoError(t, err)150 k.Run()151 })152 module.AssertCalled(t, "Run", mock.Anything)153}154func TestKernelStop(t *testing.T) {155 config, logger, module := createMocks()156 var err error157 var k kernel.Kernel158 module.On("IsEssential").Return(false)159 module.On("IsBackground").Return(false)160 module.On("GetStage").Return(kernel.StageApplication)161 module.On("Run", mock.Anything).Run(func(args mock.Arguments) {162 ctx := args.Get(0).(context.Context)163 k.Stop("test done")164 <-ctx.Done()165 }).Return(nil)166 k, err = kernel.BuildKernel(context.Background(), config, logger, []kernel.Option{167 kernel.WithModuleFactory("module", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {168 return module, nil169 }),170 kernel.WithKillTimeout(time.Second),171 mockExitHandler(t, kernel.ExitCodeOk),172 })173 assert.NoError(t, err)174 k.Run()175 module.AssertCalled(t, "Run", mock.Anything)176}177func TestKernelRunningType(t *testing.T) {178 config, logger, _ := createMocks()179 mf := new(kernelMocks.Module)180 // type = foreground & stage = application are the defaults for a module181 mf.On("Run", mock.Anything).Run(func(args mock.Arguments) {}).Return(nil)182 mb := new(kernelMocks.FullModule)183 mb.On("IsEssential").Return(false)184 mb.On("IsBackground").Return(true)185 mb.On("GetStage").Return(kernel.StageApplication)186 mb.On("Run", mock.Anything).Run(func(args mock.Arguments) {187 ctx := args.Get(0).(context.Context)188 <-ctx.Done()189 }).Return(nil)190 k, err := kernel.BuildKernel(context.Background(), config, logger, []kernel.Option{191 kernel.WithModuleFactory("foreground", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {192 return mf, nil193 }),194 kernel.WithModuleFactory("background", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {195 return mb, nil196 }),197 kernel.WithKillTimeout(time.Second),198 mockExitHandler(t, kernel.ExitCodeOk),199 })200 assert.NoError(t, err)201 k.Run()202 mf.AssertExpectations(t)203 mb.AssertExpectations(t)204}205func TestKernelMultipleStages(t *testing.T) {206 config, logger, _ := createMocks()207 options := []kernel.Option{208 kernel.WithKillTimeout(time.Second),209 mockExitHandler(t, kernel.ExitCodeOk),210 }211 var allMocks []*kernelMocks.FullModule212 var stageStatus []int213 maxStage := 5214 wg := &sync.WaitGroup{}215 wg.Add(maxStage)216 for stage := 0; stage < maxStage; stage++ {217 thisStage := stage218 m := new(kernelMocks.FullModule)219 m.On("IsEssential").Return(true)220 m.On("IsBackground").Return(false)221 m.On("GetStage").Return(thisStage)222 m.On("Run", mock.Anything).Run(func(args mock.Arguments) {223 ctx := args.Get(0).(context.Context)224 stageStatus[thisStage] = 1225 wg.Done()226 wg.Wait()227 <-ctx.Done()228 logger.Info("stage %d: ctx done", thisStage)229 for i := 0; i <= thisStage; i++ {230 assert.GreaterOrEqual(t, stageStatus[i], 1, fmt.Sprintf("stage %d: expected stage %d to be at least running", thisStage, i))231 }232 for i := thisStage + 1; i < maxStage; i++ {233 assert.Equal(t, 2, stageStatus[i], fmt.Sprintf("stage %d: expected stage %d to be done", thisStage, i))234 }235 stageStatus[thisStage] = 2236 }).Return(nil)237 allMocks = append(allMocks, m)238 stageStatus = append(stageStatus, 0)239 options = append(options, kernel.WithModuleFactory("m", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {240 return m, nil241 }))242 }243 k, err := kernel.BuildKernel(context.Background(), config, logger, options)244 assert.NoError(t, err)245 go func() {246 time.Sleep(time.Millisecond * 300)247 k.Stop("we are done testing")248 }()249 k.Run()250 for _, m := range allMocks {251 m.AssertExpectations(t)252 }253}254func TestKernelForcedExit(t *testing.T) {255 config, logger, _ := createMocks()256 logger.On("Error", mock.Anything, mock.Anything)257 mayStop := conc.NewSignalOnce()258 appStopped := conc.NewSignalOnce()259 app := new(kernelMocks.FullModule)260 app.On("IsEssential").Return(false)261 app.On("IsBackground").Return(true)262 app.On("GetStage").Return(kernel.StageApplication)263 app.On("Run", mock.Anything).Run(func(args mock.Arguments) {264 ctx := args.Get(0).(context.Context)265 <-ctx.Done()266 appStopped.Signal()267 }).Return(nil)268 m := new(kernelMocks.Module)269 m.On("Run", mock.Anything).Run(func(args mock.Arguments) {270 <-mayStop.Channel()271 assert.True(t, appStopped.Signaled())272 }).Return(nil)273 k, err := kernel.BuildKernel(context.Background(), config, logger, []kernel.Option{274 kernel.WithModuleFactory("m", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {275 return m, nil276 }, kernel.ModuleStage(kernel.StageService), kernel.ModuleType(kernel.TypeForeground)),277 kernel.WithModuleFactory("app", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {278 return app, nil279 }),280 kernel.WithKillTimeout(200 * time.Millisecond),281 kernel.WithExitHandler(func(code int) {282 assert.Equal(t, kernel.ExitCodeForced, code)283 mayStop.Signal()284 }),285 })286 assert.NoError(t, err)287 go func() {288 time.Sleep(time.Millisecond * 300)289 k.Stop("we are done testing")290 }()291 k.Run()292 app.AssertExpectations(t)293 m.AssertExpectations(t)294 assert.True(t, mayStop.Signaled())295}296func TestKernelStageStopped(t *testing.T) {297 config, logger, _ := createMocks()298 logger.On("Errorf", mock.Anything, mock.Anything)299 success := false300 appStopped := conc.NewSignalOnce()301 app := new(kernelMocks.FullModule)302 app.On("IsEssential").Return(false)303 app.On("IsBackground").Return(false)304 app.On("GetStage").Return(kernel.StageApplication)305 app.On("Run", mock.Anything).Run(func(args mock.Arguments) {306 ctx := args.Get(0).(context.Context)307 ticker := time.NewTicker(time.Millisecond * 300)308 defer ticker.Stop()309 select {310 case <-ctx.Done():311 t.Fatal("kernel stopped before 300ms")312 case <-ticker.C:313 success = true314 }315 appStopped.Signal()316 }).Return(nil)317 m := new(kernelMocks.FullModule)318 m.On("IsEssential").Return(false)319 m.On("IsBackground").Return(true)320 m.On("GetStage").Return(777)321 m.On("Run", mock.Anything).Return(nil)322 k, err := kernel.BuildKernel(context.Background(), config, logger, []kernel.Option{323 kernel.WithModuleFactory("m", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {324 return m, nil325 }),326 kernel.WithModuleFactory("app", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {327 return app, nil328 }),329 kernel.WithKillTimeout(200 * time.Millisecond),330 mockExitHandler(t, kernel.ExitCodeOk),331 })332 assert.NoError(t, err)333 k.Run()334 assert.True(t, success)335 app.AssertExpectations(t)336 m.AssertExpectations(t)337}338type fakeModule struct{}339func (m *fakeModule) Run(_ context.Context) error {340 return nil341}342type realModule struct {343 t *testing.T344}345func (m *realModule) Run(ctx context.Context) error {346 cfn, cfnCtx := coffin.WithContext(ctx)347 cfn.GoWithContext(cfnCtx, func(ctx context.Context) error {348 ticker := time.NewTicker(time.Millisecond * 2)349 defer ticker.Stop()350 counter := 0351 for {352 select {353 case <-ticker.C:354 counter++355 if counter == 3 {356 err := unix.Kill(unix.Getpid(), unix.SIGTERM)357 assert.NoError(m.t, err)358 }359 case <-ctx.Done():360 return nil361 }362 }363 })364 err := cfn.Wait()365 if !errors.Is(err, context.Canceled) {366 assert.NoError(m.t, err)367 }368 return err369}370func TestKernel_RunRealModule(t *testing.T) {371 // test that we can run the kernel multiple times372 // if this does not work, the next test does not make sense373 for i := 0; i < 10; i++ {374 t.Run(fmt.Sprintf("fake iteration %d", i), func(t *testing.T) {375 config, logger, _ := createMocks()376 k, err := kernel.BuildKernel(context.Background(), config, logger, []kernel.Option{377 mockExitHandler(t, kernel.ExitCodeOk),378 kernel.WithModuleFactory("main", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {379 return &fakeModule{}, nil380 }),381 })382 assert.NoError(t, err)383 k.Run()384 })385 }386 // test for a race condition on kernel shutdown387 // in the past, this would panic in a close on closed channel in the tomb module388 for i := 0; i < 10; i++ {389 t.Run(fmt.Sprintf("real iteration %d", i), func(t *testing.T) {390 config, logger, _ := createMocks()391 k, err := kernel.BuildKernel(context.Background(), config, logger, []kernel.Option{392 mockExitHandler(t, kernel.ExitCodeOk),393 kernel.WithModuleFactory("main", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {394 return &realModule{395 t: t,396 }, nil397 }),398 })399 assert.NoError(t, err)400 k.Run()401 })402 }403}404type fastExitModule struct {405 kernel.BackgroundModule406}407func (f *fastExitModule) Run(_ context.Context) error {408 return nil409}410type slowExitModule struct {411 fastExitModule412 kernel.ForegroundModule413 stop func()414}415func (s *slowExitModule) Run(_ context.Context) error {416 s.stop()417 return nil418}419func TestModuleFastShutdown(t *testing.T) {420 var err error421 var k kernel.Kernel422 config, logger, _ := createMocks()423 options := []kernel.Option{mockExitHandler(t, kernel.ExitCodeOk)}424 for s := 5; s < 10; s++ {425 options = append(options, kernel.WithModuleFactory("exist-fast", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {426 return &fastExitModule{}, nil427 }, kernel.ModuleStage(s)))428 options = append(options, kernel.WithModuleFactory("exist-slow", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {429 return &slowExitModule{430 stop: func() {431 k.Stop("slowly")432 },433 }, nil434 }, kernel.ModuleStage(s)))435 }436 k, err = kernel.BuildKernel(context.Background(), config, logger, options)437 assert.NoError(t, err)438 k.Run()439}...
linux.go
Source:linux.go
...19)20type linux struct{}21func (linux linux) build(targetArch, vmType, kernelDir, outputDir, compiler, userspaceDir,22 cmdlineFile, sysctlFile string, config []byte) error {23 if err := linux.buildKernel(kernelDir, outputDir, compiler, config); err != nil {24 return err25 }26 if err := linux.createImage(vmType, kernelDir, outputDir, userspaceDir, cmdlineFile, sysctlFile); err != nil {27 return err28 }29 return nil30}31func (linux) buildKernel(kernelDir, outputDir, compiler string, config []byte) error {32 configFile := filepath.Join(kernelDir, ".config")33 if err := osutil.WriteFile(configFile, config); err != nil {34 return fmt.Errorf("failed to write config file: %v", err)35 }36 if err := osutil.SandboxChown(configFile); err != nil {37 return err38 }39 // One would expect olddefconfig here, but olddefconfig is not present in v3.6 and below.40 // oldconfig is the same as olddefconfig if stdin is not set.41 // Note: passing in compiler is important since 4.17 (at the very least it's noted in the config).42 cmd := osutil.Command("make", "oldconfig", "CC="+compiler)43 if err := osutil.Sandbox(cmd, true, true); err != nil {44 return err45 }...
build.go
Source:build.go
...3 "fmt"4 "os"5 "github.com/spf13/cobra"6)7// buildKernel sets up the environment, creates the output directory and builds8// the kernel.9func buildKernel(cmd *cobra.Command, args []string) {10 var err error11 profile, err := getBuildConf(cmd)12 errFatal(err)13 err = profile.Setup()14 errFatal(err)15 err = os.MkdirAll(profile.BuildDir, 0755)16 errFatal(err)17 // If the user provides a build command explicitly only execute that18 if len(args) > 0 {19 errFatal(profile.Build(args))20 return21 }22 if skipconfig, err := cmd.Flags().GetBool("skip-config"); err != nil {23 errFatal(err)...
buildKernel
Using AI Code Generation
1import "fmt"2func main() {3 b.buildKernel()4}5import "fmt"6func main() {7 b.buildKernel()8}9import "fmt"10func main() {11 b.buildKernel()12}13import "fmt"14func main() {15 b.buildKernel()16}17import "fmt"18func main() {19 b.buildKernel()20}21import "fmt"22func main() {23 b.buildKernel()24}25import "fmt"26func main() {27 b.buildKernel()28}29import "fmt"30func main() {31 b.buildKernel()32}33import "fmt"34func main() {35 b.buildKernel()36}37import "fmt"38func main() {39 b.buildKernel()40}41import "fmt"42func main() {43 b.buildKernel()44}45import "fmt"46func main() {47 b.buildKernel()48}49import "fmt"50func main() {
buildKernel
Using AI Code Generation
1import (2func main() {3 build.buildKernel()4}5import (6func main() {7 build.buildKernel()8}9import (10func main() {11 build.buildKernel()12}13import (14func main() {15 build.buildKernel()16}17import (18func main() {19 build.buildKernel()20}21import (22func main() {23 build.buildKernel()24}25import (26func main() {27 build.buildKernel()28}29import (30func main() {31 build.buildKernel()32}33import (34func main() {35 build.buildKernel()36}37import (38func main() {39 build.buildKernel()40}41import (42func main() {43 build.buildKernel()44}45import (46func main() {47 build.buildKernel()48}49import (50func main() {
buildKernel
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 build := Build{}5 build.buildKernel()6}7import (8func main() {9 fmt.Println("Hello, playground")10 build := Build{}11 build.buildKernel()12}13import (14func main() {15 fmt.Println("Hello, playground")16 build := Build{}17 build.buildKernel()18}19import (20func main() {21 fmt.Println("Hello, playground")22 build := Build{}23 build.buildKernel()24}25import (26func main() {27 fmt.Println("Hello, playground")28 build := Build{}29 build.buildKernel()30}31import (32func main() {33 fmt.Println("Hello, playground")34 build := Build{}35 build.buildKernel()36}37import (38func main() {39 fmt.Println("Hello, playground")40 build := Build{}41 build.buildKernel()42}43import (44func main() {45 fmt.Println("Hello, playground")46 build := Build{}47 build.buildKernel()48}49import (50func main() {51 fmt.Println("Hello, playground")52 build := Build{}53 build.buildKernel()54}55import (56func main() {57 fmt.Println("Hello, playground")58 build := Build{}59 build.buildKernel()60}
buildKernel
Using AI Code Generation
1import java.io.*;2import java.util.*;3public class 2 {4 public static void main(String args[]) {5 Scanner sc = new Scanner(System.in);6 int n = sc.nextInt();7 int arr[] = new int[n];8 for (int i = 0; i < n; i++) {9 arr[i] = sc.nextInt();10 }11 build obj = new build();12 obj.buildKernel(arr, n);13 }14}15import java.io.*;16import java.util.*;17public class build {18 public void buildKernel(int arr[], int n) {19 int count = 0;20 int max = 0;21 for (int i = 0; i < n; i++) {22 if (arr[i] == 1) {23 count++;24 } else {25 if (count > max) {26 max = count;27 }28 count = 0;29 }30 }31 System.out.println(max);32 }33}34import java.util.*;35{36 public static void main(String[] args) {37 Scanner sc= new Scanner(System.in);38 int n=sc.nextInt();39 int a[]=new int[n];40 for(int i=0;i<n;i++)41 {42 a[i]=sc.nextInt();43 }44 int count=0,max=0;45 for(int i=0;i<n;i++)46 {47 if(a[i]==1)48 {49 count++;50 }51 {52 if(count>max)53 {54 max=count;55 }56 count=0;57 }58 }59 System.out.println(max);60 }61}62Time Complexity: O(n)63Space Complexity: O(1)
buildKernel
Using AI Code Generation
1import (2func main() {3 build := new(Build)4 build.buildKernel()5 fmt.Println("Kernel build successful")6}719. os.ModeSymlink()
buildKernel
Using AI Code Generation
1import java.util.*;2import java.io.*;3import java.lang.*;4{5 public static void main(String args[])6 {7 Scanner sc=new Scanner(System.in);8 int n=sc.nextInt();9 int m=sc.nextInt();10 int[][] arr=new int[n][m];11 for(int i=0;i<n;i++)12 {13 for(int j=0;j<m;j++)14 {15 arr[i][j]=sc.nextInt();16 }17 }18 Build b=new Build();19 b.buildKernel(arr,n,m);20 }21}22import "fmt"23func main() {24 fmt.Scan(&n,&m)25 for i:=0;i<n;i++ {26 for j:=0;j<m;j++ {27 fmt.Scan(&arr[i][j])28 }29 }30 buildKernel(arr[:][:],n,m)31}32func buildKernel(arr [][]int,n int,m int) {33 for i:=0;i<n;i++ {34 for j:=0;j<m;j++ {35 if arr[i][j]==1 {36 if i-1>=0 && arr[i-1][j]==1 {37 }38 if j-1>=0 && arr[i][j-1]==1 {39 }40 if i+1<n && arr[i+1][j]==1 {41 }42 if j+1<m && arr[i][j+1]==1 {43 }44 }45 }46 }47 for i:=0;i<n;i++ {48 for j:=0;j<m;j++ {49 fmt.Print(arr[i][j]," ")50 }51 fmt.Println()52 }53}54import java.util.*;55import java.io.*;56import java.lang.*;57{58 public static void main(String args[])59 {60 Scanner sc=new Scanner(System.in);61 int n=sc.nextInt();62 int m=sc.nextInt();63 int[][] arr=new int[n][m];64 for(int
buildKernel
Using AI Code Generation
1import (2func main() {3 if len(os.Args) != 4 {4 fmt.Println("Please provide a kernel size and sigma.")5 }6 size, err := strconv.Atoi(os.Args[2])7 if err != nil {8 fmt.Println("Please provide a valid kernel size.")9 }10 sigma, err := strconv.ParseFloat(os.Args[3], 64)11 if err != nil {12 fmt.Println("Please provide a valid sigma.")13 }14 file, err := os.Open(os.Args[1])15 if err != nil {16 fmt.Println("Error opening file.")17 }18 defer file.Close()19 img, err := png.Decode(file)20 if err != nil {21 fmt.Println("Error decoding image.")22 }23 newImg := image.NewRGBA(img.Bounds())24 kernel := buildKernel(size, sigma)25 convolve(img, newImg, kernel)26 out, err := os.Create("out.png")27 if err != nil {28 fmt.Println("Error creating file.")29 }30 defer out.Close()31 err = png.Encode(out, newImg)32 if err != nil {33 fmt.Println("Error encoding image.")34 }35}36func buildKernel(size int, sigma float64) [][]float64 {37 kernel := make([][]float64, size)38 for i := range kernel {39 kernel[i] = make([]float64, size)40 }41 for i := range kernel {42 for j := range kernel[i] {43 x := float64(i - size/2)44 y := float64(j - size/2)45 kernel[i][j] = math.Exp(-(x*x + y*y) / (2 * sigma * sigma
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!