Programming/golang2023. 11. 9. 10:58

눈에도 안들어 온다 으아아

[링크 : https://stackoverflow.com/questions/28040896/why-can-not-convert-sizebyte-to-string-in-go]

 

슬라이스를 배열로 하려면 copy 해야 하는 듯

package main
import "fmt"

//create main function to execute the program
func main() {
   var slice []int // initialize slice
   slice = append(slice, 10) //fill the slice using append function
   slice = append(slice, 20)
   slice = append(slice, 30)
   
   // Convert the slice to an array
   array := [3]int{} //initialized an empty array
   copy(array[:], slice) //copy the elements of slice in newly created array
   fmt.Println("The slice is converted into array and printed as:")
   fmt.Println(array) // prints the output: [10 20 30]
}

[링크 : https://www.tutorialspoint.com/golang-program-to-convert-slice-into-array]

'Programming > golang' 카테고리의 다른 글

golang echo static web / logo.* 안돼?  (0) 2023.12.08
golang 타입 땜시 짜증  (0) 2023.11.10
golang 배열과 슬라이스  (0) 2023.11.08
golang ini 지원  (0) 2023.11.07
golang 함수인자에 배열 포인터  (0) 2023.11.07
Posted by 구차니
Programming/golang2023. 11. 8. 22:34

다시 a tour of go 봐야 할 듯..

 

Arrays
The type [n]T is an array of n values of type T.

The expression

var a [10]int
declares a variable a as an array of ten integers.

An array's length is part of its type, so arrays cannot be resized. This seems limiting, but don't worry; Go provides a convenient way of working with arrays.

[링크 : https://go.dev/tour/moretypes/6]

 

 

Slices
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.

The type []T is a slice with elements of type T.

A slice is formed by specifying two indices, a low and high bound, separated by a colon:

a[low : high]
This selects a half-open range which includes the first element, but excludes the last one.

The following expression creates a slice which includes elements 1 through 3 of a:

a[1:4]

[링크 : https://go.dev/tour/moretypes/7]

 

 

크기가 정해지면 array, 정해지지않으면 slice인가?

Since you didn't specify the length, it is a slice.
An array type definition specifies a length and an element type: see "Go Slices: usage and internals"

[링크 : https://stackoverflow.com/questions/29361377/creating-a-go-slice-without-make]

 

 

갑자기 length와 capacity?!

A slice literal is declared just like an array literal, except you leave out the element count:

letters := []string{"a", "b", "c", "d"}

slice can be created with the built-in function called make, which has the signature,

func make([]T, len, cap) []T

where T stands for the element type of the slice to be created. The make function takes a type, a length, and an optional capacity. When called, make allocates an array and returns a slice that refers to that array.

var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}

When the capacity argument is omitted, it defaults to the specified length. Here’s a more succinct version of the same code:

s := make([]byte, 5)

The length and capacity of a slice can be inspected using the built-in len and cap functions.

len(s) == 5
cap(s) == 5

[링크 : https://go.dev/blog/slices-intro]

 

 

실제 사용시에 capacity까지 알 필요는 없을려나?

capacity: 실제 메모리에 할당된 공간입니다. 만약 슬라이스에 요소를 추가하여 capacity가 가득차면 자동으로 늘어납니다.

[링크 : https://www.pymoon.com/entry/Go-튜토리얼-배열-슬라이스]

[링크 : https://phsun102.tistory.com/82]

[링크 : https://go.dev/tour/moretypes/11]

 

 

2차원 배열은 [][]type 으로 생성하면되는데

make를 통해서도 2차원 배열이 생성가능한진 모르겠다

package main

import "fmt"

func main() {
    // Step 1: create empty collection.
    values := [][]int{}

    // Step 2: these are the first two rows.
    // ... Append each row to the two-dimensional slice.
    row1 := []int{1, 2, 3}
    row2 := []int{4, 5, 6}
    values = append(values, row1)
    values = append(values, row2)

    // Step 3: display first row, and second row.
    fmt.Println("Row 1")
    fmt.Println(values[0])
    fmt.Println("Row 2")
    fmt.Println(values[1])

    // Step 4: access an element.
    fmt.Println("First element")
    fmt.Println(values[0][0])
}
Row 1
[1 2 3]
Row 2
[4 5 6]
First element
1

[링크 : https://www.dotnetperls.com/2d-go]

 

 

 

make와 := []type 두개가 동등하다면 가능할지도?

package main

import (
"fmt"
"strings"
)

func main() {
// Create a tic-tac-toe board.
board := [][]string{
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
}

// The players take turns.
board[0][0] = "X"
board[0][2] = "X"
board[1][0] = "O"
board[1][2] = "X"
board[2][2] = "O"


for i := 0; i < len(board); i++ {
fmt.Printf("%s\n", strings.Join(board[i], " "))
}
}
X _ X
O _ X
_ _ O

[링크 : https://go.dev/tour/moretypes/14]

'Programming > golang' 카테고리의 다른 글

golang 타입 땜시 짜증  (0) 2023.11.10
golang 타입 캐스팅 제약(?)  (0) 2023.11.09
golang ini 지원  (0) 2023.11.07
golang 함수인자에 배열 포인터  (0) 2023.11.07
c to golang online converter  (0) 2023.11.07
Posted by 구차니
Programming/golang2023. 11. 7. 15:29

텍스트로 보이는 환경설정 파일로는 ini만한게 없지..

 

[링크 : https://pkg.go.dev/gopkg.in/ini.v1]

[링크 : https://github.com/go-ini/ini/]

[링크 : https://minwook-shin.github.io/read-and-write-ini-files-ini/]

'Programming > golang' 카테고리의 다른 글

golang 타입 캐스팅 제약(?)  (0) 2023.11.09
golang 배열과 슬라이스  (0) 2023.11.08
golang 함수인자에 배열 포인터  (0) 2023.11.07
c to golang online converter  (0) 2023.11.07
golang slice  (0) 2023.11.07
Posted by 구차니
Programming/golang2023. 11. 7. 14:38

c 들어내고 go로만 짜려니 어렵네..

함수 인자로 포인터를 넘겨줄 때에도 변수의 크기 정보가 넘어가야 한다.

그래서 정확한 포인터의 길이가 함수 인자에 지정되어야 한다.

그럼.. 굳이 포인터 쓸 필요가 없어지는거 아닌가?

 

// Golang program to pass a pointer to an 
// array as an argument to the function 
package main 
  
import "fmt"
  
// taking a function 
func updatearray(funarr *[5]int) { 
  
    // updating the array value 
    // at specified index 
    (*funarr)[4] = 750 
      
    // you can also write  
    // the above line of code 
    // funarr[4] = 750 

  
// Main Function 
func main() { 
  
    // Taking an pointer to an array 
    arr := [5]int{78, 89, 45, 56, 14} 
  
    // passing pointer to an array 
    // to function updatearray 
    updatearray(&arr
  
    // array after updating 
    fmt.Println(arr) 

[링크 : https://www.geeksforgeeks.org/golang-pointer-to-an-array-as-function-argument/]

'Programming > golang' 카테고리의 다른 글

golang 배열과 슬라이스  (0) 2023.11.08
golang ini 지원  (0) 2023.11.07
c to golang online converter  (0) 2023.11.07
golang slice  (0) 2023.11.07
golang echo bind  (0) 2023.11.06
Posted by 구차니
Programming/golang2023. 11. 7. 12:11

꿀~ 개꿀~ dog honey~

 

[링크 : https://kalkicode.com/c-to-golang-converter-online]

'Programming > golang' 카테고리의 다른 글

golang ini 지원  (0) 2023.11.07
golang 함수인자에 배열 포인터  (0) 2023.11.07
golang slice  (0) 2023.11.07
golang echo bind  (0) 2023.11.06
golang echo 구조체 배열은 미지원?  (0) 2023.11.06
Posted by 구차니
Programming/golang2023. 11. 7. 10:42

배열이라고 안하고 slice 라고 하는건지, 아니면 배열은 따로 있는건지 모르겠지만

matlab 이나 octave 와 비슷하게 배열을 마음대로 가지고 놀 수 있다.

package main

import "fmt"

func main() {
primes := [6]int{2, 3, 5, 7, 11, 13}

var s []int = primes[1:4]
fmt.Println(s)
}
[3 5 7]

[링크 : https://go.dev/tour/moretypes/7]

[링크 : http://golang.site/go/article/13-Go-컬렉션---Slice]

 

음.. slice와 array는 다른거군.

아무튼 slice를 array로 바꾸려면 그냥 일일이 복사해서 넣어줘야 하나 보다.

package main
import "fmt"

//create main function to execute the program
func main() {
   var slice []int // initialize slice
   slice = append(slice, 10) //fill the slice using append function
   slice = append(slice, 20)
   slice = append(slice, 30)
   
   // Convert the slice to an array
   var array [3]int
   for i, element := range slice {
      array[i] = element // store slice elements in the newly created array
   }
   fmt.Println("The array is printed after conversion from slice:")
   fmt.Println(array) // prints the output: [1 2 3]
}

[링크 : https://www.tutorialspoint.com/golang-program-to-convert-slice-into-array]

'Programming > golang' 카테고리의 다른 글

golang 함수인자에 배열 포인터  (0) 2023.11.07
c to golang online converter  (0) 2023.11.07
golang echo bind  (0) 2023.11.06
golang echo 구조체 배열은 미지원?  (0) 2023.11.06
golang echo 패키지 소스  (0) 2023.09.13
Posted by 구차니
Programming/golang2023. 11. 6. 16:49

어라.. 저번에는 되더니 먼가 달라져서 안되는걸까..

jquery 3.6.1 에서 3.7.1로 올라가서 그런가?

버전 바꾸어서 해봐도 3.6이나 3.7이나 동일하다. 머가 문제지?

 

 

아래에서 query라고 써있는 부분이 struct tag 라고 하는데

쿼리 스트링에서 id 부분을 파싱해서 값을 넣어달라는 의미이다

query 는 아래 녹색 줄 처럼 생긴 것.

type User struct {
  ID string `query:"id"`
}

// in the handler for /users?id=<userID>
var user User
err := c.Bind(&user); if err != nil {
    return c.String(http.StatusBadRequest, "bad request")
}

 

아래와 같이 query, json, form 등이 주로 쓰이는지 예제에서는 세가지가 보인다.

Data Sources
Echo supports the following tags specifying data sources:

query - query parameter
param - path parameter (also called route)
header - header parameter
json - request body. Uses builtin Go json package for unmarshalling.
xml - request body. Uses builtin Go xml package for unmarshalling.
form - form data. Values are taken from query and request body. Uses Go standard library form parsing.

[링크 : https://echo.labstack.com/docs/binding]

 

 

하나만 쓸 수도 있고 여러 개 늘어놓고 쓸수도 있지만, 보안을 고려하면 딱 맞추는게 좋을 듯.

type User struct {
  Name  string `json:"name" form:"name" query:"name"`
  Email string `json:"email" form:"email" query:"email"`
}

 

그나저나.. jquery ajax를 이용해 post로 보냈는데 왜 query로 처리가 되냐...

'Programming > golang' 카테고리의 다른 글

c to golang online converter  (0) 2023.11.07
golang slice  (0) 2023.11.07
golang echo 구조체 배열은 미지원?  (0) 2023.11.06
golang echo 패키지 소스  (0) 2023.09.13
go packed struct  (0) 2023.09.01
Posted by 구차니
Programming/golang2023. 11. 6. 11:54

안되면 그냥 _1 _2 붙여서 해야지 머 -_ㅠ

 

Echo framework does not support binding array from form data out of the box.
You can use json instead or use 3rd party library. See implementation or post and github issue https://github.com/labstack/echo/issues/1644

[링크 : https://stackoverflow.com/questions/69409036/how-to-bind-multipart-form-data-array-in-echo-framework]

 

 

[링크 : https://stackoverflow.com/questions/69445675/please-tell-me-how-to-bind-multi-array-to-struct/69449814#69449814]

'Programming > golang' 카테고리의 다른 글

golang slice  (0) 2023.11.07
golang echo bind  (0) 2023.11.06
golang echo 패키지 소스  (0) 2023.09.13
go packed struct  (0) 2023.09.01
golang asm  (0) 2023.08.24
Posted by 구차니

이 선이 머다~ 라고 써있는데 legend인데

거기 클릭하면 선이 보이고 안보이고 하는 기능을 picking이라고 적어 놓은듯

 

우측 상단에 1 Hz / 2 Hz가 legend인데

레전드 내의 파란색 선을 아~~~주 잘 골라서 클릭하면

 

아래처럼 사라진다.

[링크 : https://matplotlib.org/stable/gallery/event_handling/legend_picking.html]

'Programming > python(파이썬)' 카테고리의 다른 글

ipython notebook -> jupyter notebook  (0) 2024.01.11
파이썬 가상환경  (0) 2024.01.09
matplotlib  (0) 2023.10.04
pyplot  (0) 2023.10.04
python matplotlib 설치  (0) 2023.03.08
Posted by 구차니

gnuplot을 래핑해서 만든건줄 알았는데 독립된 건가?

[링크 : https://matplotlib.org/stable/tutorials/pyplot.html]

 

500.000 points scatterplot
gnuplot:      5.171 s
matplotlib: 230.693 s

[링크 : https://stackoverflow.com/questions/911655/gnuplot-vs-matplotlib]

 

2차축 추가. y축에 대해서 주로 넣지 x 축에 넣는건 먼가 신선하네

import datetime

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.dates as mdates
from matplotlib.ticker import AutoMinorLocator

fig, ax = plt.subplots(layout='constrained')
x = np.arange(0, 360, 1)
y = np.sin(2 * x * np.pi / 180)
ax.plot(x, y)
ax.set_xlabel('angle [degrees]')
ax.set_ylabel('signal')
ax.set_title('Sine wave')


def deg2rad(x):
    return x * np.pi / 180


def rad2deg(x):
    return x * 180 / np.pi


secax = ax.secondary_xaxis('top', functions=(deg2rad, rad2deg))
secax.set_xlabel('angle [rad]')
plt.show()

[링크 : https://matplotlib.org/stable/gallery/subplots_axes_and_figures/secondary_axis.html]

 

특이하게 배열로 된 값이 들어가는게 아닌, 함수를 통해서 1차축에 대해서 계산해서 2차축을 쓰는 듯?

Axes.secondary_xaxis(location, *, functions=None, **kwargs)
Axes.secondary_yaxis(location, *, functions=None, **kwargs)

functions2-tuple of func, or Transform with an inverse
If a 2-tuple of functions, the user specifies the transform function and its inverse. i.e. functions=(lambda x: 2 / x, lambda x: 2 / x) would be an reciprocal transform with a factor of 2. Both functions must accept numpy arrays as input.

The user can also directly supply a subclass of transforms.Transform so long as it has an inverse.

See Secondary Axis for examples of making these conversions.

[링크 : https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.secondary_xaxis.html#matplotlib.axes.Axes.secondary_xaxis]

[링크 : https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.secondary_yaxis.html#matplotlib.axes.Axes.secondary_yaxis]

'Programming > python(파이썬)' 카테고리의 다른 글

파이썬 가상환경  (0) 2024.01.09
pyplot legend picking  (0) 2023.10.05
pyplot  (0) 2023.10.04
python matplotlib 설치  (0) 2023.03.08
python openCV / PIL 포맷 변경  (0) 2022.04.12
Posted by 구차니