728x90

zxing 을 이용하여 QR코드를 스캔하는 방법에 대한 코드 작성에 필요한 핵심 내용을 기술한다.


앱 build.gradle

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
    implementation 'gun0912.ted:tedpermission:2.0.0'
    implementation 'com.google.android.material:material:1.1.0'
}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.link2me.android.qrcodesample">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission
        android:name="android.permission.REQUEST_INSTALL_PACKAGES"
        tools:ignore="ProtectedPermissions" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="false"
        android:hardwareAccelerated="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        <activity android:name=".MainActivity"
            android:screenOrientation="portrait"/>
        <activity
            android:name="com.journeyapps.barcodescanner.CaptureActivity"
            android:screenOrientation="portrait"
            tools:replace="screenOrientation" />
        <activity android:name=".SplahActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ScanQRActivity"
            android:screenOrientation="portrait"/>
    </application>

</manifest>


ScanQRActivity.java

public class ScanQRActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();
    private IntentIntegrator qrScan;
    Context mContext;
    String QRcode;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scanqr);
        mContext = ScanQRActivity.this;

        qrScan = new IntentIntegrator(this);
        qrScan.setOrientationLocked(false);
        qrScan.setPrompt("QRcode Sample!");
        qrScan.initiateScan();

        textView = findViewById(R.id.textView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(ScanQRActivity.this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            } else {
                if(result.getContents() != null) {
                    QRcode = result.getContents();
                    PrefsHelper.write("QRCode",result.getContents());
                    // QRcode 결과를 가지고 서버에서 정보를 조회하여 가져오거나, 다른 처리를 하면 된다.
                    // QRcode 읽은 결과를 화면에 표시
                    textView.setText(QRcode);
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

}


resource 등 코드 세부적인 사항은 https://github.com/jsk005/JavaProjects/tree/master/qrcodesample 를 참조하시길.

'안드로이드 > Android QRCode' 카테고리의 다른 글

PHP TCPDF 설치 및 샘플 코드  (0) 2020.05.30
PHP QR code 생성하는 방법  (0) 2020.03.04
QRCode 개요  (0) 2020.03.03
블로그 이미지

Link2Me

,
728x90

Git 을 설치하고 나서 기본적으로 알아야 할 명령어를 Visual Studio Code 툴에서 사용해보자.

 

GitHub 자료와 내 PC Git 과 비교하여 상이한 자료 가져오기

git pull origin master

 

Git 생성 및 GitHub 업로드

git config --global user.name "Charlie"
git config --global user.email "abc@naver.com"
git config --global core.autocrlf true
git config --global --list
 
git init  # 현재 디렉토리에 Git 생성
git status
git add .  # 변경된 모든 소스 추가
git commit -"1st commit"  #커밋(버전 생성)
git remote add origin https://github.com/jsk005/JavaBasic.git
git push -u origin master  # 최종 push 로 GitHub에 업로드
 

 

git init 는 한번 설정하고 나면 다시 하지 않아도 된다.

git push origin +master 도 master 에 계속 추가하는 것이라면 git push 만 해도 된다.

#GitHub에 데이터를 업데이트할 때
git init
git status
git add .
git commit -"1st commit"
git push origin +master

 

#GitHub에 데이터를 업데이트할 때
git init
git status
git add .
git commit -"1st commit"
git remote add origin https://github.com/jsk005/JavaBasic.git
git branch -M main
git push -u origin main

add: 내 컴퓨터에서 작업한 파일들을 스테이지에 추가

git add . 으로 해도 된다.

commit: 스테이지에 올라온 파일들을 가지고 내 컴퓨터에 저장

push: 커밋들을 원격 저장소에 업로드

 

브랜치 생성/이동/삭제

# branch 생성
# git branch 브랜치명
git branch add-style
 
# 브랜치 생성 및 현재 브랜치 위치 확인
git branch
 
# 브랜치로 이동
git checkout add-style
git checkout master
 
# 브랜치 생성과 동시 이동
git checkout -b add-style2
 
# 브랜치 삭제 : 현재 생성된 브랜치에서는 삭제 불가
# 다른 브랜치로 이동한 후 삭제 가능
git branch -d 브랜치명
 

 

브랜치 병합

# abc 브랜치 생성
git branch adc
 
# abc 브랜치로 이동
git checkout abc
 
# 필요한 파일 수정하면 git status 로 확인
git status
 
# git add . 으로 커밋 준비
git add .
git commit -"다형성 수정"
 
# 현재 branch 확인
git branch
 
# master 브랜치로 이동
git checkout master
 
# master 브랜치에서 abc 브랜치 병합
git merge abc
 
# 버전 확인
git log
 

 

버전 되돌리기

# 버전 되돌리기
# 먼저 log 로 생성된 버전을 확인한다.
git log
 
# 버전 되돌리기 : HEAD~1 이라고 입력할 것을 HEAD~ 로 1을 생략 가능
git reset --hard HEAD~
git log
 
# 버전 원복하기 (되돌리기 한 후 바로 아래 명령 실행하면 가능)
# 기존 버전을 ORIG_HEAD 라는 메모리에 잠시 보관
git reset --hard ORIG_HEAD
git log
 
# 2단계 전 버전으로 되돌리기
git reset --hard HEAD~2
git log

 

Git 생성 및 GitHub 업로드 예제

먼저 GitHub에 저장할 폴더를 JavaProjects 라고 만들었다.

그리고 VS Code에서 JavaProjects 폴더 하단에 ActivityChange 라는 폴더를 만들고 코드를 옮겨놓았다.

Android Studio 에서 직접 연결하지 않고 별도로 폴더를 복사해서 업로드하는 걸 해보고 싶어서다.

 

VS Code에서 Ctrl + ' 를 누르면 Termial 창이 보인다.

 

git init : 깃 저장소 생성 및 로컬저장소로 사용되도록 설정

git init 명령어를 실행하면 아래와 같이 숨김폴더 git이 생성된다.

 

git bash 실행
git config --global user.name "Json-Jeon"
git config --global user.email "jsk005@daum.net"

 

현재 설정정보 조회

git config --global --list

 

 

파일 상태 명령어

git status

 

git add : index에 파일 추가하는 명령어

git add --all

을 하려면 현재 폴더에 반드시 1개 이상의 파일이 존재해야 한다.

 

git status : 파일 상태 확인 명령어

 

git commit : 폴더의 변경 내용을 저장

 

 

이제 원격 저장소를 추가해보자
git remote

위를 입력하면 처음에는 원격저장소에 연결된적이 없어서 아무것도 안나온다

 

Github 사이트에서 new repository를 해서 새로운 프로젝트를 생성한다.

 

생성한 Repository 폴더에 들어가면 아래와 같은 명령어가 친절하게 보일 것이다.

 

git remote add [단축이름] [url]
git push [리모트 저장소이름 ] [브랜치 이름]

 

명령어를 복사해서 아래 그림과 같이 붙여넣기 한다.

git remote add origin https://github.com/jsk005/JavaProjects.git
git push -u origin master

 

 

이제 GitHub email 과 password 를 입력하고 로그인한다.

 

위와 같이 파일이 업로드되었다고 나온다.

 

git remote -v
로컬 저장소에 있던 파일, 폴더들이 제대로 원격 저장소로 이동했는지를 확인하는 명령어

위와 같이 나온다면 성공이다.

 

GitHub 사이트에서 조회하면 파일이 업로드된 걸 확인할 수 있다.

 

이상으로 간단하게 git 명령어와 파일을 GitHub에 업로드하는 걸 해봤다.

 

자료를 추가하는 데 에러가 발생하고 올라가지 않는다.

git push origin +master

를 하면 자료가 업로드되는데 기존 데이터는 보장하지 못한다.

 

 

'자료 구하기 > Git' 카테고리의 다른 글

소스트리 설치  (0) 2021.02.18
윈도우10 Git 설치  (0) 2020.08.23
블로그 이미지

Link2Me

,
728x90

Git은 소스 코드 형상관리 툴이다.

유투브 동영상 검색하면 설명 잘 나온다.


- Git 은 소스코드 형상관리를 본인의 PC에 한다.

- 서버(GitHub)에 업로드하여 관리할 수 있다.

- 같은 소스코드로 여러명이 동시에 개발이 가능하다. (branch)

- 최종적으로 의사결정하여 본 프로그램에 합치는 것(merge)이 가능하다.



Git 프로그램 설치

https://git-scm.com/  에서 프로그램을 다운로드 한다.



운영체제 환경에 맞게 자동으로 버전이 다운로드 된다.

받은 파일을 설치한다.









설치된 버전 확인

git --version


config 확인

git config --list



버전을 관리하고 싶은 폴더에서 git init 를 하면 초기화 준비가 된다.

default 로 만들어지는 가지가 master 이다.


Github에 계정이 있다면 등록한다.

git config --global user.name "사용자"
git config --global user.email "사용자 이메일"


git bash 실행
git config --global user.name "Json-Jeon"
git config --global user.email "jsk005@naver.com"


출처: https://link2me.tistory.com/1867?category=1144153 [소소한 일상 및 업무TIP 다루기]

빠져나오는 명령어는 exit 이다.

명령어 입력 등을 좀 더 편리하게 하려면 Visual Studio Code 에서 하는 것이 편하다.

'자료 구하기 > Git' 카테고리의 다른 글

소스트리 설치  (0) 2021.02.18
Git 기본 명령어 및 GitHub에 업로드  (0) 2020.08.24
블로그 이미지

Link2Me

,
728x90

class OuterClass{
  //중첩클래스
  class NestedClass
}

중첩클래스의 class 키워드 앞에 inner 키워드를 붙이면 내부클래스가 된다.
class OuterClass{
  //내부클래스
  inner class InnerClass
}

이 두 클래스에 대해서 공통점과 차이점을 간단히 요약해보면 다음과 같다.
공통점 : 클래스 내부에 다른 클래스로 정의된다.
외형적 차이점 : inner 키워드를 쓰면 내부클래스, 안쓰면 중첩클래스이다.
기능적 차이점 : 중첩클래스는 OuterClass의 참조를 가지지 않지만 내부클래스는 OuterClass의 인스턴스를 참조를 가진다.
중첩클래스는 외형적으로는 OuterClass 소속인 것 같지만 사실은 연관성이 거의 없다.


class OuterClass {
    val outerValue = 10
    val a = "Outside Nested class."

    inner class Inner {
        private val innerValue = 20
        fun callMe() = a // OutClass 의 변수 할당 가능
        fun printItems() {
            println("inner: $innerValue, outer: $outerValue")
        }
    }

    fun printItems() {
        val inner = Inner() // 객체 생성
        inner.printItems()
    }
}

fun main(args: Array<String>) {
    val outer = OuterClass() // 객체 생성
    outer.printItems()

    println("Using outer object: ${outer.Inner().callMe()}")

    val inner = OuterClass().Inner()
    println("Using inner object: ${inner.callMe()}")
}
 


https://www.bsidesoft.com/8218 에 더 많은 내용이 있으니 참조하면 도움된다.

블로그 이미지

Link2Me

,
728x90

자바에서는 A 클래스 안에 B 클래스를 정의하면 B 클래스는 자동으로 내부 클래스가 되었다.
하지만 코틀린에서는 반대다.
한 클래스안에 다른 클래스를 정의하면 기본적으로는 중첩 클래스가 되고,
내부 클래스로 만들고 싶다면 inner 키워드로 클래스를 선언해야 한다.
내부 클래스는 기본적으로 외부 클래스를 참조하게 되지만 중첩 클래스는 그렇지 않다.


class Outer {
    val a = "Outside Nested class."

    class Nested {
        // Outer Class 변수에 접근할 수 없다.
        val b = "Inside Nested class."
        fun callMe() = "Function call from inside Nested class."
    }
}

fun main(args: Array<String>) {
    // accessing member of Nested class
    println(Outer.Nested().b) // 자바의 static 중첩 클래스와 동일하다.

    // creating object of Nested class
    val nested = Outer.Nested()
    println(nested.callMe())
}
 




'안드로이드 > Kotlin 문법' 카테고리의 다른 글

[코틀린] ArrayList, mutableListOf  (0) 2021.06.14
[코틀린] Inner Class  (0) 2020.08.21
코틀린 클래스  (0) 2020.05.06
코틀린 null 안전과 예외  (0) 2020.05.05
코틀린 object  (0) 2020.01.19
블로그 이미지

Link2Me

,
728x90

날짜를 선택하여 입력하는 EditText 예제이다.


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="5dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="70dp"
        android:layout_height="30dp"
        android:layout_marginTop="5dp"
        android:text="운행일자"
        android:textSize="18sp"
        android:textStyle="bold"
        android:textColor="@color/colorBlack"/>

    <EditText
        android:id="@+id/et_drivingDate"
        android:layout_width="120dp"
        android:layout_height="30dp"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="20dp"
        android:background="#E3E8EA"
        android:gravity="center"
        android:focusable="false"
        android:inputType="date"/>

</LinearLayout> 


public class MainActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();
    Context mContext;

    //Declaring EditText
    private EditText et_drivingDate;
    String drivingDate; // 운행일자
    final Calendar myCalendar = Calendar.getInstance();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        initView();
    }

    private void updateLabel() {
        String myFormat = "yyyy-MM-dd"; //In which you need put here
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

        et_drivingDate.setText(sdf.format(myCalendar.getTime()));
    }

    private void initView() {
        //Initializing the views
        et_drivingDate = findViewById(R.id.et_drivingDate);
        DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                updateLabel();
            }

        };
        et_drivingDate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new DatePickerDialog(MainActivity.this, date, myCalendar
                        .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                        myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });

    }
}


'안드로이드 > Layout' 카테고리의 다른 글

LinearLayout 동적 생성  (0) 2020.10.01
SMS authentication with OTP Layout Example  (0) 2020.09.14
Floating Action Button  (0) 2020.07.11
CardView Layout 예제  (0) 2020.04.12
Meterial Design 로그인 Layout 예제  (0) 2020.03.21
블로그 이미지

Link2Me

,
728x90

파이썬은 변수 선언 키워드가 없다.

 

LIST : 복수개의 값을 담을 수 있는 데이터의 구조

리스트에서 원소를 삽입, 제거, 정렬할 수 있다.(mutable)

 

리스트 초기화

  • [] # 빈리스트
  • list() 함수로 생성
  • str.split()함수로 생성
# 문자열은 immutable
= 'hello, world.'
# a[0] = 'J'  # TypeError: 'str' object does not support item assignment
print(a)
 
= a.replace('h''J')
print(b)


['a','b']
['a',2] # 다른자료형을함께

 

[1,2,3] + [4,5,6]

결과는 [1,2,3,4,5,6]

 

a = [1, 2, 3]

a.append(4) # 리스트 마지막 원소 뒤에 추가한다.

print(a)

 

a.insert(1,7) # def insert(index,object)

- 리스트의 원하는 위치에 추가 가능

- 앞에 인덱스, 뒤에 아이템을 명시

= [123]
a.append(4)
print(a)  # [1, 2, 3, 4]
 
a.insert(1,7)  # def insert(index, object)
print(a)  # [1, 7, 2, 3, 4]
 
a[0= 100
print(a)  # [100, 7, 2, 3, 4]
 
# slicing
= [123456789]
print(a[4:7]) # [5, 6, 7]  # 뒤 index 숫자는 포함하지 않음.
print(a[:7]) # [1, 2, 3, 4, 5, 6, 7]
print(a[3:]) # [4, 5, 6, 7, 8, 9]
print(a[1:7:2]) # [2, 4, 6]  # 마지막 2 는 step 2

 

subway = ["유재석""홍길동""강호동"]
print(subway.index("강호동"))
print(subway.index("홍길동"))
print(subway.index("유재석"))
subway.append("강감찬"# 리스트 마지막 원소 뒤에 추가한다.
print(subway)  # ['유재석', '홍길동', '강호동', '강감찬']
 
# 1번째에 키워넣기 insert(위치, 값)
subway.insert(1,"이순신")
print(subway)  # ['유재석', '이순신', '홍길동', '강호동', '강감찬']

 

여러개의 요소를 추가하고 싶을 때는 extend 함수를 사용한다.

def extend(iterable)

a.extend([5,6,7])

 

= [1,2,3,4,5]
= [6,7,8,9,10]
 
a.append(b)
print(a) # [1, 2, 3, 4, 5, [6, 7, 8, 9, 10]]
 
# 리스트 합치기
# 방법 1
a.extend(b)
print(a)  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 방법 2
+= b
print(a) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 

 

index()

- 찾고자 하는 값의 인텍스를 반환

 

in 키워드

- 리스트 내에 해당 값이 존재하는 지 확인

- value in [list]

- True, False 중 한가지로 반환

# list 는 mutable(가변), tuple은 immutable(불변)
# list 는 대괄호, tuple 은 소괄호 사용
= [4231]
= ["hello""hi"579]
 
x[3= 10  # list는 값을 변경할 수 있지만, tuple은 값 변경 불가
print(x)  # [4, 2, 3, 10]
 
print(x + y)
 
= sum(x) # 리스트를 합한 값을 반환.
print(z)  # 4 + 2 + 3 + 10 = 19
 
# index : 찾고자 하는 값의 인덱스를 반환
print(x.index(3))  # 2
 
for n in x:
  print(n)
 
print("hello" in y) # hello 가 y 에 있어?
 
if "hello" in y:
  print("hello 가 있어요.")

 

리스트 정렬

리스트 정렬(list.sort()) : 숫자는 오름차순, 문자열은 사전순

- 같은 자료형만 정렬 가능

- 리스트 내부 다른 자료형은 사용 불가

# 순서대로 정렬하기
num_list = [5,2,3,4,1]
num_list.sort()
print(num_list)  # [1, 2, 3, 4, 5]
 
# 순서 역순 정렬하기
num_list.reverse()
print(num_list)  # [5, 4, 3, 2, 1]
 

 

sort() : list 자체를 내부적으로 정렬

sorted() : list의 정렬된 복사본을 반환

# list 는 mutable(가변), tuple은 immutable(불변)
= [91071912202187]
# a.sort(reverse=True)
print(a)  # [21, 20, 19, 10, 9, 8, 7, 7, 2, 1]
 
= sorted(a)
print(a) # [9, 10, 7, 19, 1, 2, 20, 21, 8, 7]
print(b) # [1, 2, 7, 7, 8, 9, 10, 19, 20, 21]

 

리스트 요소 제거

- 값으로 항목 제거

  1. remove() 함수

- 인덱스로 제거

  1. del 연산자

  2. pop() 함수 : 지우고자 하는 아이템을 반환 후, 삭제

 

# remove 함수
= [123345]
a.remove(3)
print(a)  # [1, 2, 3, 4, 5]
# 동일한 값이 있을 경우 앞에 있는 값을 제거한다.
 
a.remove(7# ValueError: list.remove(x): x not in list
print(a)
 

 

list.pop(index)

- 인덱스 해당 요소를 제거한다.

- 인덱스를 지정하지 않으면 자동으로 -1을 호출하여 마지막 요소를 제거한다.

# pop 함수
= ["유재석""홍길동""강호동"]
 
# list.pop(i) : 인덱스 i의 원소를 제거 후 그 원소를 반환
# 한 명씩 뒤에서 꺼내기
print(b.pop())
print(b.pop())
 
# 특정한 원소 꺼내기
print(b.pop(0))
 
= [12345]
a.pop()  # 지정하지 않으면 마지막 원소 제거
print(a)  # [1, 2, 3, 4]
 
= [12345]
= a.pop(2)
print(a)  # [1, 2, 4, 5]
print(d)  # 3

 

# seq.count(d) : 시퀀스 내부의 자료 d의 개수를 반환
my_seq = [2,2,2,4,4,6,7]
print(my_seq.count(2)) # 결과 : 3
 
# 숫자 1, 2, 2, 3, 3, 3이 담긴 리스트 my_list를 하나 선언해 봅시다.
# my_list 안의 숫자 3의 개수를 변수 var1에 넣어 봅시다.
# 일부 원소를 제거하여 my_list가 [1, 2, 3]이 되도록 해봅시다.
my_list = [122333]
var1 = my_list.count(3)
print(var1) # 3
my_list.pop()  # 마지막 원소 제거
my_list.pop()  # 마지막 원소 제거
my_list.pop(2# 3번째 원소 제거
print(my_list)

 

문자열 분리

str.split(c)

c를 기준으로 문자열을 쪼개서 리스트를 반환(괄호를 비울시 공백)

words = "python은 프로그래밍 배우기에 아주 좋은 언어입니다."
words_list = words.split()
print(words_list) # ['python은', '프로그래밍', '배우기에', '아주', '좋은', '언어입니다.']
 
time_str = "10:34:17"
time_str_list = time_str.split(':')
print(time_str_list) # ['10', '34', '17']
 

 

str.join(list)

str를 기준으로 리스트를 합쳐서 문자열을 반환(괄호를 비울시 공백)

= ['a''b''c''d''1''2''3']
print(a)
 
# 리스트를 문자열로 : join 이용
result1 = "".join(a)
print(result1)  # 결과 : abcd123
 
friend = ['Pat''Mat']
print('&'.join(friend))  # Pat&Mat

 

'파이썬 > Python 기초' 카테고리의 다른 글

[파이썬기초] Tuple(튜플)  (0) 2021.01.01
[파이썬 기초] dictionary  (0) 2021.01.01
[파이썬 기초] 반복문 for, while  (0) 2020.12.29
[파이썬 기초] 함수와 조건문  (0) 2020.12.29
파이썬 기초  (0) 2020.08.08
블로그 이미지

Link2Me

,
728x90

처음에는 인프런 사이트에 등재된 Python 무료 강좌를 듣고 파이썬의 개념이 이런 것인가 싶어 적었다.

6시간만 공부하면 파이썬 기초 개념을 이해한다는 동영상 강좌도 들어봤고,

혼자공부하는 파이썬(윤인성) 동영상 강의를 들으면서 개념 정리가 확실하게 되는 걸 느끼고 있다.

\n : 개행
\t : 탭
\\ : 문자
\' : 문자
\" : 문자
\r : 캐리지 리턴
\f : 폼 피드
\a : 벨 소리
\b : 백 스페이스
\000 : 널 문자
print(4**3) # n제곱
print(pow(4,3)) # n 제곱
print(13//7) # 몫
print(13%7) # 나머지
number = 13
number %= 7
print("나머지 result :",number)
number *= 3
print("곱하기 result :",number)
print(1 != 3) # True
print(not(1 != 3)) # False
print(5>4>7) # False
print(round(3.14)) # 반올림
print(round(4.98)) # 반올림

from math import *
print(sqrt(16)) # 제곱근
print(floor(4.98)) # 내림
print(ceil(3.14)) # 올림

from random import *
print(random()) # 0.0 ~ 1.0 미만의 임의의 값 생성
print(random()*10) # 0.0 ~ 10.0 미만의 임의의 값 생성
print(int(random()*45)+1) # 1 ~ 45이하의 임의의 값 생성

print("로또번호 생성")
print(randint(1,45)) # 1~45 이하의 임의의 값 생성
print(randint(1,45)) # 1~45 이하의 임의의 값 생성
print(randint(1,45)) # 1~45 이하의 임의의 값 생성
print(randint(1,45)) # 1~45 이하의 임의의 값 생성
print(randint(1,45)) # 1~45 이하의 임의의 값 생성
print(randint(1,45)) # 1~45 이하의 임의의 값 생성

문자열

jumin = "970414-2464777"
print("성별 : "+ jumin[7])
print("년 : " + jumin[0:2]) # 0 ~ 2 직전까지 가져오기
print("월 : " + jumin[2:4]) # 2 ~ 4 직전까지 가져오기
print("일 : " + jumin[4:6]) # 4 ~ 6 직전까지 가져오기
print("생년월일 : " + jumin[:6]) # 처음부터 ~ 6 직전까지 가져오기
print("뒷7자리 : " + jumin[7:]) # 7부터 마지막까지 가져오기
print("뒷7자리 : " + jumin[-7:]) # 맨 마지막은 -1이고 -7부터 가져오기
print("안녕하세요"[0:2])  # 출력결과 : 안녕
print("안녕하세요"[:2])  # 출력결과 : 안녕
print("안녕하세요"[2:]) # 출력결과 : 하세요.

x = "qwertyui"
a = int(len(x)/2)
commna = ","
print(x[:a] + commna + x[a:])

 

문자열 포멧

# format 사용

print("나는 {}색과 {}색을 좋아해요.".format("파란","초록")

print("나는 {0}색과 {1}색을 좋아해요.".format("파란","초록")) 

print("나는 {1}색과 {0}색을 좋아해요.".format("파란","초록"))

print("나는 {var1}색과 {var2}색을 좋아해요.".format(var1="파란",var2="초록")) 

# 문자열 포멧
print("나는 %d살입니다." % 25)
print("나는 %s을 좋아합니다." % "파이썬")
print("나는 %s색과 %s색을 좋아해요." % ("파란","초록"))
print("나는 {}색과 {}색을 좋아해요.".format("파란","초록")) 
print("나는 {age}살이며, {color}색을 좋아해요.".format(age=25, color="파란"))

age = 20
color="빨간"
print(f"나는 {age}살이며, {color}색을 좋아해요.")

# \n : 문장내 줄바꿈
print("백문이 불여일견\n백견이 불여일타")
# 문장내 따옴표 처리 \"
print("저는 \"초보코딩\" 입니다.")
# \\ : 문장내에서 하나의 \
print("C:\\Users\\jsk005\\PythonWorkspace")
# \b : 백스페이스
 

url ="https://google.com"
my_str = url.replace("https://","")
print(my_str)
my_str = my_str[:my_str.index(".")]
print(my_str)
password = my_str[:3] + str(len(my_str)) + str(my_str.count("e")) + "!#"
print("{}의 비밀번호는 {} 입니다.".format(url,password))

연산자

// 몫

% 나머지

** 제곱연산자

# 3472를 17로 나누었을 때 몫과 나머지 구하기
print("몫 :", 3472//17)
print("나머지 :", 3472%17)

# 741 과 같이 input으로 입력받은 맨 첫글자를 출력하는 코드
a = input("숫자를 입력하세요 : ")
b = len(a)
c = int(a)//(10**(b-1))
print(c)

# 자료형을 확인해보자
print(type(a))
print(type(b))

# 만약 a = int(input("숫자를 입력하세요 : ")) 로 하면 어떻게 될까?
# object of type 'int' has no len() 로 b=len(a)를 할 수 없다고 나온다.
# 정수형의 문자열 길이를 알고자 한다면 len(str(a)) 를 해야 한다.
a = int(input("숫자를 입력하세요 : "))
b = len(str(a))
c = a//(10**(b-1))
print(c)

문자열 교체

# 문자열 교체 코드
a = int(input("문자열 입력 >> "))
b = int(input("문자열 입력 >> "))

print(a, b)
a, b = b, a # 튜플 기능 이용한 swap
print(a, b)

문자열 변환

string = "hello, my world."
# 함수들은 대부분 자기 자신을 변경하지 않는다.
string.upper()
print(string) # 결과 : hello, my world. 
print(string.upper()) # 결과 : HELLO, MY WORLD.

 

문자열은 불변(immutable)이라 원소를 변경할 수 없다.

a = 'hello, world'

a[0] = 'J'

print(a)

'파이썬 > Python 기초' 카테고리의 다른 글

[파이썬기초] Tuple(튜플)  (0) 2021.01.01
[파이썬 기초] dictionary  (0) 2021.01.01
[파이썬 기초] 반복문 for, while  (0) 2020.12.29
[파이썬 기초] 함수와 조건문  (0) 2020.12.29
[파이썬기초] List  (0) 2020.08.10
블로그 이미지

Link2Me

,
728x90

LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
// Set the layout manager to your recyclerview
recyclerView.setLayoutManager(mLayoutManager);


출처 : https://freakycoder.com/android-notes-46-how-to-reverse-recyclerview-by-adding-items-f32db1e36c51

블로그 이미지

Link2Me

,
728x90

private val groupList: Unit
    private get() {
        remoteService = RetrofitAPI.getClient().create(RemoteService::class.java)
        val groupResultCall = remoteService?.getGroupList(Value.encrypt(Value.URLkey()))
        groupResultCall?.enqueue(object : Callback<GroupResult> {
            override fun onResponse(call: Call<GroupResult>, response: Response<GroupResult>) {
                if (response.body()!!.status.contains("success")) {
                    groupItem.clear()
                    val groupData = response.body()!!.message
                    for (item in groupData) {
                        groupItem.add(item)
                    }
                    Log.d("TAG", "Number of groupItem :" + groupItem.size)
                }
            }

            override fun onFailure(call: Call<GroupResult>,t: Throwable) {
            }
        })
    }
 


Java로 작성한 코드를 코틀린으로 변환하여 테스트하고 적어둔다.


override fun onClick(view: View) {
    when (view.id) {
        R.id.btn_drawer -> drawer_layout.openDrawer(GravityCompat.START)
        R.id.btn_group -> {
            // 팝업 메뉴 나오게 하는 방법
            Log.d("TAG", "popupMenu of groupItem :" + groupItem.size)
            val popupMenu = PopupMenu(this, view)
            val menu = popupMenu.menu
            var i = 0
            while (i < groupItem.size) {
                menu.add(Menu.NONE,i,Menu.NONE,groupItem[i].name)
                i++
            }
            popupMenu.setOnMenuItemClickListener { item: MenuItem ->
                val i = item.itemId
                freeActiveMarkers()
                getAddrData(item.title.toString())
                LocationAt(groupItem[i].latitude.toDouble(),groupItem[i].longitude.toDouble())
                Toast.makeText(context,item.title.toString() + " 선택했습니다",Toast.LENGTH_SHORT).show()
                true
            }
            popupMenu.show()
        }
    }
}


private fun LocationAt(latitude: Double, longitude: Double) {
    val coord = LatLng(latitude, longitude)
    mNaverMap!!.moveCamera(CameraUpdate.scrollTo(coord).animate(CameraAnimation.Easing, 300))
}


PHP 서버코드

<?php
error_reporting(0);
//error_reporting(E_ALL);
//ini_set("display_errors", 1);
header("Cache-Control: no-cache, must-revalidate");
header("Content-type: application/json; charset=utf-8");

// 파일을 직접 실행하는 비정상적 동작을 방지 하기 위한 목적
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST"){
    @extract($_POST);
    require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
    require_once $g['path_config'].'config.php';
    require_once $g['path_class'].'dbconnect.php';
    require_once $g['path_class'].'loginClass.php';
    $c = new LoginClass;

    //키워드 확인
    if(!isset($_POST['keyword'])){
        $result = array(
            'status' => "fail",
            'message' => "no keyword"
        );
        echo json_encode($result);
        exit;
    }

    $keyword=$c->AES_Decode($_POST['keyword']);
    //키워드 일치 확인
    if(strcmp($keyword,$mykey)<>0){
        $result = array(
            'status' => "keyfail",
            'message' => "서버와 단말의 KEY가 일치하지 않습니다."
        );
        echo json_encode($result);
        exit;
    }

    // 배열 저장
    $R = array();
    array_push($R,array("name"=>"전체","latitude"=>"37.358752","longitude"=>"127.1149243"));
    $map_sql = "select name,latitude,longitude from mapTree";
    $map_result = mysqli_query($db,$map_sql);
    while($row = mysqli_fetch_row($map_result)) {
        array_push($R,array("name"=>$row[0],"latitude"=>$row[1],"longitude"=>$row[2]));
    }

    $status = "success";
    $message = $R;
   
    $result = array(
        'status' => $status,
        'message' => $message
    );
    echo json_encode($result);
}
?> 


블로그 이미지

Link2Me

,