2017년 12월 8일 금요일

2017년 11월 23일 목요일

visual studio 프로젝트 복사 붙여넣기후 모든 Dll 오류날때

프로젝트 통채로 복사 붙여넣기시 모든 Dll이 오류날때가 있다.

짐작으로 Nuget Package의 영향인것 같다.

이럴경우

1. 모든 Nuget Package를 삭제하고 직접 프로젝트 폴더에 Dll을 넣어서 직접 참조한다.

2. 1으로도 안될경우

 - project.csproj  을 편집기로 연다.

-  nuget 으로 검색후 관련 항목들을 다 삭제한다.


3. 2번까지 하면 왠만하면 다 해결된다. 

c# Method Parameter Class and Struct Different

https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/classes-and-structs/how-to-know-the-difference-passing-a-struct-and-passing-a-class-to-a-method

2017년 11월 21일 화요일

wpf 초기화 후 컴포넌트들 ActualWith 가 0 인 문제 해결

https://stackoverflow.com/questions/1695101/why-are-actualwidth-and-actualheight-0-0-in-this-case

아니면 window loaded  이벤트를 활용한다.

처음에 생성자시 모든 초기 길이 정해지지 않은 컴포넌트들은 길이가 0으로 된다.

그후  Loaded 이벤트 발생후 각자의 길이가 정해진다.

지속적으로 윈도우 사이드 변경때마다 지정하려면 sizechanged 이벤트떄 각각의 길이를 정해주면 된다.

아니면 viewport를 사용한다.

2017년 11월 1일 수요일

그동안 대충 정리

1. 텐서 플로우 모델 저장 및 복원
2. 텐서 플로우 기본적인 사용법
3. CNTK C# API 기본적인 사용법 - 미완
4. 라이브차트 WPF 사용법 (깃에 예제 정리)
5. 이미지 그라데이션 제거 방법 개발

6. FRP입문중
7. Paket 사용법 익힐 예정

빨리 블로그 만들어서 지식 저장소로 활용하자 !!

2017년 9월 25일 월요일

[wpf] border


     
   


이렇게 쓰면 된다. border안에 원하는 컨트롤 사용하면 그 컨트롤 밖에 경계가 쳐진다


2017년 9월 14일 목요일

[C#] Fast array to bitmap

public Bitmap CopyDataToBitmap( byte [ ] data , int w, int h)
{
//Here create the Bitmap to the know height, width and format
Bitmap bmp = new Bitmap( w, h, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

//Create a BitmapData and Lock all pixels to be written
BitmapData bmpData = bmp.LockBits(
  new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
  ImageLockMode.WriteOnly, bmp.PixelFormat);

//Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy( data , 0 , bmpData.Scan0 , data.Length );


//Unlock the pixels
bmp.UnlockBits( bmpData );


//Return the bitmap
return bmp;
}

2017년 9월 10일 일요일

funtor applicative monad different

*Main> [(\n -> [1..n])] <*> [1..5]
[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
*Main> [1..5] >>= \n -> [1..n]
[1,1,2,1,2,3,1,2,3,4,1,2,3,4,5]
*Main> [(\n -> [1..n])] <*> [1..5]
[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
*Main> fmap (\n -> [1..n]) [1..5]
[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
*Main> fmap [(\n -> [1..n])] [1..5]

:29:6: error:
    • Couldn't match expected type ‘Integer -> b’
                  with actual type ‘[Integer -> [Integer]]’
    • In the first argument of ‘fmap’, namely ‘[(\ n -> [1 .. n])]’
      In the expression: fmap [(\ n -> [1 .. n])] [1 .. 5]
      In an equation for ‘it’: it = fmap [(\ n -> [1 .. n])] [1 .. 5]
    • Relevant bindings include it :: [b] (bound at :29:1)
*Main>



1. Functor 는 [ 함수 ] 에서 함수를 꺼내 적용하는게 불가능
2. Applicative 는 [함수 ] 에서 함수를 꺼내 , 목표 리스트에 각각 적용후 다시 리스트 [ ] 로 감싼다.
3.Monad 는 함수 바인드를 하는데 결과는 같은 타입인 [ a ] 로 나오게 바뀐다.


book

Python Machine Learning by Sebastian Raschka (recommended)
-Building Machine Learning Systems with Python by by Luis Pedro Coelho and Willi Richert (nice to have for additional perspective)

2017년 9월 1일 금요일

[haskell] foldr foldl

foldr 이란?

foldr :: (a → b → b) → b → [a] → b
foldr [] = v
foldr f v (x:xs)
= f x ( foldr v xs )
f (x1 , ( f ( x2 , f ( x3 , [] )) )

EX>
foldr f v (x1:x1s)
= f x1 ( foldr v x1s )
= f x1 ( foldr v (x2:x2s) )
= f x1 ( f x2 ( foldr v x2s ))

foldl 이란?

foldl :: (a → a → a) → [a]→ a
foldl f v ( x : xs )
= foldl f f(v,x) xs
f ( f ( f ( v , x1) , x2 ) x3)

EX>
foldl f v ( x1 : x1s )
= foldl f f(v,x1) (x2,x2s) 
= foldl f f ( f(v,x1)  , x2  )  x2s

v 는 가장 처음에 f에 첫번재 파라미터로 들어가는 수

2017년 8월 28일 월요일

[C#] fastest byte[] to Hex string array

 public static class IOExt
    {
        private static readonly uint[] _lookup32Unsafe = CreateLookup32Unsafe();

        private static unsafe readonly uint* _lookup32UnsafeP = (uint*)GCHandle.Alloc(_lookup32Unsafe,GCHandleType.Pinned).AddrOfPinnedObject();

        private static uint [ ] CreateLookup32Unsafe()
        {
            var result = new uint[256];
            for ( int i = 0 ; i < 256 ; i++ )
            {
                string s=i.ToString("X2");
                if ( BitConverter.IsLittleEndian )
                    result [ i ] = ( ( uint )s [ 0 ] ) + ( ( uint )s [ 1 ] << 16 );
                else
                    result [ i ] = ( ( uint )s [ 1 ] ) + ( ( uint )s [ 0 ] << 16 );
            }
            return result;
        }

        public static string ByteArrayToHexViaLookup32Unsafe( byte [ ] bytes )
        {
            unsafe
            {
                var lookupP = _lookup32UnsafeP;
                var result = new char[bytes.Length * 2];
                fixed ( byte* bytesP = bytes )
                fixed ( char* resultP = result )
                {
                    uint* resultP2 = (uint*)resultP;
                    for ( int i = 0 ; i < bytes.Length ; i++ )
                    {
                        resultP2 [ i ] = lookupP [ bytesP [ i ] ];
                    }
                }
                return new string( result );
            }
        }

    }
https://stackoverflow.com/a/24343727/6127030

[C#] IO Path 관련 명령어 - 프로그램 자체 경로 가져올때


  1. Application.StartupPathand 7. System.IO.Path.GetDirectoryName(Application.ExecutablePath) - Is only going to work for Windows Forms application
  2. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location)
    Is going to give you something like: "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Temporary ASP.NET Files\\legal-services\\e84f415e\\96c98009\\assembly\\dl3\\42aaba80\\bcf9fd83_4b63d101" which is where the page that you are running is.
  3. AppDomain.CurrentDomain.BaseDirectory for web application could be useful and will return something like "C:\\hg\\Services\\Services\\Services.Website\\" which is base directory and is quite useful.
  4. System.IO.Directory.GetCurrentDirectory() and 5. Environment.CurrentDirectory
will get you location of where the process got fired from - so for web app running in debug mode from Visual Studio something like "C:\\Program Files (x86)\\IIS Express"
  1. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
will get you location where .dll that is running the code is, for web app that could be "file:\\C:\\hg\\Services\\Services\\Services.Website\\bin"
Now in case of for example console app points 2-6 will be directory where .exe file is.
Hope this saves you some time.




 AppDomain.CurrentDomain.BaseDirectory  이거써라

2017년 8월 24일 목요일

[windows]c드라이브 권한 제거

http://blog.daum.net/khkim6001/649
c드라이브 권한 제거


[Haskell] Install

-- haskell and cobal install --

My Enviroment is  windows10 64bit and i just install full version haskell installer from https://www.haskell.org/platform/

and i down load cobal 2.0.0.0 from https://hackage.haskell.org/package/cabal-install

and put this cobal.exe in  

C:\Program Files\Haskell Platform\8.0.2-a\bin
C:\Program Files\Haskell Platform\8.0.2-a\lib\extralibs\bin

both.

and add enviroment path
C:\Program Files\Haskell Platform\8.0.2-a\bin
C:\Program Files\Haskell Platform\8.0.2-a\lib\extralibs\bin

After all this , when i opened cmd and typed "calbal --version"

-cabal update
cabal install ghc-mod stylish-haskell
or
cabal update 
cabal install alex
cabal install happy
cabal install ghc-mod hlint stylish-haskell


-- install atom
  • language-haskell : 문법 강조, 자동 들여쓰기, Snippets
  • haskell-ghc-mod : 형(type) 검사
  • ide-haskell : 에러/경고/Lints, type/info 보여주기, Prettify
  • autocomplete-haskell : 자동완성
apm install language-haskell haskell-ghc-mod ide-haskell-cabal ide-haskell autocomplete-haskell




2017년 8월 21일 월요일

Covariance vs Contravariance

covariance : converting from wider to narrower (넓은것에서 좁은것으로의 변환)

contravariance : converting from narrower to wider (좁은것에서 넓은것으로의 변환)


제네릭 인터페이스에서 형식 매개 변수가 다음 조건을 충족하는 경우 공변(covariant)으로 선언할 수 있습니다.
  • 형식 매개 변수는 인터페이스 메서드의 반환 형식으로만 사용되고 메서드 인수의 형식으로 사용되지 않습니다.

형식 매개 변수는 인터페이스 메서드에 대한 제네릭 제약 조건으로 사용되지 않습니다.


   interface INoraml { }
    class NormalSample : INoraml { }



    interface ICovariant { }
    class Sample : ICovariant { }

    interface IContravariant { }
    class SampleContra : IContravariant { }


    public class covriance
    {
      public void main()
        {
            ICovariant iobj = new Sample();
            ICovariant istr = new Sample();
            ICovariant iobst = new Sample();

            iobj = istr;
        }

        public void main2()
        {
            INoraml iobj = new NormalSample();
            INoraml istr = new NormalSample();
            INoraml iobst = new NormalSample();
            iobj = istr;
            istr = iobj;
        }

        public void main3()
        {
            IContravariant iobj = new SampleContra();
            IContravariant istr = new SampleContra();
            IContravariant iobst = new SampleContra();
            iobj = istr;
            istr = iobj;
        }

[bitplex] 분석

데이터 로드 

MxFile은 전역변수 

1. MxFile에 "ptnmap_depth1" 이 있는지 체크 
!Data.HasData(partition_name)
DataHeaders.Any(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));
//https://msdn.microsoft.com/ko-kr/library/system.stringcomparison(v=vs.110).aspx

2. "ptnmap_depth1" 이 있다면 

2-1 : MxDataHeader

2017년 8월 17일 목요일

[C#] enum name to string

public enum Teste { ab ,abg}
    class Program
    {
        static void Main( string [ ] args )
        {
            var strlist = Enum.GetNames(typeof(Teste)); // To String List
            var name = Teste.ab.ToString();  // single string

            Console.ReadLine();



        }
    }

[C#] Jagged Array Property

 int[][] temp = new int[2][] {
               new int[] {2,4},
               new int[] {3,2}
           };

            int[][] temp2 = new int[2][] {
               new int[] {20,2,4,5,4},
               new int[] {30,40}
           };

            temp [ 0 ] = temp2 [ 0 ];
            temp [ 0 ] = temp2 [ 0 ];



[C#] Get Files in Folder

 FolderBrowserDialog ofd = new FolderBrowserDialog();
            if ( ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK )
            {
                try
                {
                    FileNamesList = new List();
                    Directory.GetFiles( ofd.SelectedPath ).Where( x => System.IO.Path.GetExtension(x) == ".jpg").Select( x => x).ToList();
                   




                    var result = SingleProcessing( new Image( ofd.FileName ) , true);
                    mainimg.ImageSource = result.Item1.ToBitmapSource();
                }
                catch ( Exception )
                {
                }
            }

2017년 8월 14일 월요일

[c#] partial application

 public static Func>> tt => str1 => str2 => str3 => Console.WriteLine( str1 + str2 + str3 );


        static void Main( string [ ] args )
        {
            var temp1 = tt("2");
            var temp2 = tt("2")("3");

        }

2017년 7월 28일 금요일

[vision] filter

필터리스트
http://lodev.org/cgtutor/filtering.html

필터 설명
https://pdfs.semanticscholar.org/fcbf/0322f336f5d2470b623fe4115dd4efbea9b7.pdf

2017년 7월 27일 목요일

[Coding] 계획

1. 설정파일용 XML
2. 로깅
3. 모나드 => 스칼라 익히기 , corsera의 스칼라 강의 보기


최종적 목표 : 모나드를 활용한 어플리케이션 만들기

2017년 7월 18일 화요일

[ Camera ] Depth of Field 구하는법

http://www.slrclub.com/bbs/vx2.php?id=user_lecture&page=1&divpage=2&ss=on&keyword=%BD%C9%B5%B5&select_arrange=headnum&desc=asc&no=9061

http://blog.envision.co.kr/32

2017년 7월 13일 목요일

단식

https://m.blog.naver.com/PostView.nhn?blogId=cesmile&logNo=150172579019&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F

2017년 7월 10일 월요일

nuget package 등록하기

http://funnygangstar.tistory.com/entry/Nuget-Gallery-%EC%84%9C%EB%B2%84%EC%97%90-%EB%82%B4-%ED%8C%A8%ED%82%A4%EC%A7%80-%EB%93%B1%EB%A1%9D%ED%95%98%EA%B8%B0-Uploading-package-to-nugget-gallery



1 : https://dist.nuget.org/index.html 여기서 nuget.exe 다운후 폴더에 저장 "c:\nuget"

2. 환경변후 의 PATH 항목에 "c:\nuget" 추가

3. cmd 들가서 csproj 파일이 있는 곳으로 가서  nuget spec 으로 만듬

**약간 바뀜
https://docs.microsoft.com/en-us/nuget/create-packages/publish-a-package


폴더 구조는 다음의 링크를 참조


- 폴더 구조 설명
https://docs.microsoft.com/en-us/nuget/create-packages/supporting-multiple-target-frameworks

- 프레임웍 폴더명
https://docs.microsoft.com/en-us/nuget/reference/target-frameworks#supported-frameworks

[visual studio] project copy or move folder and dll missing probelm

https://stackoverflow.com/questions/33694515/visual-studio-2015-project-missing-all-references




Whenever you import a project to VS 2015 it modifies your .csproj. So, in order to fix it. Right click on .csproj and open it in notepad or any editor and delete the following

  
    This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
  
  


1 :  .csproj에 가서 아랫부분 보면 위의 내용이 있다 .이걸 삭제. 

2 : nuget 에 가서 느낌표가 떠있는 dll 들을 update 한다. 

[wpf] window and control resize automatically

https://stackoverflow.com/questions/19393774/how-to-make-all-controls-resize-accordingly-proportionally-when-window-is-maximi



        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SerialCommunication"
        mc:Ignorable="d"
        Title="MainWindow" Height="500" Width="525" Loaded="Window_Loaded">
   
       
           
               
               
           

           
           
               
                   
                       
                       
                   
                   
                   
               

           

       
   


2017년 7월 6일 목요일

[ACS Controller] Setting

이더캣 : 컨트롤러 기본 ip 는 10.0.0.100 으로 되어있다.

spiiplus mmi application studio

=> 에서 접속 세팅은

network type
10.0.0.100
포트 701

그전에 반듯이

이더캣이 꼽혀있는 랜카드 속성에서


TCP/IPv4 를 설정 해야 한다.

IP address : 10.0.0.101 < 100으로 하면 안됨. 그외는 됨
subnet mask : 255.255.255.0

으로 세팅

이후에는 된다.

2017년 7월 4일 화요일

2017.07.04 화 배운거

1. 케라스 에서

크로스 엔트로피 시 레이블을 one hot code 로, 최종 아웃풋은 클래스 갯수와 같게 한다.

그리고 마지막 activation 은 softmax로 한다.


2.파이썬

2-1 time 모듈 사용


import time


2-2 리스트에서

a = [ [1]*10 + [0] * 10  ] 은 [ [1] [1] ...] 이지만

b = [ [ 1, 0] * 10 ]은 [ 1, 0 ,1, 0, 1, 0 ...] 이 된다.
b = [ [1 , 0] for i in range(10) ] 이렇게 한다.



3. 디자인 패턴 데코레이터 패턴

장점 : 객체에 추가요소를 동적으로 추가 가능 (동적이란 처음에 정해진대로가 아닌, 나중에 데코레이터로 기능을 확장 할 수 있다는 말.  )

단점: 자잘한 클래스들이 매우 많이 추가 될 수도 있다.

룰:
1.데코레이터 클래스는 상속을 받고, 원래 클래스와 형식이 같아야 한다.





4. cnn, rnn

cnn에서 convolution layer의 아웃풋 shape 는?

original image shape = 128 x 128
filter size = 5
stride = 4

(128 - 5 ) / stride + 1

2017년 7월 3일 월요일

[keras[ keras Install 2017



-------- tensorflow ----

1. Cuda 8.0 / cudnn 5.1 설치 / c++ redistributable 설치

환경변수 설정
https://nitishmutha.github.io/tensorflow/2017/01/22/TensorFlow-with-gpu-for-windows.html




2. anaconda 4.2 나 4.4 설치

anadoncda 설치후
conda upgrade conda

가상 환경시
coonda create -n tf python=3.5.2
activate tf



3. pip install --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-0.12.1-cp35-cp35m-win_amd64.whl


GPU 버전 사용시 안된다.
시도했던 방법
텐서플로우는 1.3 버전
1. Python3.5.4 , 3.5.3 버전
2. cudnn5.1 / cuda 8 , cudnn5.1 / cuda 8.2
3. PathEXT에 .DLL 추가
4.

4. import 로 확인.




----- keras ------

conda install pandas matplotlib scikit-learn pip install keras

conda install mingw libpython


pip install keras



--- option --

conda install jupyter notebook

참고로 Keras 설치 전에 jupyter notebook 설치시 keras module을 import 하지 못하는 오류가 있다. 그래서 keras 설치후 jupyter notebook을 설치한다.

* Install Opencv3.2
conda install -c conda-forge opencv=3.2.0 

2017년 6월 29일 목요일

[C#] Task.WhenAll , WhenAny

Task.WhenAll(task1 , task2 )를 풀어서 쓰면 다음과 같다.

var exceptions = new List();
try{ task1.Wait() ;} catch ( AggregateException ex) { exceptions.Add(ex) ;}
try{ task2.Wait() ;} catch ( AggregateException ex) { exceptions.Add(ex) ;}
if(exceptions.Count > 0 ) throw new AggregateException (exceptions )

 따라서  WhenAll에 task1,task2를 넣기 전에 task1,task2는 미리 실행이 되어 있어야 한다.

[c#] Continuewith 추가 설명

Task task1 = Task.Run(() => Console.Write("task1"));
Task task2 = task1.ContinueWith(() => Console.Write("task1"));

1. task2 는 task1이 완료,실패,취소 되자마나 실행됨.

2. 2번째 라인에 진입하기전에 이미  task1이 완료된 상태라면 task2는 바로 실행된다.

2017년 6월 28일 수요일

[c#] Task Cancel token

public class CancelationTokenTest
    {
        public void testmethod2_multicancel()
        {
            var cancelsrc = new CancellationTokenSource();

            Task k1 = Task.Run( async ()=>
            {
                while(true)
                {
                    await Task.Delay(1200);
                    Console.WriteLine("k1 Done");
                    cancelsrc.Token.ThrowIfCancellationRequested(); // 여시서 토큰 상태 확인
                }
            }, cancelsrc.Token );

            Task k2 = Task.Run( async ()=>
            {
                while(true)
                {
                    await Task.Delay(1100);
                    Console.WriteLine("k2 Done");
                    cancelsrc.Token.ThrowIfCancellationRequested();
                }
            }, cancelsrc.Token );

            //await Task.Delay( 5000 );
            Thread.Sleep( 5000 );
            Console.WriteLine("cancel is started");
            cancelsrc.Cancel(); // 여기서 토큰 상태 취소로 바꿈.
            Console.WriteLine("Cancel done");
            Thread.Sleep( 5000 );
        }

        public void testmethod()
        {
            var cancelSource = new  CancellationTokenSource();
            Task foo = Foo(cancelSource.Token);
            Thread.Sleep( 3000 );
            Console.WriteLine( "cancel" );
            cancelSource.Cancel();
            Thread.Sleep( 3000 );
        }

        async Task Foo( CancellationToken cancellationToken )
        {
            int counter = 0;
            try
            {
                for ( int i = 0 ; i < 10 ; i++ )
                {
                    Console.WriteLine( i );
                    await Task.Delay( 500 );
                    cancellationToken.ThrowIfCancellationRequested();
                }
            }
            catch ( Exception ex )
            {
                Console.WriteLine( "Exception" );
                Console.WriteLine( counter );
                counter++;
            }
        }
    }

[C#] Task Tip

1. Task testtask = Task.Run( () => 3); 시 

int result =  testtask .Result;  는 테스크가 끝나서 결과를 반환할 때까지 대기를 탄다.

2. 테스크 끝난후 다른 테스크 실행하기 .

방법은 두가지

2-1 . GetAwaiter사용

 Task task = Task.Run( () => 3);

var awaiter = testtask.GetAwaiter(); // 이 awaiter는 테스크가 끝난건지 알수 있는 상태자체이다.

awaiteer.OnCompleted(  () =>
{
 Console.Writeline("Second Done")
 int result = awaiter.GetResult(); // testask의 결과값은 awaiter.GetResult() 이다.
Console.Writeline(result ) ;
});

** 선행 작업에서 예외 발생시 awaiter.GetResult()에서 그 예외가 그대로 발생.
** 비제네릭시 awaiter.GetResult()는 void반환. 오직 예외만 전달받는다는 기능이 있는거임.

** 선행 테스크와 같은 쓰레드에서 실행을 시키고 싶을때는

var awaiter = testask.ConfigureAwait(False).GetAwaiter();
이렇게 쓰면 된다. 이러면 단순히 선행 테스크와 코드가 합쳐지는 거라고 보면 된다.


2-2 ContinueWith

testtask.ContinueWith( firsttask =>
{
   int result = firsttask.Result;
  Console.Writeline(result ) ;
})

**여기서는 익셉션이 전파가 안된다. 따로 작성을 해줘야 한다. (선행 테스크에서 예외 발생시 그걸 따로 처리해서 전달을 하던지 해야 한다. )

** 같은 쓰레드에서 실행시키려고 하면 TaskCOntinueousOption 으로 ExecuteSynchronously를 지정해 줘야 한다.
Task t2= testtask.ContinueWith( firsttask =>
{
       int result = firsttask.Result;
       Console.Writeline(result ) ;
}
 , TaskContinuationOptions.ExecuteSynchronously);

3. Delay

Task.Delay(400).GetAwaiter().OnComplete( () => Console.Writeline(""));

Task.Delay(400).ContinueWith( ftask => Console.Writeline(""));

4. await async - TaskCompletionSource 로 작업의 연결, 완료 등을 관리해야 하면 힘들어서 이것들이 등장했다.

 var result = await 표현식;
문장들

은 원래는 다음과 같다.

var awaiter = 표현식.GetAwaiter();
awaiter.ConCompleted(()=>
{
  var result = awaiter.GetResult();
문장들
})

2017년 6월 27일 화요일

[C#] Collection Speed

Speed

Array  가장 빠름 

list queue stack 추가는 O(1) . list는 검색은 O(n) =>  Capacity로 용량을 미리 지정시 오버헤드 피할 수 있다.  queue stack 검색은 O(1)

linkedlist 추가는 O(1) , 검색은O(1)



http://flystone.tistory.com/154

http://game-secret.tistory.com/entry/C-%EA%B8%B0%EB%B3%B8%EA%B8%B0-II-%EC%9E%90%EB%A3%8C-%EA%B5%AC%EC%A1%B0%EC%9D%98-%EA%B8%B0%EB%B3%B8

[C#] WPFUserControl

1. UserControl  생성 : 반드시 네임을 지정한다. 아래는 네임 스페이스가 Menu이다.
             Name="user1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Menu"
             mc:Ignorable="d"
             Width="Auto" Height="Auto" d:DesignWidth="307.031" d:DesignHeight="395.312"
             >
   
       
           
           
       


       
           
           
       
       
           
       
       
   



2. 메인 폼에서 
xmlns:local="clr-namespace:Menu"


3.만약 네임스페이스가 다를경우 : Menu.UC 이다

             Name="Ucin1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Menu.UC"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
   
       
           
           
       

       
       


   

4. 메인폼에서 다음을 추가한다. : local2 
xmlns:local2="clr-namespace:Menu.UC"



[C#] Wpf Style 사용법

1.  styleDictionary.xmal 만듬.

--




--


2. App.xaml 에서 다음을 추가.
--

           
               
           

       
   

--

3. Form에서는 다음과 같이 사용
--




--






2017년 6월 26일 월요일

[WPF] Grid Line

http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&pageno=0&wid=739&rssMode=1&wtype=0

[c#] wpf startup wpf window

https://stackoverflow.com/questions/18138934/startup-code-in-a-windows-presentation-form-application


[C#] event Propagate

//In winform
// event is propagated c3 => c2 => c1 => winform

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EventPropagate
{
    public partial class Form1 : Form
   
{

        c1 cc1 = new c1();
        public Form1()
        {
            InitializeComponent();
            cc1.evtcc1 += new ff( test );
        }

        private void button1_Click( object sender , EventArgs e )
        {
            cc1.fire();
        }

        void test( int input )
        {
            label1.Text = input.ToString();
        }

    }


    public class c1
    {
        c2 cc2 = new c2();

        public void fire() { cc2.fire(); }

        public event ff evtcc1
        {
            add
            {
                Debug.WriteLine("c1");
                cc2.evtcc2 += value;
            }
            remove { }

        }

    }

    public class c2
    {
        c3 cc3 = new c3();
        public void fire() { cc3.fire(); }

        public event ff evtcc2
        {
            add
            {
                Debug.WriteLine("c2");
                cc3.evt += value;
            }
            remove { }

        }

    }

    public delegate void ff( int input );
    public class c3
    {
        public event ff evt ;

        public void fire()
        {
            Debug.WriteLine( "c3" );
            evt( 10000 );
        }
    }

}

2017년 6월 22일 목요일

[C#] casting

1. (int)3.4 =: InvalidCastException.
2.  as : null faster


[C#] Attribute

1. GetMethod()

-> 반환되는 메소드는 알파벳 순서로 나열이 된다.
-> bindingFlag 로 필터링해 메소드를 얻을 수 있다.

가져오는것은 다음과 같다.

https://msdn.microsoft.com/ko-kr/library/system.reflection.methodinfo(v=vs.110).aspx

2017년 6월 21일 수요일

2017년 6월 19일 월요일

[C#] Create Method Flow and Run Flow

        static void Main( string [ ] args )
        {
            Func temp = new Func(x =>
            {
                Console.WriteLine("temp done // input is : " +  x.ToString());
                return "g0";

            } );
            Func temp1 = new Func(x =>  {
                Console.WriteLine("temp1 done");
                return "g1";

            } );
            Func temp2 = new Func(x =>  {
                Console.WriteLine("temp2 done");
                return 4.5;

            } );
            List any = new List();
            any.Add( temp );
            any.Add( temp1 );
            any.Add( temp2 );

            Console.WriteLine( "anycount = " + any.Count.ToString() );
            var result = runme( 0, any , 10 );
            Console.WriteLine( result );
            Console.ReadLine();
        }


        static object runme( int idx , List list , object input  )
        {
            Console.WriteLine( idx );
            if ( idx == list.Count )
            {
                return input;
            }
            var output =  list [ idx ].DynamicInvoke( input );
            return runme( idx + 1 , list , output );
        }

2017년 6월 15일 목요일

[ Python] Tensorflow on windows10 and vision lib setting

Install Anadonda Installer 4.2.1

Install Tensorflow

Install keras (option)

Install opencv3

-- conda install -c https://conda.binstar.org/menpo opencv3





[TF] tensor to ndarray

https://stackoverflow.com/questions/34097281/how-can-i-convert-a-tensor-into-a-numpy-array-in-tensorflow


predict =   tf.argmax(model, 1)
result =    sess.run(predict , feed_dict = {
    X: x_data,
    Y: y_data,
    keep_prob: 1
    })

print(type(result)) << ndarray
print( 'Predict' , result)

2017년 6월 14일 수요일

[keras] image generater

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import cv2
import numpy as np


datagen = ImageDataGenerator(
        rotation_range=180,
        width_shift_range=0.5,
        height_shift_range=0.5,
        shear_range=0.3,
        zoom_range=0.6,
        horizontal_flip=True,
        vertical_flip = True,
        fill_mode = "wrap")


img = cv2.imread(r"C:\image data\test\defect 001.jpg", 0)

#tensorflow backend
x = img_to_array(img)  # this is a Numpy array with shape (150, 150 , 1)

x = x.reshape( (1,) + x.shape )  # this is a Numpy array with shape (1, 150, 150 , 1~3(ch) )
i = 0
for batch in datagen.flow_from_directory( directory= r"C:\image data\defect"
                                         , target_size = (64,64)
                                         , color_mode = "grayscale"
                                         , batch_size=1
                                         , shuffle = True
                                         , save_to_dir=r'C:\image data\test\result'
                                         , save_prefix='defect'
                                         ):
    i += 1
    if i > 50000:
        break






new keras install

I uninstalled Keras using 

pip uninstall keras

Then I executed the following commands.
1. C:\Users\tjhau>conda create -n keras_tensorflow python=3.5.2 anaconda=4.3
2. C:\Users\tjhau>activate keras_tensorflow
3. C:\Users\tjhau>conda install -c conda-forge tensorflow keras

I understand that keras will be available in a directory after I execute the command 
 C:\Users\tjhau>activate keras_tensorflow
Thanks for your help.

[python] keras image dim converting


keras image dim convert

tensorflow image <-> theano image

https://github.com/fchollet/keras/issues/3994

2017년 5월 31일 수요일

[c#] WPF Event on multi Layer Control

가령 같은 공간 안에 캔버스와 버튼이 같이 있으면, 밑에 쓴 쪽으로 이벤트가 발생하게 된다.

2017년 5월 17일 수요일

[c#] c#7 pattern Matching


object temp = 4;

if(temp is string t)
{}

=> 먼저 (string)temp = t 라고 캐스팅한다.

이게 성공시 if문장 안은 데이터 타입이 string  인  t 라는 변수가 로컬 변수가 된다.

실패시 if 문 안으로 안들어 간다.

2017년 5월 16일 화요일

[c#} Lazy

1. if문에서 ||(OR) 은 Lazy가 아닌데, &&(AND)는 Lazy이다. 즉

AND는 처음 문장실행후 판별=> 다음 문장

OR은 각 문장 다 실행 => 각각 판별

이렇게 동작한다.

따라서 And가 무조건 성능상 좋다.

[c#] Console,Wirte 에서 글씨들 간격 일정하게 .

Console.Write(numbers + "\t"); 하면

1   2   3   4  ...

이런식으로 출력이 된다.

[c#] Enumerator

IEnumerable  을 구현

IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

 IEnumerator를 상속받는  GetEnumerator 를 구현을 한다.

IEnumerator를 상속받는  GetEnumerator

는 currnet  라는 오브젝트를 리턴하고, 다음에 MoveNext실행 다시 current라는 오브젝틀르 리턴하는 식으로 구동하게 된다.

여기서 MoveNext는 bool을 리턴하고, True리턴시 currnet를 반환, Fals 리턴시 Dispose라는 메소드로 가서 더이상 반환을 안하게 된다.



public class FibonacciNumbers : IEnumerable
    {
        public IEnumerator GetEnumerator()
        {
            return new FibEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

       
    }

    public class FibEnumerator : IEnumerator
    {
        public FibEnumerator()
        {
            Reset();
        }

        public Int64 Current { get; private set; }

        Int64 Last { get; set; }

        object IEnumerator.Current { get { return Current; } }

        public void Dispose()
        { Console.WriteLine("Enumerator is over"); }

        public bool MoveNext()
        {
            if(Current == -1)
            {
                Current = 0;
            }
            else if(Current == 0)
            {
                Current = 1;
            }
            else if(Current == 5) return false;
            else
            {
                Int64 next = Current + Last;
                Last = Current;
                Current = next;
            }
            return true;
        }

        public void Reset()
        {
            Current = -1;
        }

2017년 3월 27일 월요일

[python] pandas subplot

fig, axes = plt.subplots(nrows=2, ncols=2)
fig.set_figheight(6)
fig.set_figwidth(8)
df[0].plot(ax=axes[0,0], style='r', label='Series'); axes[0,0].set_title(0)
df[1].plot(ax=axes[0,1]); axes[0,1].set_title(1)
df[2].plot(ax=axes[1,0]); axes[1,0].set_title(2)
df[3].plot(ax=axes[1,1]); axes[1,1].set_title(3)
fig.tight_layout()