Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
programming_tips_and_tricks [2016/01/14 05:39] – [경위도 변환] ledyxprogramming_tips_and_tricks [2021/02/07 03:15] (current) – external edit 127.0.0.1
Line 646: Line 646:
 == 정렬 알고리즘(Sort Algorithm) == == 정렬 알고리즘(Sort Algorithm) ==
 === 합병 정렬(Merge Sort) === === 합병 정렬(Merge Sort) ===
-[[Merge Sort | 합병 정렬(Merge Sort)]]+[[algorithm:Merge Sort | 합병 정렬(Merge Sort)]]
  
-=== 중복되지 않는 난수 생성 === 
-<sxh java> 
-//language : Java 
-//1~5 중복되지 않는 난수 발생 
-  
-int[] arr = new int[5]; 
-Random random = new Random(); 
-  
-for(int i=0 ; i<arr.length ; i++) { 
-    arr[i] = random.nextInt(arr.length)+1; 
-  
-    for(int j=0 ; j<i ; j++) { 
-        if(j!=i && arr[j] == arr[i]) 
-            i--; 
-    } 
-} 
-</sxh> 
  
 += Language & FrameWork =
  
 +== Java ==
  
-Java & C# =+=== 양력/음력 날짜 계산 === 
 + 
 +{{:calendarlib.zip|}} 
 + 
 +  * http://site.icu-project.org/download 
 +  * https://github.com/JodaOrg/joda-time/releases
  
-== Serialization을 이용한 Deep Copy == 
 <sxh java> <sxh java>
-/* Java */ +import org.joda.time.DateTime;
-@SuppressWarnings("unchecked"+
-public static <T> T deepClone(T obj) { +
- try { +
- ByteArrayOutputStream baos = new ByteArrayOutputStream(); +
- ObjectOutputStream oos = new ObjectOutputStream(baos); +
- oos.writeObject(obj);+
  
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())+import com.ibm.icu.util.ChineseCalendar
- ObjectInputStream ois = new ObjectInputStream(bais); + 
- return (T) ois.readObject(); +public class LunarDateTime 
- } catch (IOException e) +  
- return null+ private static int yearCorrectionValue = 2637
- } catch (ClassNotFoundException e) { + 
- return null;+ private LunarDateTime() {
  }  }
-} +  
-</sxh> + /** 
-https://github.com/xeyez/CSharp-PrototypePattern+  *  
 + * @return 오늘 음력날짜 
 + */ 
 + public static DateTime now() { 
 + ChineseCalendar cc = new ChineseCalendar(); 
 +  
 + int year = cc.get(ChineseCalendar.EXTENDED_YEAR) yearCorrectionValue; 
 + int monthOfYear = cc.get(ChineseCalendar.MONTH) + 1; 
 + int dayOfMonth = cc.get(ChineseCalendar.DAY_OF_MONTH); 
 +  
 + int[] hms = getNowHMS(); 
 + return new DateTime(year, monthOfYear, dayOfMonth, hms[0], hms[1], hms[2]); 
 +
 +  
 + public static DateTime solarToLunar(int solarYear, int solarMonthOfYear, int solarDayOfMonth) { 
 +  
 + int[] hms = getNowHMS(); 
 + DateTime dt = new DateTime(solarYear, solarMonthOfYear, solarDayOfMonth, hms[0], hms[1], hms[2]);
  
-<sxh csharp> + ChineseCalendar cc = new ChineseCalendar(); 
-/* C# */ + cc.setTimeInMillis(dt.getMillis()); 
-public static T DeepClone<T>(T obj+  
-{ + int year = cc.get(ChineseCalendar.EXTENDED_YEAR) - yearCorrectionValue; 
-        using (var ms new MemoryStream()) + int monthOfYear cc.get(ChineseCalendar.MONTH+ 1; 
-        + int dayOfMonth = cc.get(ChineseCalendar.DAY_OF_MONTH); 
-            var formatter = new BinaryFormatter(); +  
-            formatter.Serialize(msobj); + return new DateTime(year, monthOfYear, dayOfMonth, hms[0], hms[1], hms[2]); 
-            ms.Position = 0;+
 +  
 + public static DateTime lunar2Solar(int lunarYear, int lunarMonthOfYear, int lunarDayOfMonth) 
 + ChineseCalendar cc = new ChineseCalendar(); 
 + cc.set(ChineseCalendar.EXTENDED_YEARlunarYear + yearCorrectionValue); 
 +        cc.set(ChineseCalendar.MONTH, lunarMonthOfYear - 1); 
 +        cc.set(ChineseCalendar.DAY_OF_MONTH, lunarDayOfMonth);
  
-            return (T)formatter.Deserialize(ms); +        int[] hms = getNowHMS()
-        }+        cc.set(ChineseCalendar.HOUR_OF_DAY, hms[0]); 
 +        cc.set(ChineseCalendar.MINUTE, hms[0]); 
 +        cc.set(ChineseCalendar.SECOND, hms[0]); 
 +         
 +        return new DateTime(cc.getTimeInMillis()); 
 +
 +  
 + private static int[] getNowHMS() { 
 + DateTime now = DateTime.now(); 
 + return new int[] {now.getHourOfDay(), now.getMinuteOfHour(), now.getSecondOfMinute()}; 
 + }
 } }
 </sxh> </sxh>
-https://github.com/xeyez/Java-PrototypePattern 
  
  
-== C# - Lambda 이용하여 오름차순 정렬 == 
-<sxh csharp> 
-List<Point> points = new List<Points>(); 
-points.Add(new Point(11.0, 13.0)); 
-//... 
  
-points.Sort((Point point1, Point point2) => point1.Y.CompareTo(point2.Y)); 
-</sxh> 
  
  
-== 포인터와 구조체 기초 개념 예제 ==+ 
 + 
 +== C == 
 + 
 +=== 포인터와 구조체 기초 개념 예제 ===
 <sxh c ; collapse:true> <sxh c ; collapse:true>
 #include <stdio.h> #include <stdio.h>
Line 836: Line 848:
 </sxh> </sxh>
  
-C = +=== 동적 배열 할당 ===
- +
-== 동적 배열 할당 ==+
 <sxh c> <sxh c>
 //1차원 //1차원
Line 855: Line 865:
  
  
-= Android = +== Android =
-== Parcelable ==+=== Parcelable ===
   * Intent를 이용하여 **Reference Type**의 데이터를 넘길 때 사용.   * Intent를 이용하여 **Reference Type**의 데이터를 넘길 때 사용.
 http://arsviator.tistory.com/169 http://arsviator.tistory.com/169
  
-== Uri에서 실제 경로를 받아오는 Method == +=== Image 압축 및 실제 경로 얻기 === 
-  * SD Card에 저장된 그림 파일을 ImageView에 붙일 필요가 있을 때 사용.+
 <sxh java> <sxh java>
-private String getRealImagePath (Uri uri) {  +public class ImageUtil { 
- Cursor cursor = getContentResolver().query(uri, null, null, null, null); + 
- cursor.moveToFirst(); +    private static final int MAX_IMAGE_SIZE = 1280; 
- int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); +    private static final int MAX_IMAGE_LENGTH = 720 * 1280; 
- return cursor.getString(index);+ 
 +    /** 
 +     * Image Uri → Compressed byte array 
 +     * (반복문으로 인하여 별도의 Thread 필요) 
 +     * @param context 
 +     * @param uri 
 +     * @return 
 +     * @throws Exception 
 +     */ 
 +    public static byte[] getCompressedByteArray(Context context, Uri uri) throws Exception { 
 +        BitmapFactory.Options options = new BitmapFactory.Options(); 
 + 
 +        options.inSampleSize = calculateInSampleSize(options, 800, 800); 
 +        options.inJustDecodeBounds = false; 
 +        options.inPreferredConfig= Bitmap.Config.ARGB_8888; 
 + 
 +        BufferedInputStream bin = new BufferedInputStream(context.getContentResolver().openInputStream(uri)); 
 +        Bitmap bitmap = BitmapFactory.decodeStream(bin, null, options); 
 + 
 +        // resize (지정한 크기보다 작은 경우만) 
 +        if(bitmap.getWidth() * bitmap.getHeight() > MAX_IMAGE_SIZE * 2) 
 +            bitmap = resizeBitmap(bitmap, MAX_IMAGE_SIZE); 
 + 
 +        int compressQuality = 100; 
 +        int streamLength; 
 + 
 +        byte[] bitmapdata; 
 + 
 +        String realPath = getRealImagePath(context, uri); 
 +        String extension = realPath.substring(realPath.lastIndexOf('.') + 1); 
 +        Bitmap.CompressFormat format; 
 +        switch (extension.toLowerCase()) { 
 +            case "jpg"
 +            case "jpeg"
 +                format = Bitmap.CompressFormat.JPEG; 
 +                break; 
 + 
 +            case "png"
 +            case "gif"
 +                format = Bitmap.CompressFormat.PNG; 
 +                break; 
 + 
 +            case "webp"
 +                format = Bitmap.CompressFormat.WEBP; 
 +                break; 
 + 
 +            default: 
 +                throw new Exception("Unsupported format!"); 
 +        } 
 + 
 +        do { 
 +            ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
 +            bitmap.compress(format, compressQuality, baos); 
 +            bitmapdata = baos.toByteArray(); 
 +            streamLength = bitmapdata.length; 
 +            compressQuality -= 5; 
 +        } while (streamLength >= MAX_IMAGE_LENGTH); 
 + 
 +        Log.d("compressBitmap", "Quality: " + compressQuality); 
 +        Log.d("compressBitmap", "Size: " + streamLength/1024+" kb"); 
 + 
 +        return bitmapdata; 
 +    } 
 + 
 +    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 
 +        final int height = options.outHeight; 
 +        final int width = options.outWidth; 
 +        int inSampleSize = 1; 
 + 
 +        if (height > reqHeight || width > reqWidth) { 
 + 
 +            final int halfHeight = height / 2; 
 +            final int halfWidth = width / 2; 
 + 
 +            // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
 +            // height and width larger than the requested height and width. 
 +            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { 
 +                inSampleSize *= 2; 
 +            } 
 +        } 
 +        Log.d("inSampleSize", String.valueOf(inSampleSize)); 
 +        return inSampleSize; 
 +    } 
 + 
 +    private static Bitmap resizeBitmap(Bitmap bitmap, int maxSize) { 
 +        float ratio = Math.min((float) maxSize / bitmap.getWidth(), (float) maxSize / bitmap.getHeight()); 
 +        int width = Math.round(ratio * bitmap.getWidth()); 
 +        int height = Math.round(ratio * bitmap.getHeight()); 
 +        return Bitmap.createScaledBitmap(bitmap, width, height, false); 
 +    } 
 + 
 +    /** 
 +     * Uri를 이용해 실제 저장소 경로 얻기 
 +     * @param context 
 +     * @param uri 
 +     * @return 
 +     */ 
 +    public static String getRealImagePath(Context context, Uri uri) { 
 +        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); 
 +        cursor.moveToFirst(); 
 +        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
 +        return cursor.getString(index); 
 +    } 
 + 
 +    /** 
 +     * [0] : fileName 
 +     * [1] : extension 
 +     * @param filePath 
 +     * @return 
 +     */ 
 +    public static String[] getFileNameAndExtension(String filePath) { 
 +        return new String[] {filePath.substring(filePath.lastIndexOf(File.pathSeparator) + 1), filePath.substring(filePath.lastIndexOf('.') + 1)}; 
 +    }
 } }
 +</sxh>
 +
 +
 += Intellij - Git Bash 연동 =
 +
 +Tools -> Terminal
 +
 +<sxh bash>
 +"C:\Program Files\Git\bin\sh.exe" -login -i
 </sxh> </sxh>
programming_tips_and_tricks.1452749980.txt.gz · Last modified: 2021/02/07 03:15 (external edit)