2024. 2. 18.

get path variable in dynamic routing in app routing of next.js

 Next.js 

 app routing 

dynamtic routing


Next.js 에서 app routing을 사용할때  dynamic path를 사용하는 경우  path로 넘기는 변수 값을 얻어 오기 

page에 대한 dynamic routing은 설명이 되어 있으나 ,  route.js에서 쓰는 방법을 찾기가 어려웠음 

https://nextjs.org/docs/app/api-reference/file-conventions/route

route.ts 에 패스를 넘기는 설명이 있음


링크 예제에는 아래와 같이 되어 있으나, 

export async function GET(request, context: { params }) {
const team = params.team; // '1'
...
}

위 경우를 아래와 같이  수정 함 

async function GET(req: NextRequest, context: { params: any }) {
const companyId = context.params.companyId;
const memberId = context.params.memberId;
...
}

디렉토리 구조 


2024. 1. 7.

Copy recursive files from directory to directory ( to remember) 디렉토리에서 있는 디렉토리로 복사하기

 필요하지만 잊어 먹는 커맨드


디렉토리에서  기존 디렉토리로 모두 복사 할때 (디렉토리 포함 ) 

cp -Rv  sourcedir/.*   targetdir/         ## 숨은디렉토리까지 복사 ( R 하위포함,   v:진행과정 표시)

2024. 1. 1.

Using Modal component of Next.UI ( close , )

 Next.UI 의 modal 컴포넌트를 사용할때  몇가지 팁


1) 선택된 아이템의 값으로 모달에서 표시할 때 

  •      모달을 띄우는 버튼 클릭 이벤트에서  useState에 변수를 선언하여 현재 선택된 데이터를 설정한다.

    //  바로 이벤트를 매핑 하는 경우 클릭 된 값을 설정하거나 전달  할 수 없으므로, 

<Button onPress={clickDelete} >선택 </Button>

  // 바로 이벤트를 매핑하지 말고 { }  현재 설정값 을 state에 설정하고  모달을 띄우고 설정된 값을 참조하도록 한다 호출을 하는 방식을 아래와 같이 바꿔본다.

//   event={eventFunc}     ---> event={    ( ) =>{ eventFunc(parameter) } }

const [selectedData, setSelectedData] = useState<MyItem>();
const clickButton = (item: MyItem) => {
console.log(item)
setSelectedData(item)
onOpen() // modal 열기
}
//----------------------------------------------------
<Button onPress={()=>{clickButton(item)}} />

// Modal 내에서, item의 속성을 표시한다
{item.title}


2) 모달에서 데이터를 처리하고 모달을 닫을 때, 모달내 button 에 이벤트를 연결하고 호출

<Button color="primary" variant="ghost" onPress={onProcess}>닫기</Button>
//--------------------------------------------
const onProcess = () => {
someCustomProcess() // some custom process you needed
onOpenChange() // modal close
}



2023. 12. 30.

자주 쓰지만 자꾸 잊어 먹는, ssh 암호없이 키로 접속하기

기본단계

 1) 키페어 생성

     ~/.ssh/id_rsa         # private key

    ~/.ssh/id.rsa.pub  # public key ( 다른 서버에 복사해야할 파일)

2) pub 키를 접속할 호스트로 복사

      scp  ~/.ssh/id_rsa   remoteuser@remotehost:id_rsa.tmp 

3)  ssh 접속후 키 복사 (기존 파일에 붙여 넣기 ) 

       cat   id_rsa.tmp >> ~/.ssh/authorized_keys

4) 이후 패스워드 없이 접속

ssh remoteuser@remotehost


2023. 11. 18.

Install Virtualenv on osX (MAC)

 1) Install brew 

     home page:  https://brew.sh/

2 ) Install python3 

  $>  brew install python3

3) Install virtualenv

  $> pip3 install virtualenv

4) check installed python version

   ls -l /usr/local/bin/python*

5) make Local Env 

  $> python3 -m virtualenv  venv310 --python=/usr/local/bin/python3.10

     // venv310 :  directory which contains python3.10 data 

     // --python={installed path}  :  source path which is selected python version

2023. 7. 15.

Passing custom event function from parent component to child in react

 


Passing  function  from parent to child component 
for click-event customizing 

1) define function in app level

    function. custom_event (key, event) {

      // this is custom function 

      console.log ("call custom function ") ;

    }

2) passing custom function to child by property

     when click item ,  item calls internalClick

       custom_event function is called by name "customFunction" in internalClick function 

        


// in app.js     

  function. custom_event (key, event) {

      // this is custom function 

      console.log ("call custom function ") ;

    }

 <BoardList  customFunction= { this.props.custom_event }  />    


//  in BoardList.js

      // some loop ... 

     <BoardRow keyField={ this.props.keyField}   customFunction = { this.props.customFunction} /> 


//  in BoardRow.js 

     <BoardItem keyField={ this.props.keyField} customFunction = { this.props.customFunction} /> 

// in BoardItem.js 

     internalClick = (e) => {

       console.log ( "click item ") ;

       this.props.customFunction(this.props.keyField , e) ;

     }

    render() {

          return (<button  onClick = { this.internalClick } > click </button>)

    }

    

      

    



Python new string format (update) f-string

 Update .. 

Late news 


My previous post:  2016 

https://blog.boxstory.com/2016/08/python-new-string-format.html


New Addition  :  f-string   ( support  from 3.6 )

variable = 'hello'
print(f' my variable is {variable}') # using f' xxxx {variable_name}'


 # output 
my variable is hello 

# Yes , It's very simple and powerful. 

2023. 5. 21.

brew command list in mac OS


homepage: 

  • site : https://brew.sh/ 
  • full command list : https://docs.brew.sh/Manpage

Minimum command list

  • Install
    • brew install {programname}
  • Start service 
    • brew services start {program name}
  • Stop service
    • brew services stop {program name }
  • List services
    • brew services list
  • Update brew itself
    • brew update
  • Upgrade program
    • brew upgrade {program name }

2023. 5. 20.

License listing used in java project ( maven, gradle )

maven ( POM.xml)

  • run task site,
  • files are generated in
    • target/site/dependencies.html
    • target/site/project-info.html
<Project> <reporting> <plugins> <plugin> <!-- This plugin needs site plugin" --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.4.3</version> <reportSets> <reportSet> <reports> <report>dependencies</report> <report>licenses</report> </reports> </reportSet> </reportSets> </plugin> </plugins> </reporting> ...

gradle (build.gradle)

  • run task : generateLicenseReport
  • file generated in
    • build/licenses/index.html
    • build/licenses.csv
    • build/index.xml
import com.github.jk1.license.render.* //import com.github.jk1.license.importer.* plugins { id 'java' id 'org.springframework.boot' version '3.0.6' id 'io.spring.dependency-management' version '1.1.0' id 'project-report' id 'com.github.jk1.dependency-license-report' version '2.1' } // ref : https://github.com/jk1/Gradle-License-Report // run generateLicenseReport licenseReport { outputDir = "$projectDir/build/licenses" renderers = [new InventoryHtmlReportRenderer(),new XmlReportRenderer(), new CsvReportRenderer()] }

2023. 4. 15.

Example code : Split PDF using PyPDF2 (python)

 

  • Very simple example code
  • ref : https://pypdf2.readthedocs.io/en/3.0.0/
* install 
  >> pip install PyPDF2 

*sample src: sample pdf has 38 pages.

12 files are generated and each file has three pages.

this code uses fixed file count number because I already know page count, 

but you can use "len(src_pdf.pages)" to get page count of source file.

from PyPDF2 import PdfFileReader, PdfFileWriter

src_pdf = PdfFileReader(open("./src.pdf'))

for file_index in range(12): # <= len(src_pdf.pages)/3
writer = PdfFileWriter()
for page_index in range(3):
writer.addPage(src_pdf.getPage(file_index*3+page_index+2))
writer.write(open("./out-{:02}.pdf".format(file_index), 'wb'))


== ver 3.0.1 
generate single page
from PyPDF2 import PdfReader, PdfWriter

src_pdf = PdfReader("./multi-page.pdf")
number_of_pages = len(src_pdf.pages)
writer = PdfWriter()

for idx in range(number_of_pages):
    writer.add_page(src_pdf.pages[idx])
    writer.write(open(f"./single-page-{idx}.pdf", 'wb'))

2023. 4. 2.

Looking for lottie files ( animated file format ) Echo system

 

로티를 찾아서

  • 이야기의 시작은 유튜브 영상을 만들려고 하는데서 부터 시작 된다. 남들도 다 한다는 유뷰브를 하기 위해서 핸드폰으로 영상을 찍었고, imovie를 이용해서 동영상을 제작하면서, 뭔가 부족함을 느껴 툴을 찾던중 createstudio 라는 것을 알게 되었고 유료로 구매를 하게 되었다. 이 프로덕트의 특징중 하나는 움직이는 애니메이션들을 넣을수 있는데 기본적인 것 이외의 추가적인 것들은 당연하게도 추가로 유료를 지불해야 하는데, 그중 하나가 애니메이션이 되는 클립이였다. 그런데 , 어느날 인가 lottie 형식의 애니메이션을 지원하다고 했는데 , 생소한 포맷이여서 알아보니, AfterEffects 애니메이션을 json형식으로 만들고, 모바일과 웹에서 랜더링할수 있게 만들어준 라이브러리 였다. ( https://airbnb.io/lottie/#/ , https://lottiefiles.com/)
  • 모바일 앱에서 인트로 화면에서 애니메이션이 되는 것들을 볼수 있는데, 동영상을 쓸수도 있지만, lottie파일을 이용해서 하는 경우들이 많이 있다고들 했다. - 벡터이므로, 디바이스별로 해상도에 신경쓰지 않아도 된다. 또한 파일 사이즈도 작으며, 상호작용에 대한 동작도 지원한다.
  • 그래서, 로티형식의 애니메이션클립을 만들수 있는 툴을 찾아보니, abode의 ‘AfterEffect’이외의 haiku 라는 툴이 있었고 나름 직관적인 UI 로 기능도 나쁘지 않고, 사용법도 어렵지 않아서, 사용법을 익히던 중, 궁금한 것이 있어 홈페이지에 들어가지, 유지 보수가 안되고 있는지 페이지 링크도 깨져 있고, 검색한 결과는 모두 시간이 좀 지난 것들 뿐이였다. 기능상 버그라기 보다는 사용법을 좀더 심도 있게 익히기 위해서는 많은 노력이 들어가야 한다는 것을 알았다. 더 이상 사용법 익히기를 중단 했다.
  • 유료지만, afterEffect를 필요할때 구독해서 써야 할것 같다.

관련 프로그램 및 자료들 , 용어
  • Clip animation tools
    • haiku, flow, synfig, after effect
  • Presentation/Motion EditTools
    • after effect
    • CreateStudio 
  • format
    • lottie files
    • svg : scalable vector graphic


2022. 12. 4.

Using paginator in boto3


How to convert codes for using paginator

### no paginations code
  1. for region in regions:
  2.     resource = boto3.client('resourcegroupstaggingapi', region_name=region)
  3.     res = resource.get_resources(ResourceTypeFilters=resource_type_filters)
  4.     list_items(res)

    

### using paginator code
  1. for region in regions:
  2.     resource = boto3.client('resourcegroupstaggingapi', region_name=region)
  3.     paginator = resource.get_paginator('get_resources')  # parameter is 'method name' which is LINE3 of above code 
  4.     response_iterator = paginator.paginate(ResourceTypeFilters=resource_type_filters) #Passing parameter is same with   LINE3 in above code
  5.     for page in response_iterator:
  6.         list_items(page)

2022. 10. 16.

migration evernote to notion ( by python program :enex2notion)

I 've been used  evernote for a long time. but  I changed to notion recently. 

I tried to export data from  evernote to notion. The guide which is proposed by notion team is not good.  But I found 'enex2notion' tool  by googling. It it very effective for me although  some installation step is not simple for me.

I shared it for another users.  

My pc is mac. 

ref: https://github.com/vzhd1701/enex2notion

Step 

1. install enex2notion
  -  you can refer on above ref site. Don't give it up , this app is compensate for your install try.

2. export notebooks from evernote app.

2.5  get  auth_v2 key from your browser
  -  open notion with web browser and login 
  -  find cookie ( token_v2)  in browser. You need  token to upload to notion 




3 run enex2notion with notebook file (*.enex)
 - program will upload  pages one by one  ( Upload speed is not fast.)
 - some pages are fail to uploading. ( You must copy these pages by manual )
 - You can check progress on your notion app.

 enex2notion --token <TOKEN from 2.5 step> "mynotebook.enex"  ## do not include letter "<", ">"
4. Check pages which are uploaded. 

2022. 8. 13.

OrderedDict. ( in Python)

func: Dictionary remembers added order of items.

Ref : https://docs.python.org/3/library/collections.html


Usecase  sample : convert number to roman numerals.


import string
from collections import OrderedDict

def to_roman(num):
maps = OrderedDict([('M', 1000), ('CM', 900), ('D', 500),
('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40),
('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)])
res = ''
for k, v in maps.items():
while num >= v:
print(f' {num}, {v}')
res += k
num -= v
return res

print(1988)
print(to_roman(1988))

### output #####
1988 1988, 1000 988, 900 88, 50 38, 10 28, 10 18, 10 8, 5 3, 1 2, 1 1, 1 MCMLXXXVIII



2022. 7. 3.

Loading xml data in excel vba by using XML Object(MSXML2.DOMDocument)

### in excel file ( xlsm , macro excel , enable macro) 


' Declare xml object

  set xmlObj = CreateObject("MSXML2.DOMDocument.6.0")

 ' set loading option with non async

 xmlObj.Async = False

' validate off

xmlObj.validateOnParse = False

' reading file from sample.xml 

xmlObj.Load "sample.xml"

' select all "mynode" from root node recursively ( ref. xml path grammar in detail)

' root node에서 mynode 모두 선택하기 추가적인 부분은 xml path 문법을 참고

Set nodeList = xmlObj.SelectNodes("//mynode")

for index to nodeList.Length -1 

    set myNode = nodeList(index)

    ' do somthing 

    aa = myNode.text

next index


2021. 12. 18.

Install node.js as you want with package 'n'

NodeJs install manager 'n'

  • You can install /update  nodejs as you want  with package 'n' 
  • please refer as below link in detail
    •  https://github.com/tj/n


## install   : 

npm install -g n     # 'n' is not option, It's package name. 


2021. 8. 31.

Using simple web server for firewall test (python)

 ## 3.x ( # ref : https://docs.python.org/3/library/http.server.html)

python3 -m http.server  {port}

# ex) run 8888 port

$ python3 -m http.server 8888        







### server1 ####

curl http://server2:8888

> default response is  file listing 

### server2 ####

python3 -m http.server 8888


2021. 8. 16.

build vuejs with new config mode with production build

 ## When you want to use another config values in deploying. you must add NODE_ENV=production


## .env.mynewmode

   NODE_ENV=production                 ##<-- this line makes files for deploying 

   VUE_APP_MY_VAR='mynewvalue' 


## build

npm run build -- --mode mynewmode


#ref: https://cli.vuejs.org/guide/mode-and-env.html#modes



https://cli.vuejs.org/guide/mode-and-env.html#modes

using app_vue variable in scss file

 VUEJS 2.x

## vue.config.js

css: {
loaderOptions: {
sass: {
perpendData: `
$VAR_NAME: "
${VUE_APP_MY_VAR1}" ;
`;
}
}
}


### in scss
  att:  $VUE_APP_MY_VAR1 + "my.png"