2015年12月24日 星期四

[Project-web]Front end web final project

這是一堂網頁設計的期末專題
雖然老師進度緩慢,但是我從零到有,並偷懶從bootstrap開始學起,從中真的學到非常多的東西,像是html 相關標籤語言,利用css來達成美化和版面配置,最後一些滑動點擊事件處理利用jQuery,很開心完成自己從以前就想學習怎麼實作的想法,感謝自己有勇氣修這堂課.

This is my web design courses final project.
In this part we are going to show the front end part.Although teacher taught in a slow way, I learn how to use bootstrap by making my web!!
From zero to 100%.It's really a fantastic thing!!!!


2015年11月26日 星期四

[Android] EditText close the default pop-out keyboard 關閉鍵盤自動跳出

Method: 
在AndroidMainfest.xml中把windowSoftInputMode把屬性設成
adjustUnspecified|stateHidden

Go to Mainfest.xml choose your activity and type android:windowSoftInputMode="adjustUnspecified|stateHidden"

< activity android:name=" .Main " 
android:label="@string/app_name" 
android:windowSoftInputMode="adjustUnspecified|stateHidden" > 
< intent-filter> 
< action android:name="android.intent.action.MAIN" /> 
< category android:name="android.intent.category.LAUNCHER" /> 
< /intent-filter> 
< /activity>  

2015年11月17日 星期二

[OpenCV C++]Load Image 圖片開啟

cvLoadImage()

載入圖片的意思 IplImage* cvLoadImage("檔案名稱",參數); 參數的部份可以參考命名規則的說明,回傳的訊息是IplImage資料結構,它的參數分類有 #define CV_LOAD_IMAGE_UNCHANGED -1 原圖影像 #define CV_LOAD_IMAGE_GRAYSCALE 0 灰階 #define CV_LOAD_IMAGE_COLOR 1 彩色 #define CV_LOAD_IMAGE_ANYDEPTH 2 任何彩度 #define CV_LOAD_IMAGE_ANYCOLOR 4 任何彩色

cvNamedWindow()

cvNamedWindow("視窗名稱",參數);
而它的參數實質上只有一個
AUTOSIZE可以讓圖片便成原圖大小,也就是圖形維度不做調整,但是圖片太大很容易造成困擾
如果要微調就要用到cvResizeWindow()這個函式
但是,cvNamedWindow()不能設成1(CV_WINDOW_AUTOSIZE),務必將參數設為0或其他非1的數字.

#include < opencv2/core/core.hpp >
#include < opencv2/highgui/highgui.hpp >
#include < iostream >
using namespace cv;
using namespace std;
int main()
{
    IplImage *InImage;

 InImage = cvLoadImage("C:/Users/Public/Pictures/Sample Pictures/789.jpg",CV_LOAD_IMAGE_GRAYSCALE);
    
 CvSize Size1 = cvGetSize(InImage);

    //建立視窗(視窗名稱,參數)
 cvNamedWindow("InImage",CV_WINDOW_AUTOSIZE);
 
    //顯示影像(視窗名稱,影像檔案)
    cvShowImage("InImage",InImage);
  
    cvWaitKey(0); //按下任意按鍵可將圖片關閉
 cvReleaseImage(&InImage); //釋放來源影像佔用的記憶體
    cvDestroyWindow( "InImage" ); //銷毀視窗「src」
    return 0;

  
}

2015年10月29日 星期四

[Eclispe]加上自動提示(Intellisense)程式碼

When u build an new environment!!! Don't forget to set Eclipse Intellisense. it will help u a lot haha!!

打一打沒有提示字真得好難,這次來分享自動提示

Solution:
Windows -> Preferences -> Java -> Editor -> Content Assist
Auto activation triggers for Java keyin                    abcdefghijklmnopqrstuvwxyz(,


[Eclipse] console font size

Sometime i will forget how to resize my console font size in my eclipse!!

Solution
window -> preferences-> general -> appearance -> colors and fonts ->debug -> console font 


【Android】Redering Problems Missing Styles

After i update my Android Studio , my XML always show  Rendering Problems Missing Style
今天在升級版的Android Studio後,在建立新應用程式後,都會出現下列的問題畫面:


Solution:

【File】→【Invalidate Caches / Restart...】:

[Android] java.io.FileNotFoundException AND android.os.NetworkOnMainThreadException!!

1.Android 4.0 has a new Exception in NetWork part.So if you request it.
You will get a android.os.NetworkOnMainThreadException!!

Android4.0在網路的部份多了一個新的Exception,
叫做android.os.NetworkOnMainThreadException
意思就是說:網路的活動跑在主要執行緒上了,很貼心的告訴你,這樣子你的APP可能會因為網路的活動等待回應太久,而被系統強制關閉(收到ANR)。

Solution:(put it in main )
StrictMode
    .setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
    .detectDiskReads()  
    .detectDiskWrites()  
    .detectNetwork()   // or .detectAll() for all detectable problems  
    .penaltyLog()  
    .build());  



2.Android 4.0 hope developer use post to request ,But if will occur
Java.io.FileNotFoundException

4.0中設置httpCon.setDoOutput(true),将導致請求以post方式提交
然後就會出現 java.io.FileNotFoundException

Soluation:
Delete-->httpCon.setDoOutput(true);

2015年8月29日 星期六

[C++]VECTOR ALLOCATION

Basis

Define:vector<int> array;

Two dynamic vector +initialize  0:

vector<vector<int> > array;
array.resize(y, vector<int>(x, 0));

OR

vector<vector<int> > array(y, vector<int>(x, 0));
**
vector<vector<int> > array(y, vector<int>(x));//ALSO '0'


2015年7月26日 星期日

【Eclipse] 中文出現亂碼 gibberish in chinese character

有時候import project的時候,就會出現中文亂碼#%$#%一整個很困擾
Sometime i import a project the chinese character all become %$#$%# !!!!
IT'S VERY NOISY!!!!! 

 SOLVE METHOD
 Step 1. 「Window」->「Preferences」
 Step 2. 「General」->「Workspace」。
 Step 3. 「Text file encoding」 Change Default (MS950) ->「UTF-8」。
 Step 4. Press 「Apply」

[Android] 通知(Notification)

Take a note !! so next time if i use notification it will become faster :")) 
新(New):Notification.Builder來快速產生出來
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE );
Builder builder = new Notification.Builder(Update.this );
PendingIntent contentIndent = PendingIntent.getActivity(Update. this, 0, new Intent(Update.this , Update. class),PendingIntent. FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIndent)
       .setSmallIcon(R.drawable.icon) // 設置狀態列裡面的圖示          
       .setTicker("New Message") // 設置狀態列的顯示的資訊
       .setWhen(System. currentTimeMillis()) // 設置發生時間
       .setContentTitle( "I-Calories計算結果通知" )//設置通知清單裡的標題
       .setContentText("共消耗"+ca); // 設置內容
							  
Notification notification = builder.getNotification();
notificationManager.notify(1, notification);
設定預設提示音(notification.defaults to set default alarm ring)
notification.defaults |= Notification.DEFAULT_SOUND;//預設鈴聲
相關連結(good learning website) 更詳細可以點及這個很棒的網站作更深入的學習 http://magiclen.org/android-notifications/ 
http://www.codedata.com.tw/mobile/android-tutorial-the-5th-class-2-notificationhttp://givemepass.blogspot.tw/2011/11/notification.html 
http://blog.maxkit.com.tw/2014/03/android-notification.html

[Android] Vibrate 振動實作

Sometime we need to let the phone vibrate when receive a message or something happen
我們現在來進行實做 "振動" 這項功能
  Vibrator myVibrator = (Vibrator) getApplication().getSystemService(Service.VIBRATOR_SERVICE);
  myVibrator.vibrate(1000);//millisecond

Don't forget to add in your AndroidManifest.xml!!!!!
<uses-permission android:name="android.permission.VIBRATE" />

[Android] Toast

We have two method to use Toast 我們有兩種方式來顯示Toast

1.ToastActivity.this depends on this class name
 Toast toast = Toast.makeText(ToastActivity.this,"Hello world!", Toast.LENGTH_LONG);
 toast.show();
2.getApplicationContext()to get Current Context
 Context context1 = getApplication();
 Toast.makeText(context2, "Hello world!", Toast.LENGTH_LONG).show();

2015年6月8日 星期一

Android-finished with non-zero exit value 1

I encounted a problem in android studio. it shows ".....finished with non-zero exit value 1"
all my R.~~has a red underline!!! 
i was really shock!!!

Solution:
I cleaned the project and solved

Reason:
I faced this issue after replacing png drawables with jpg with the same name

2015年5月31日 星期日

Google Glass - 'Jump' to a card in CardScrollView via setSelection doesnt work

I had found why it can't jump to specific card for 1~2days.
Finally i got a resolution. hope i could help others
This block is get the position and use animate to jump to the specific
 mCardScroller.setSelection(mCardScroller.getSelectedItemPosition() + 1);
 mCardScroller.startAnimation(AnimationUtils.makeInAnimation(mCardScroller.getContext(), true));
BUT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NOT WORK
IMPORTANT!!ADD THIS IN YOUR ONCREATE()
mCardScroller.activate()
AND CHECK THIS TWO LIFE PERIOD
@Override
    protected void onResume() {
        super.onResume();
        mCardScroller.activate();
    }

    @Override
    protected void onPause() {
        mCardScroller.deactivate();
        super.onPause();
    }
GOOGLE GLASS 跳到特定的CARD,如果你咬遇到一樣的問題setSelection始終無法使用,在ONCREATE()理面加入mCardScroller.activate()就會有結果了 希望可以幫住到更多人,因為GLASS的資訊好少,我們也花了一點時間來解決這個問題!!

2015年5月29日 星期五

[mySQL]hinet.net is not allow to connect to this mySQL server

When i tried to connect mySql (not localhost),i met a problem






[Solution]:Because other the authority
shell>mysql --user=root -p
輸入密碼
mysql>use mysql
mysql>GRANT SELECT,INSERT,UPDATE,DELETE ON [db_name].* TO [username]@[ipadd] identified by '[password]';

[username]:遠程登入的使用者代碼(userid)
〔db_name]:表示欲開放給使用者的數據庫稱(show for user db name)
[password]:遠程登入的使用者密碼(user pwd)
[ipadd]:IP地址或者IP反查後的DNS Name,此例的內容需填入'59-126-182-81.HINET-IP.hinet.net',包涵上引號(')

(其實就是在遠端服務器上執行,地址填寫本地主機的ip地址。)

2015年5月22日 星期五

C# Textbox automatically scroll to the bottom

If you try to show the text on your textbox,we will account a problem.
The textbox vertical or horizontal length is not enough for us to use.
LIKE THIS PICRURE BELOW



















Solution:
  textBox1.ScrollBars = ScrollBars.Vertical; //scroll in vertical 
  textBox1.Text +=count+" : "+ read.GetInt32(0) + "Data"+"\r\n";
  textBox1.SelectionStart = textBox1.Text.Length;
  textBox1.ScrollToCaret();
  textBox1.Refresh();






2015年5月19日 星期二

C++ Fixed decimal point

Record how to fix the decimal point in c++
int main(){
 long double o = sqrt(2);
 for(int i = 0 ; i < 20 ; i++){//print long double
        cout.precision(i);
        cout << o << endl;
    }
}
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142136
1.41421356
1.414213562
1.4142135624
1.41421356237
1.414213562373
1.4142135623731
1.41421356237310
1.414213562373095
1.4142135623730951
1.41421356237309510
1.414213562373095100
1.4142135623730951000

2015年5月15日 星期五

C++ Vector

Record c++ Vector otherwise i will forget~~
First #include<vector>

"Add element"
for(int i=0 ; i<10 ; i++){
     cout<<"Add "<< i<<" to vector"<< endl;
     v1.push_back(i);
}
     cout<<"size : "<< v1.size()<< endl;

"Resize"
v1.resize(8);
cout<<"resize :"<< v1.size()<< endl;
cout<<"resize element :"<< endl;
for(int i=0 ; i < v1.size() ; i++){
cout<<"NO "<< i+1<<" : "<< v.1[i]<<"  "<< endl;
}

"Delete element"
int pos;
cout<<"Delete NO ";
cin>>pos;
v1.erase(v1.begin()+(pos-1));//begin=起始+0
for(int i=0 ; i < v1.size() ; i++)
cout<<"NO "<< i+1<<" : "<< v1[i]<< endl;

"Pop top element"
cout<<"pop top "<< endl;
v1.pop_back();
for(int i=0 ; i < v1.size() ; i++)
cout<<"NO "<< i+1<<" : "<< v1[i]<<"  "<< endl;

"Sort"
sort(v1.begin(),v1.end());
for(int i=0 ; i < v1.size() ; i++)
cout<< v1[i]<<" ";
cout<< endl;

"Reverse element"
cout<<"reverse : ";
reverse(v1.begin() , v1.end());
for(int i=0 ; i < v1.size() ; i++)
cout << v1[i]<<"  ";
cout<< endl;

"Use iterator"
cout<<"Find value : ";
int fnum;
cin>>fnum;
vector< int >::iterator it;
it=find(v1.begin() , v1.end() , fnum);
  if(it != v1.end()) {
     cout << "Found value!" << endl;
  }
  else{
      cout << "Not found!" << endl;
  }
cout<<"Use iterator"<< endl;
int count=0,temp;
for(it=v1.begin() ; it!=v1.end() ; it++){
     count++;
     cout<< *it <<" ";
       if(*it==fnum)
  temp=count;
}
 cout<< endl;
 cout<<"Found "<< fnum<<" position : "<< temp<< endl;

"Clean vector"
cout<<"use clear vector "<< endl;
v1.clear();
if(v1.empty())
   cout<<"empty vector"<< endl;
else
   cout<<"unempty"<< endl;

Some vector learning website:
web1
web2

2015年4月30日 星期四

Arduino Obstacle Avoidance Robot Car

Finally my MIDTERN exam is over~~ 
so i have time to share my arduino hw

This is our Arduino Obstacle Avoidance Robot Car.
It took us about 1hour to build it :O
 

This is part of our video with a lovely tempo~~

//超音波智能避障(ARDUINO)
//    L = 左
//    R = 右
//    F = 前
//    B = 後

#include  
int pinLB=6;     // 定義6腳位 左後
int pinLF=7;     // 定義9腳位 左前

int pinRB=8;    // 定義10腳位 右後
int pinRF=9;    // 定義11腳位 右前

int inputPin = A0;  // 定義超音波信號接收腳位
int outputPin =A1;  // 定義超音波信號發射腳位

int Fspeedd = 0;      // 前速
int Rspeedd = 0;      // 右速
int Lspeedd = 0;      // 左速
int directionn = 0;   // 前=8 後=2 左=4 右=6 
Servo myservo;        // 設 myservo
int delay_time = 50; // 伺服馬達轉向後的穩定時間

int Fgo = 8;         // 前進
int Rgo = 6;         // 右轉
int Lgo = 4;         // 左轉
int Bgo = 2;         // 倒車

void setup()
 {
  Serial.begin(9600);     // 定義馬達輸出腳位 
  pinMode(pinLB,OUTPUT); // 腳位 8 (PWM)
  pinMode(pinLF,OUTPUT); // 腳位 9 (PWM)
  pinMode(pinRB,OUTPUT); // 腳位 10 (PWM) 
  pinMode(pinRF,OUTPUT); // 腳位 11 (PWM)
  
  pinMode(inputPin, INPUT);    // 定義超音波輸入腳位
  pinMode(outputPin, OUTPUT);  // 定義超音波輸出腳位   

  myservo.attach(2);    // 定義伺服馬達輸出第5腳位(PWM)
 }
void advance(int a)     // 前進
    {
     digitalWrite(pinRB,LOW);  // 使馬達(右後)動作
     digitalWrite(pinRF,HIGH);
     digitalWrite(pinLB,LOW);  // 使馬達(左後)動作
     digitalWrite(pinLF,HIGH);
     delay(a * 100);     
    }

void right(int b)        //右轉(單輪)
    {
     digitalWrite(pinRB,LOW);   //使馬達(右後)動作
     digitalWrite(pinRF,HIGH);
     digitalWrite(pinLB,HIGH);
     digitalWrite(pinLF,HIGH);
     delay(b * 80);
    }
void left(int c)         //左轉(單輪)
    {
     digitalWrite(pinRB,HIGH);
     digitalWrite(pinRF,HIGH);
     digitalWrite(pinLB,LOW);   //使馬達(左後)動作
     digitalWrite(pinLF,HIGH);
     delay(c * 80);
    }
void turnR(int d)        //右轉(雙輪)
    {
     digitalWrite(pinRB,LOW);  //使馬達(右後)動作
     digitalWrite(pinRF,HIGH);
     digitalWrite(pinLB,HIGH);
     digitalWrite(pinLF,LOW);  //使馬達(左前)動作
     delay(d * 80);
    }
void turnL(int e)        //左轉(雙輪)
    {
     digitalWrite(pinRB,HIGH);
     digitalWrite(pinRF,LOW);   //使馬達(右前)動作
     digitalWrite(pinLB,LOW);   //使馬達(左後)動作
     digitalWrite(pinLF,HIGH);
     delay(e * 80);
    }    
void stopp(int f)         //停止
    {
     digitalWrite(pinRB,HIGH);
     digitalWrite(pinRF,HIGH);
     digitalWrite(pinLB,HIGH);
     digitalWrite(pinLF,HIGH);
     delay(f * 100);
    }
void back(int g)          //後退
    {

     digitalWrite(pinRB,HIGH);  //使馬達(右後)動作
     digitalWrite(pinRF,LOW);
     digitalWrite(pinLB,HIGH);  //使馬達(左後)動作
     digitalWrite(pinLF,LOW);
     delay(g * 100);     
    }
    
void detection()        //測量3個角度(0.90.179)
    {      
      int delay_time = 250;   // 伺服馬達轉向後的穩定時間
      ask_pin_F();            // 讀取前方距離
      
     if(Fspeedd < 10)         // 假如前方距離小於10公分
      {
      stopp(1);               // 清除輸出資料 
      back(2);                // 後退 0.2秒
      }
           
      if(Fspeedd < 15)         // 假如前方距離小於25公分
      {
        stopp(1);               // 清除輸出資料 
        ask_pin_L();            // 讀取左方距離
        delay(delay_time);      // 等待伺服馬達穩定
        ask_pin_R();            // 讀取右方距離  
        delay(delay_time);      // 等待伺服馬達穩定  
        
        if(Lspeedd > Rspeedd)   //假如 左邊距離大於右邊距離
        {
         directionn = Rgo;      //向右走
        }
        
        if(Lspeedd <= Rspeedd)   //假如 左邊距離小於或等於右邊距離
        {
         directionn = Lgo;      //向左走
        } 
        
        if (Lspeedd < 10 && Rspeedd < 10)   //假如 左邊距離和右邊距離皆小於10公分
        {
         directionn = Bgo;      //向後走        
        }          
      }
      else                      //加如前方不小於(大於)25公分     
      {
        directionn = Fgo;        //向前走     
      }
     
    }    
void ask_pin_F()   // 量出前方距離 
    {
      myservo.write(90);
      digitalWrite(outputPin, LOW);   // 讓超聲波發射低電壓2μs
      delayMicroseconds(2);
      digitalWrite(outputPin, HIGH);  // 讓超聲波發射高電壓10μs,這裡至少是10μs
      delayMicroseconds(10);
      digitalWrite(outputPin, LOW);    // 維持超聲波發射低電壓
      float Fdistance = pulseIn(inputPin, HIGH);  // 讀差相差時間
      Fdistance= Fdistance/5.8/10;       // 將時間轉為距離距离(單位:公分)
      Serial.print("F distance:");      //輸出距離(單位:公分)
      Serial.println(Fdistance);         //顯示距離
      Fspeedd = Fdistance;              // 將距離 讀入Fspeedd(前速)
    }  
 void ask_pin_L()   // 量出左邊距離 
    {
      myservo.write(5);
      delay(delay_time);
      digitalWrite(outputPin, LOW);   // 讓超聲波發射低電壓2μs
      delayMicroseconds(2);
      digitalWrite(outputPin, HIGH);  // 讓超聲波發射高電壓10μs,這裡至少是10μs
      delayMicroseconds(10);
      digitalWrite(outputPin, LOW);    // 維持超聲波發射低電壓
      float Ldistance = pulseIn(inputPin, HIGH);  // 讀差相差時間
      Ldistance= Ldistance/5.8/10;       // 將時間轉為距離距离(單位:公分)
      Serial.print("L distance:");       //輸出距離(單位:公分)
      Serial.println(Ldistance);         //顯示距離
      Lspeedd = Ldistance;              // 將距離 讀入Lspeedd(左速)
    }  
void ask_pin_R()   // 量出右邊距離 
    {
      myservo.write(177);
      delay(delay_time);
      digitalWrite(outputPin, LOW);   // 讓超聲波發射低電壓2μs
      delayMicroseconds(2);
      digitalWrite(outputPin, HIGH);  // 讓超聲波發射高電壓10μs,這裡至少是10μs
      delayMicroseconds(10);
      digitalWrite(outputPin, LOW);    // 維持超聲波發射低電壓
      float Rdistance = pulseIn(inputPin, HIGH);  // 讀差相差時間
      Rdistance= Rdistance/5.8/10;       // 將時間轉為距離距离(單位:公分)
      Serial.print("R distance:");       //輸出距離(單位:公分)
      Serial.println(Rdistance);         //顯示距離
      Rspeedd = Rdistance;              // 將距離 讀入Rspeedd(右速)
    }  
    
void loop()
 {
    myservo.write(90);  //讓伺服馬達回歸 預備位置 準備下一次的測量
    detection();        //測量角度 並且判斷要往哪一方向移動
      
   if(directionn == 2)  //假如directionn(方向) = 2(倒車)             
   {
     back(8);                    //  倒退(車)
     turnL(2);                   //些微向左方移動(防止卡在死巷裡)
     Serial.print(" Reverse ");   //顯示方向(倒退)
   }
   if(directionn == 6)           //假如directionn(方向) = 6(右轉)    
   {
     back(1); 
     turnR(6);                   // 右轉
     Serial.print(" Right ");    //顯示方向(左轉)
   }
   if(directionn == 4)          //假如directionn(方向) = 4(左轉)    
   {  
     back(1);      
     turnL(6);                  // 左轉
     Serial.print(" Left ");     //顯示方向(右轉)   
   }  
   if(directionn == 8)          //假如directionn(方向) = 8(前進)      
   { 
    advance(1);                 // 正常前進  
    Serial.print(" Advance ");   //顯示方向(前進)
    Serial.print("   ");    
   }
 }




2015年4月26日 星期日

CodeFight02

it's my midterm exam week!!!!!!  just so terrible~~

Year is leap if its number is divisible by 4 and isn't divisible by 100 or if its number is divisible by 400. Determine if a given year is leap or not.
[input] integer year number of the year
[output] boolean true if the given year is leap, false otherwise
bool leapYear(int year) {
    
  if (year % 4 == 0 && year % 100 !=0 || year % 400 == 0) {
    return true;
  }
  return false;
}

2015年4月18日 星期六

CodeFight01

1.Given array of integers, find the sum of absolute differences of consecutive numbers.
 Example [4, 7, 1, 2] -> 3 + 6 + 1 = 10
 [input] array.integer inputArray
 [output] integer sum of absolute differences of consecutive numbers from inputArray
int arraySumAdjacentDifference(std::vector inputArray) {

  int answer = 0;
  for (int i = 1; i < inputArray.size(); i++) {
    answer += std::abs(inputArray[i] - inputArray[i - 1]);
  }
  return answer;
}


2.Find the area of a rectangle with given sides.
 Example rectangleArea(2, 3) = 6
 [input] integer a positive integer
 [input] integer b positive integer [output] integer
int rectangleArea(int a, int b) {
   int result = a*b;
   for(int i=0; i < a; i++){
   result = a*b;
   }
   return result;
3.Determine if the given point is inside the given circle. [input] array.integer point array of length 2 representing a point [input] array.integer center array of length 2 representing the center of a circle [input] integer radius radius of the circle [output] boolean true if point is inside the circle centered at center with radius equal to radius or on its border, false otherwise
boolean insidecircle(std::vectorpoint ,std:vectorcenter,int radius){

  struct Helper{
    int sqr(int value){
      return value*value;
    }
  };

   Helper h;

   if(h.sqr(point[0]-center[0])+h.sqr(point[1]-center[1])<=h.sqr(radius)){
     return true;
   }
   return false;

}
4.Given integer n, find n! (factorial of n).
 [input] integer n non-negative integer
[output] integer
int factorial(int n) {
  if(n==0){
    return 1;
  }
  return n*factorial(n-1);
}

2015年4月15日 星期三

CodeFighter

1.For a given triangle determine if it is a right triangle.
[input] array.integer sides array of three integers representing triangle sides
[output] boolean true if the triangle with sides from the sides array is a right triangle, false otherwise
bool rightTringle(std::vector sides){
    struct Helper{
     int sqr(int value){
       return value*value;
     }
   };
   Helper h;
   std::sort(sides.gegin(),sides.end());
   if(h.sqr(sides[0]+h.sqr(sides[1]==h.sqr(sides[2])){
      return true;
   }
   return false
}

2.If the given integer is greater than 12 return this number, otherwise return 12.
 [input] integer number positive integer
 [output] integer
int returnTwelve(int number) {
  while(number < 12){
   number = number + 1;
  }
  return number
}

3.Given two integers a and b, find the remainder of a when divided by b.  
     Example for a=5, b=3 output should be 2

 [input] integer a a positive integer
 [input] integer b a positive integer
 [output] integer
int findTheRemainder(int a, int b) {
   while(a > b){
   a = a -b;
  }
  return a;
}

4.Given a string, find the number of different characters in it. for "cabca" output should be 3
[input] string s a string of lowercase latin letters
[output] integer
int differentSymbolsNaive(std::string s) {

  int result = 0;

  for (int i = 0; i < 26; i++) {
    bool found = false;
    for (int j = 0; j < s.size(); j++) {       
      if (s[j] = 'a' + i) {
        found = true;
        break;
      }
    }
    if (found) {
      result++;      
    }
  }
  return result;
}

5.Given an integer n, find the volume of the cube with edges equal to n.
     Example for n=5 output should be 125
[input] integer n positive integer
[output] integer

int cube(int n){
   int result =1;
   for(int i = 0; i < 3; i++){
     result = result * n; 
   }
   return result; 
}

2015年4月11日 星期六

#JAVA change line in txt

I tried to write string to txt file in java .
When i checked my txt file in my windows,i encountered some problems.
If i use \n to change a new line ,i saw some black block appear the position that should change line and change line doesn’t work at all.
But when i use my android device to check the result ,it’s ok!!!
It’s wired,but i found a way to solve it.

answer:
use \r\n instead of using \n and the txt file you open on you pc will be ok :")


如果單純用\n來換行,用記事本打開檔案時
會看到原本應該換行的地方變成很多黑色小方塊
而且每行會接在一起,看起來很奇怪
不過用Java讀取這個文字檔時卻又是正常的
解決法很簡單,只要在\n前面加上\r
變成"\r\n",在記事本上看就不會亂掉了