Saturday 31 December 2016

Error: '…' does not name a type

Most solutions to this problem talk about the headers. But the first reference below mentioned something that inspire me and solved my problem --  circular inclusion. 

There are many references about it online but I like this one:
http://stackoverflow.com/questions/625799/resolve-header-include-circular-dependencies

The way to think about this is to "think like a compiler".
Imagine you are writing a compiler. And you see code like this.
// file: A.h
class A {
  B _b;
};

// file: B.h
class B {
  A _a;
};

// file main.cc
#include "A.h"
#include "B.h"
int main(...) {
  A a;
}
When you are compiling the .cc file (remember that the .cc and not the .h is the unit of compilation), you need to allocate space for object A. So, well, how much space then? Enough to store B! What's the size of B then? Enough to store A! Oops.
......you can read on.

ref:
http://stackoverflow.com/questions/3961103/error-does-not-name-a-type (inspired by this)
http://stackoverflow.com/questions/2133250/does-not-name-a-type-error
http://stackoverflow.com/questions/8470822/error-x-does-not-name-a-type

http://stackoverflow.com/questions/625799/resolve-header-include-circular-dependencies

Tuesday 27 December 2016

Android: Send “POST” JSON Data to Server

The following blog provide a great example of posting JSON data to Server:

                               http://hmkcode.com/android-send-json-data-to-server/


But there are a few problems to be solved before successfully running.

(1) Check:
http://boriscoding.blogspot.ca/2016/12/fail-to-import-orgapachehttpxxx-stuff.html

(2) Check:
http://boriscoding.blogspot.ca/2016/12/error-method-gettext-must-be-called.html
And my MainActivity.java


import android.support.v7.app.AppCompatActivity;import android.os.Bundle;
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONObject;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.AsyncTask;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener {

    TextView tvIsConnected;    EditText etName,etCountry,etTwitter;    Button btnPost;
    Person person;    String got_etName,got_etCountry,got_etTwitter;    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
        // get reference to the views        tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);        etName = (EditText) findViewById(R.id.etName);        etCountry = (EditText) findViewById(R.id.etCountry);        etTwitter = (EditText) findViewById(R.id.etTwitter);        btnPost = (Button) findViewById(R.id.btnPost);
        // check if you are connected or not        if(isConnected()){
            tvIsConnected.setBackgroundColor(0xFF00CC00);            tvIsConnected.setText("You are conncted");        }
        else{
            tvIsConnected.setText("You are NOT conncted");        }

        // add click listener to Button "POST"        btnPost.setOnClickListener(this);
    }

    public static String POST(String url, Person person){
        InputStream inputStream = null;        String result = "";        try {

            // 1. create HttpClient            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL            HttpPost httpPost = new HttpPost(url);
            String json = "";
            // 3. build jsonObject            JSONObject jsonObject = new JSONObject();            jsonObject.accumulate("name", person.getName());            jsonObject.accumulate("country", person.getCountry());            jsonObject.accumulate("twitter", person.getTwitter());
            // 4. convert JSONObject to JSON to String            json = jsonObject.toString();
            // ** Alternative way to convert Person object to JSON string usin Jackson Lib            // ObjectMapper mapper = new ObjectMapper();            // json = mapper.writeValueAsString(person);
            // 5. set json to StringEntity            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity            httpPost.setEntity(se);
            // 7. Set some headers to inform server about the type of the content            httpPost.setHeader("Accept", "application/json");            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL            HttpResponse httpResponse = httpclient.execute(httpPost);
            // 9. receive response as inputStream            inputStream = httpResponse.getEntity().getContent();
            // 10. convert inputstream to string            if(inputStream != null)
                result = convertInputStreamToString(inputStream);            else                result = "Did not work!";
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());        }

        // 11. return result        return result;    }

    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();        if (networkInfo != null && networkInfo.isConnected())
            return true;        else            return false;    }
    @Override    public void onClick(View view) {

        switch(view.getId()){
            case R.id.btnPost:
                if(!validate())
                    Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();                // call AsynTask to perform network operation on separate thread                new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");                break;        }

        got_etName = etName.getText().toString();        got_etCountry = etCountry.getText().toString();        got_etTwitter = etTwitter.getText().toString();    }

    // Helps in creating the connection in a separate thread so the UI will not freeze.    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override        protected String doInBackground(String... urls) {

            person = new Person();            person.setName(got_etName);            person.setCountry(got_etCountry);            person.setTwitter(got_etTwitter);
            //person.setName(etName.getText().toString());            //person.setCountry(etCountry.getText().toString());            //person.setTwitter(etTwitter.getText().toString());
            return POST(urls[0],person);        }
        // onPostExecute displays the results of the AsyncTask.        @Override        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();        }
    }

    // Helper method to check that data is not empty before send the request.    private boolean validate(){
        if(etName.getText().toString().trim().equals(""))
            return false;        else if(etCountry.getText().toString().trim().equals(""))
            return false;        else if(etTwitter.getText().toString().trim().equals(""))
            return false;        else            return true;    }

    // Helper method to convert inputstream to String    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));        String line = "";        String result = "";        while((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();        return result;
    }
}




Error: “Method getText() must be called from the UI thread, currently inferred thread is worker.”





ref:
http://stackoverflow.com/questions/32011996/method-gettext-must-be-called-from-the-ui-thread-android-studio    (I did this)
http://stackoverflow.com/questions/32324769/error-method-gettext-must-be-called-from-the-ui-thread-currently-inferred-t
http://stackoverflow.com/questions/32568340/android-studio-error-method-gettext-must-be-called-from-the-ui-thread-curre

Sunday 18 December 2016

Fail to Import org.apache.http.XXX stuff in Android Studio

I was just trying to import these:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

but they went grey and says "unused ...". This is because HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')

Solution:
If you need sdk 23, add this to Gradle Scripts/build.gradle(Module:app)
          useLibrary 'org.apache.http.legacy'

It looks like the following:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
    applicationId "com.example.xxxx.xxxxxxxxxxample"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  }

.....................

}

Then there will be a pop up saying something changed in Gradle, do you want to Sync? And press Sync, it will re-compile everything and the errors are gone.


ref:
http://stackoverflow.com/questions/32153318/httpclient-wont-import-in-android-studio

Saturday 17 December 2016

Particle Photon Setup Problem: Flashing Cyan with a Quick Red Burst(Bad Key Issue)

Just didn't know why the Photon cannot connect to the cloud and keeps flashing cyan (with some very quick red burst sometimes). But the Particle team has been really helpful! Check this topic:

https://community.particle.io/t/photon-setup-flashing-cyan-with-a-quick-red-burst-now-orange-burst-solved/12118/70

To sum up:

particle keys new particle keys load device.pem particle keys send <device_id> device.pub.pem // grab this file https://s3.amazonaws.com/spark-website/cloud_public.der particle keys server cloud_public.der

Then try to put the device into Safe Mode and it CAN finally connected to the cloud again!!!
(Dec 17 2016)

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

This shit happened again Apr. 20 2017!!!!!!!!!

This time I fixed this with a easier way:

(1) Put the device into DFU

(2) particle keys doctor DEVICE_ID

Found DFU device 2b04:d008
Found DFU device 2b04:d008
New Key Created!
Found DFU device 2b04:d008
Found DFU device 2b04:d008
Saved!
spawning dfu-util -d 2b04:d008 -a 1 -i 0 -s 34:leave -D XXXYYYZZZDeviceID_rsa_new.der
dfu-util 0.8

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

dfu-util: Invalid DFU suffix signature
dfu-util: A valid DFU suffix will be required in a future dfu-util release!!!
Opening DFU capable USB device...
ID 2b04:d008
Run-time device DFU version 011a
Claiming USB DFU Interface...
Setting Alternate Setting #1 ...
Determining device status: state = dfuIDLE, status = 0
dfuIDLE, continuing
DFU mode device DFU version 011a
Device returned transfer size 4096
DfuSe interface name: "DCT Flash   "
Downloading to address = 0x00000022, size = 608
Download [=========================] 100%          608 bytes
Download done.
File downloaded successfully
Saved!
attempting to add a new public key for device XXXYYYZZZDeviceID
submitting public key succeeded!
Okay!  New keys in place, your device should restart.


(3) particle keys server

Found DFU device 2b04:d008
spawning dfu-util -d 2b04:d008 -a 1 -i 0 -s 2082 -D /usr/local/lib/node_modules/particle-cli/keys/rsa.pub.der
dfu-util 0.8

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

dfu-util: Invalid DFU suffix signature
dfu-util: A valid DFU suffix will be required in a future dfu-util release!!!
Opening DFU capable USB device...
ID 2b04:d008
Run-time device DFU version 011a
Claiming USB DFU Interface...
Setting Alternate Setting #1 ...
Determining device status: state = dfuIDLE, status = 0
dfuIDLE, continuing
DFU mode device DFU version 011a
Device returned transfer size 4096
DfuSe interface name: "DCT Flash   "
Downloading to address = 0x00000822, size = 512
Download [=========================] 100%          512 bytes
Download done.
File downloaded successfully
Okay!  New keys in place, your device will not restart.


(4) particle flash --usb tinker

Found DFU device 2b04:d008
spawning dfu-util -d 2b04:d008 -a 0 -i 0 -s 0x080A0000:leave -D /usr/local/lib/node_modules/particle-cli/binaries/p1_tinker.bin
dfu-util 0.8

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

dfu-util: Invalid DFU suffix signature
dfu-util: A valid DFU suffix will be required in a future dfu-util release!!!
Opening DFU capable USB device...
ID 2b04:d008
Run-time device DFU version 011a
Claiming USB DFU Interface...
Setting Alternate Setting #0 ...
Determining device status: state = dfuIDLE, status = 0
dfuIDLE, continuing
DFU mode device DFU version 011a
Device returned transfer size 4096
DfuSe interface name: "Internal Flash   "
Downloading to address = 0x080a0000, size = 4740
Download [=========================] 100%         4740 bytes
Download done.
File downloaded successfully

Flash success!

ref:
https://community.particle.io/t/solved-photon-fast-blinking-cyan-with-a-random-red-burst/14359
https://community.particle.io/t/photon-setup-flashing-cyan-with-a-quick-red-burst-now-orange-burst-solved/12118/75
https://community.particle.io/t/photon-flashing-cyan-with-red-bursts-solved/25113/3


Thursday 1 December 2016

Compiling Using Particle CLI with Subfolders

I always like to keep things tidy and neat so I keep many things in subfolders such as ./sensors/xxxTemperature.cpp and #include them in the same way with relative directories. However, problems come after I updated my particle cli this morning (didn't happen before). The compiler started to tell me:
fatal error: No such file or directory ../build/target/user/platform-6xxxx

I tried with just one directory with everything in it and it worked, although I HATE it because it looks so fatty. "Stupid Particle" I said...

The first reference inspired me that Particle is actually making its compiler "smart" enough to search through all subfolders and we don't have to manually setup the relative directories. For example, if we have ./sensors/xxxTemperature.h, we usually write the include code:
#include "./sensors/xxxTemperature.h"

Now you can just (no...ONLY) follow the smart way by writing:
                                                   #include "xxxTemperature.h"

And the Particle Compiler could automatically search for it.

ref:
https://community.particle.io/t/subdirectories-not-compiling-in-cli-fixed/9283/5   (helped me.)
https://community.particle.io/t/compiling-using-cli-with-multiple-directories/24273
https://community.particle.io/t/multiple-folders-in-the-dev-ide-compile-errors-go-to-blank-file/18876




Monday 28 November 2016

Using a void* Parameter



ref:
http://www.cplusplus.com/forum/general/50934/
http://stackoverflow.com/questions/3200294/how-do-i-convert-from-void-back-to-int


Bitbucket Daily Use


Daily Use:

git status
git branch

git add -A  // if you put something inside a sub-directory "git add ." won't detect

git commit -m 'accomplished what in this version'

git push origin develop

////////////////////////////////////////////////////////////////////////////////////////////////////////

Troubleshoots:
(0)
error: failed to push some refs to 'https://xxxxx@bitbucket.org/yyyyyyy/zzzzzzzz.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.

git push -f origin master

Force Push...

////////////////////////////////////////////////////////////////////////////////////////////////////////////

ref:
https://www.douban.com/note/525306465/
http://stackoverflow.com/questions/20939648/issue-pushing-new-code-in-github




Friday 18 November 2016

Particle Photon Firmware Dev Get Started Part: error: "BYTE_ORDER" redefined [-Werror]


Yet stuck at:
    make clean all PLATFORM=photon -s program-dfu

And I got:

In file included from ./src/photon/wiced/network/LwIP/WWD/FreeRTOS/arch/cc.h:69:0,
                 from ./src/photon/wiced/network/LwIP/ver1.4.0.rc1/src/include/lwip/arch.h:43,
                 from ./src/photon/wiced/network/LwIP/ver1.4.0.rc1/src/include/lwip/debug.h:35,
                 from ./src/photon/wiced/network/LwIP/ver1.4.0.rc1/src/include/lwip/opt.h:46,
                 from ./src/photon/wiced/network/LwIP/ver1.4.0.rc1/src/include/ipv4/lwip/ip_addr.h:35,
                 from ./src/photon/wiced/network/LwIP/WICED/wiced_network.h:43,
                 from ./src/photon/include/wiced_tcpip.h:44,
                 from ./src/photon/include/wiced.h:46,
                 from src/photon/delay_hal.c:27:
./src/photon/wiced/network/LwIP/WWD/FreeRTOS/cpu.h:43:0: error: "BYTE_ORDER" redefined [-Werror]
 #define BYTE_ORDER LITTLE_ENDIAN
 ^
In file included from /usr/local/gcc-arm-none-eabi-5_4-2016q3/arm-none-eabi/include/sys/types.h:67:0,
                 from /usr/local/gcc-arm-none-eabi-5_4-2016q3/arm-none-eabi/include/stdio.h:61,
                 from ./src/photon/wiced/WWD/include/wwd_debug.h:40,
                 from ./src/photon/wiced/WWD/include/wwd_assert.h:42,
                 from ./src/photon/wiced/RTOS/FreeRTOS/WWD/ARM_CM3/FreeRTOSConfig.h:41,
                 from ./src/photon/wiced/RTOS/FreeRTOS/ver7.5.2/Source/include/FreeRTOS.h:78,
                 from ./src/photon/wiced/RTOS/FreeRTOS/WWD/wwd_rtos.h:46,
                 from ./src/photon/wiced/WWD/include/RTOS/wwd_rtos_interface.h:47,
                 from ./src/photon/wiced/platform/MCU/STM32F2xx/peripherals/platform_mcu_peripheral.h:56,
                 from ./src/photon/wiced/platform/include/platform_peripheral.h:42,
                 from ./src/photon/include/wiced_platform.h:46,
                 from ./src/photon/include/wiced.h:44,
                 from src/photon/delay_hal.c:27:
/usr/local/gcc-arm-none-eabi-5_4-2016q3/arm-none-eabi/include/machine/endian.h:20:0: note: this is the location of the previous definition
 #define BYTE_ORDER _BYTE_ORDER
 ^
cc1: all warnings being treated as errors
../build/module.mk:256: recipe for target '../build/target/hal/platform-6-m/./src/photon/delay_hal.o' failed
make[2]: *** [../build/target/hal/platform-6-m/./src/photon/delay_hal.o] Error 1
../../../build/recurse.mk:11: recipe for target 'hal' failed
make[1]: *** [hal] Error 2
makefile:85: recipe for target '/home/boris/Dropbox/GROBO/Photon/PhotonSystemFirmwareDev/GetStarted/firmware/modules/photon/system-part1/makefile' failed


==========================================================

Seems to have something to do the arm-gcc compiler.

I find the solution in this link: https://github.com/spark/firmware/issues/1054
It turned out that arm gcc 5.4 is too new for Particle Firmware.

So I did everything again using arm gcc 5.3 and it worked!!!!!!!!!!
Don't forget to change the GCC_ARM_PATH.

Particle Photon Firmware Dev Get Started Part: ARM GCC Compiler Not Found Issue


I followed this link to install my ARM GCC Toolchain:

And I followed this link to start Photon Firmware development:

BUT I stuck at:
make clean all PLATFORM=photon -s program-dfu
And I get:

/bin/sh: 1: arm-none-eabi-gcc: not found
../build/arm-tools.mk:43: *** "ARM gcc version 4.8.4 or later required, but found ".  Stop.

This is mentioned in the Common Error and the provided solution is to export the PATH. However, at the end of the first Link above, it mentions that it would be better not to do that. So here is my solution:

(1) Locate file ../build/arm-tools.mk from firmware/modules
We can see all we need to fix is to indicate GCC_ARM_PATH

(2) At the top there is a line : include $(COMMON_BUILD)/common-tools.mk
GCC_ARM_PATH must be in there.

(3) open file ../build/common-tools.mk
We can see:
# GCC_ARM_PATH can be defined to be the path of the GCC ARM compiler,
# It must include a final slash! Default is empty

So I defined right here:
GCC_ARM_PATH = /usr/local/gcc-arm-none-eabi-5_4-2016q3/bin/


Friday 11 November 2016

Arduino Uploading Problem: stk500_recv(): programmer is not responding


This actually works for me:
switch on verbose output during upload (in the arduino IDE preferences pane).


ref:
http://stackoverflow.com/questions/19765037/arduino-sketch-upload-issue-avrdude-stk500-recv-programmer-is-not-respondi

Sunday 6 November 2016

Android Environment Setup





ref:
https://www.digitalocean.com/community/tutorials/how-to-install-java-with-apt-get-on-ubuntu-16-04
http://askubuntu.com/questions/421389/where-to-unpack-the-android-studio-file

http://askubuntu.com/questions/775078/lib32bz2-1-0-missing-on-16-04
http://stackoverflow.com/questions/29916379/unable-to-run-mksdcard-tool-during-android-studio-installation-on-ubuntu-15-04/39567843

http://stackoverflow.com/questions/16579448/how-to-change-or-add-theme-to-android-studio

Ubuntu Chinese Input Method




ref:
http://pinyinjoe.com/linux/ubuntu-12-chinese-setup.htm
http://pinyinjoe.com/linux/ubuntu-10-chinese-input-pinyin-chewing.htm

Wednesday 2 November 2016

Delete Ubuntu Safely with Win 7


(1) Download mbrfix.zip and unzip under root c:\
http://www.sysint.no/mbrfix

(2) Open Windows terminal and input:
cd \
mbrfix /drive 0 fixmbr /yes
(3) reboot
We don't see the grub list any more.

(4) delete the ubuntu partitions.

ref:
http://forum.ubuntu.org.cn/viewtopic.php?t=66401

Tuesday 1 November 2016

Grub Rescue

I got this prompt when I was trying to clear out some Disk from my Win 7 for Ubuntu. Here are the commands I've used to fix the problem.

(1) Find the /boot partition
ls

we can see something like:
(hd0,1),(hd0,5),(hd0,3),(hd0,2)

(2) Try them one by one and if one shows a file "grub.cfg", that is our /boot
ls (hd0,X)/grub -- I remember I have an independent partition for /boot

(3)
grub rescue>set root=(hd0,5)
grub rescue>set prefix=(hd0,5)/grub
grub rescue>insmod normal
grub rescue>normal

We can see our grub list now. BUT!!!!!! It's not over yet.

(4) last step

sudo update-grub
sudo grub-install /dev/sda



ref:
http://forum.ubuntu.org.cn/viewtopic.php?t=348503
http://askubuntu.com/questions/192621/grub-rescue-prompt-repair-grub

Friday 14 October 2016

[Important] static variable and static global variable


There might be a time, that you DID assigned some value to an static variable, but in a function somewhere else, the change cannot be detected. For example, I met this problem when using Software Timers (Particle) whose callback functions don't take any input parameters and return values. Therefore, global/static variables are the only way of communication to the callback functions.

Here is the reason:

(1) Global variables are stored in static region.(2*) Non-static global variable and static global variable are different where non-static global variable (just defined without keyword static) can be seen in all project source files while static global variable can only be seen in the source file where it is defined. 

So if I want some variables to be static and global, I should not put "static" in front of the definition otherwise functions in other source files cannot see it.

///////////////////////////////////////////////////////////////////////////////////////////////////////////

More, if coping with c++ objects...here are some tips.

(1) Dealing with Class/Object pointers:

First, variables declared as external must be defined. So you need to have
Logger *log;
in Logger.cpp. You can also initialize it there like this:
Logger *log = new Logger();
Second, you don't need any more declarations, that is you just need to include Logger.h, no need to declare another Logger variable in Foo.h, just use log from Logger.h.
(2) Dealing with objects

In .h file:
extern Timer _timerXXX;
extern Timer _timerYYY;
extern Timer _timerZZZ;

In .cpp file:
// give inputs to the constructors
Timer _timerXXX(x1, x2); 
Timer _timerYYY(y2, y2);
Timer _timerZZZ(z1, z2);

ref:
http://www.cnblogs.com/sideandside/archive/2007/03/29/692559.html
http://blog.csdn.net/ymangu666/article/details/22277673

ref more:
http://stackoverflow.com/questions/8362679/extern-pointer-initialization



Sunday 2 October 2016

Great Vim Configuration File


Found many online, but this one is perfect for me:


My Vim Configuration:
Mono-spaced small font suitable for a small laptop screen at 1280×800
“Desert theme” with dark background, 256-color palette
Some useful keyboard mappings
Use spaces as tabs (2 spaces = 1 tab), Smart indentation
Display line-numbers, Show matching braces when hover
Display all special characters (that is generally not supported in code files)
Auto-completion
Status-line modifications
Syntax-checking upon saving for almost all languages (plugins, see below)
File skeletons upon creation (plugins, see below)
Ignore CVS-, temporary and images (etc) files and directories
Disabled annoying sounds and bells (blinking)

Configuration:

" For Pathogen plugin manager
call pathogen#runtime_append_all_bundles()
call pathogen#helptags()

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Editing setings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" Enable filetype plugin
filetype plugin on
filetype indent on

" Filetypes and encoding
set fileformats=unix,dos,mac
set encoding=utf-8
set wildignore=.svn,CVS,*.o,*.a,*.class,*.mo,*.la,*.so,*.obj,*.swp,*.jpg,*.png,*.xpm,*.gif

" General behaviour
set autochdir      " CWD is always same as current file
set ai             " Autoident
"set si             " Smartident
set nowrap         " Do not wrap lines
set nocompatible   " ViM settings instead of Vi
set smartcase      " Smart casing when searching
set ignorecase     " ... or ignore casing
set hlsearch       " Highlight matches
set incsearch      " Modern (wrapping) search
set history=500    " Long undo history
set tw=1000

" make backspace a more flexible
set backspace=indent,eol,start

" Disable sounds
set vb t_vb="
set noerrorbells
set visualbell
" Tabbing, Default to 2 spaces as tabs
set cino=:0g0(0,W2
set expandtab
set tabstop=2
set softtabstop=2
set shiftwidth=2

" Filetype sesific
"au FileType python setlocal tabstop=4 softtabstop=4 shiftwidth=4

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" User interface setings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

syntax on
colorscheme desert

set showmatch                        " Show matching braces when over one
set ruler                            " Always show current position
set number                           " Always show line-numbers
set numberwidth=5                    " Line-number margin width
set mousehide                        " Do not show mouse while typing
set antialias                        " Pretty fonts
set t_Co=256                         " 256-color palletes
set background=dark                  " Dark background variation of theme
set guifont=Andale\ Mono\ 7.5          " Monospaced small font
set guioptions-=T                    " TODO
set guioptions+=c                    " TODO Console messages
set linespace=0                      " Don't insert any extra pixel lines
set lazyredraw                       " Don't redraw while running macros
set wildmenu                         " Wild menu
set wildmode=longest,list,full       " Wild menu options

" Display special characters and helpers
set list
" Show < or > when characters are not displayed on the left or right.
" Also show tabs and trailing spaces.
set list listchars=nbsp:¬,tab:>-,trail:.,precedes:<,extends:>
" Autocompletion
set ofu=syntaxcomplete#Complete
set completeopt+=longest,menuone
highlight Pmenu guibg=brown gui=bold
let g:SuperTabDefaultCompletionType = "<C-x><C-o>"

" Statusline
set statusline=%F%m%r%h%w[%L][%{&ff}]%y[%p%%][%04l,%04v]
"              | | | | |  |   |      |  |     |    |
"              | | | | |  |   |      |  |     |    + current
"              | | | | |  |   |      |  |     |       column
"              | | | | |  |   |      |  |     +-- current line
"              | | | | |  |   |      |  +-- current % into file
"              | | | | |  |   |      +-- current syntax in
"              | | | | |  |   |          square brackets
"              | | | | |  |   +-- current fileformat
"              | | | | |  +-- number of lines
"              | | | | +-- preview flag in square brackets
"              | | | +-- help flag in square brackets
"              | | +-- readonly flag in square brackets
"              | +-- rodified flag in square brackets
"              +-- full path to file in the buffer

" Highlight trailing whitespaces (+ keybindings below)
highlight ExtraWhitespace ctermbg=red guibg=red
highlight ExtraWhitespace ctermbg=darkgreen guibg=darkgreen
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhitespace /\s\+$/

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Plugins
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" ViM highlighting
au BufNewFile,BufRead *.mxml set filetype=mxml
au BufNewFile,BufRead *.as set filetype=actionscript

" Highlight errors for VIM supported languages
" Supported languages are: ada, c, chill, csc, forth, groovy, icon, java, lpc, mel, nqc, nroff, ora, pascal, plm, plsql, python and ruby. The c settings also apply to cpp.
let c_space_errors = 1
let java_space_errors = 1
let python_space_errors = 1
let ruby_space_errors = 1
" NERDTree
noremap <F12> :NERDTree<CR>

" Tskel
let tskelUserName='Anders Evenrud'
let tskelUserEmail='andersevenrud@gmail.com'

" Syntastic
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
"SyntasticEnable php
"SyntasticEnable javascript
"SyntasticEnable xhtml
"SyntasticEnable python
let g:syntastic_enable_signs=1
let g:syntastic_auto_loc_list=1
"let g:syntastic_quiet_warnings=1

" CloseTag
autocmd FileType html,htmldjango,jinjahtml,eruby,mako let b:closetag_html_style=1
autocmd FileType html,xhtml,xml,htmldjango,jinjahtml,eruby,mako source ~/.vim/bundle/closetag/plugin/closetag.vim

" SuperTab
let g:SuperTabDefaultCompletionType = "context"

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Key mappings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
inoremap <expr> <Esc>      pumvisible() ? "\<C-e>" : "\<Esc>"
inoremap <expr> <CR>       pumvisible() ? "\<C-y>" : "\<CR>"
inoremap <expr> <Down>     pumvisible() ? "\<C-n>" : "\<Down>"
inoremap <expr> <Up>       pumvisible() ? "\<C-p>" : "\<Up>"
inoremap <expr> <PageDown> pumvisible() ? "\<PageDown>\<C-p>\<C-n>" : "\<PageDown>"
inoremap <expr> <PageUp>   pumvisible() ? "\<PageUp>\<C-p>\<C-n>" : "\<PageUp>"

" RESIZE with numlock +-/*
if bufwinnr(1)
  map + <C-W>+
  map - <C-W>-
endif
"<home> toggles between start of line and start of text
imap <khome> <home>
nmap <khome> <home>
inoremap <silent> <home> <C-O>:call HHome()<CR>
nnoremap <silent> <home> :call HHome()<CR>
function! HHome()
 let curcol = wincol()
 normal ^
 let newcol = wincol()
 if newcol == curcol
  normal 0
 endif
endfunction

"<end> goes to end of screen before end of line
imap <kend> <end>
nmap <kend> <end>
inoremap <silent> <end> <C-O>:call HEnd()<CR>
nnoremap <silent> <end> :call HEnd()<CR>
function! HEnd()
 let curcol = wincol()
 normal g$
 let newcol = wincol()
 if newcol == curcol
  normal $
 endif
 "http://www.pixelbeat.org/patches/vim-7.0023-eol.diff
 if virtcol(".") == virtcol("$") - 1
  normal $
 endif
endfunction

"Ctrl-{up,down} to scroll. (gvim)
if has("gui_running")
 nmap <C-up> <C-y>
 imap <C-up> <C-o><C-y>
 nmap <C-down> <C-e>
 imap <C-down> <C-o><C-e>
endif

if bufwinnr(1)
  map <kPlus>  <C-W>+
  map <kMinus> <C-W>-
  map <kDivide> <c-w><
  map <kMultiply> <c-w>>
endif
" For highlighting trailing whitespaces
nnoremap <Leader>wn :match ExtraWhitespace /^\s* \s*\<Bar>\s\+$/<CR>
nnoremap <Leader>wf :match<CR>

" space / shift-space scroll in normal mode
noremap <S-space> <C-b>
noremap <space> <C-f>

ref:
https://anderse.wordpress.com/2011/09/07/my-vim-gvim-configuration/

Saturday 1 October 2016

permissions denied on serial port /dev/ttyACM0

Serial port is very commonly used when developing embedded systems such as Arduino or Particle core.

But we might encounter the following problem when trying to open the serial monitor:

                   Permission denied, cannot open /dev/ttyACM0

Many suggest to do:

              sudo chmod 666 /dev/ttyACM0

I don't know them but it did NOT work for me. This DID:

sudo usermod -a -G dialout boris

in which boris is my username.
And call:
      groups boris
to check.

Maybe you gotta login again.


Ref:
http://askubuntu.com/questions/616517/dev-ttyacm0-permission-denied-error
http://askubuntu.com/questions/58119/changing-permissions-on-serial-port

Open terminal by right click


Install nautilus-open-terminal. In a terminal type:
sudo apt-get install nautilus-open-terminal
Once it installs, type nautilus -q && nautilus & to quit and reopen nautilus, and check the right click option.


ref:
http://askubuntu.com/questions/293566/open-terminal-from-nautilus-by-right-click

Sunday 25 September 2016

Make VIM into an IDE



(1) ctags

$sudo apt-get install exuberant-ctags

> Now go to the directory with the source files, go into it, not one level out it. And use:
    $ctags -R *

  -R indicates recursively, which means the subdirectories are also searched. And we can see a new file naned "tags".

Here are some useful cmds for ctags:

Ctrl + ]
Ctrl + t
:tag function_name 
:ta function_name












ref:
http://blog.csdn.net/daniel_ustc/article/details/8299096
https://andrew.stwrt.ca/posts/vim-ctags/



Friday 23 September 2016

Ubuntu Chinese Pingying Characters not Coming Out


When I just added Pingying Input and tried to type, there is no characters coming out for choosing. Here is the solution:

terminal$:  ibus-daemon -drx

This basically re-start the ibus process.

Ubuntu Chinese Pingying Characters not Coming Out


When I just added Pingying Input and tried to type, there is no characters coming out for choosing. Here is the solution:

terminal$:  ibus-daemon -drx

This basically re-start the ibus process.

Wednesday 21 September 2016

How to use #if 0 ... #endif


#if 0
...
#endif

basically tells the compiler that there is no need to compile this part of codes.

Usage:
(1) There might be something needed LATER in the program but we don't yet know exactly how this part works. So just leave it there now without compiling it.

(2) When we want to comment a block of codes using /* ... */, but there are some other comments in this block using  /* ... */, the only option we have is use #if 0 to avoid the compilation of it.

(3) Testing and debugging

#if 0
{original program...}
#else{new program...}
#endif


if we need to change back to the original program, just change the 0 back to 1.

ref:
http://www.programmer-club.com.tw/ShowSameTitleN/c/29150.html

Tuesday 13 September 2016

Particle Photon Getting Started


Step 1:
To install Node.js, type the following command in your terminal:
Then install the Node package manager, npm:
Create a symbolic link for node, as many Node.js tools use this name to execute.
Now we should have both the Node and npm commands working:
$ npm install -g particle-cli
Step 2:
sudo npm install -g particle-cli


Ref:
http://www.hostingadvice.com/how-to/install-nodejs-ubuntu-14-04/#ubuntu-package-manager
https://docs.particle.io/guide/tools-and-features/cli/photon/


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Trouble shooting, after an particle-cli upgrade, I am getting two errors look like:

        /usr/local/lib/node_modules/particle-cli/commands/Key Commands.js:213 

and the other similar one.

This is because the node version is too old. So we have to (1) upgrade node (2) remove particle-cli (3) re-install particle-cli again.

(1) in order to install the latest node
   1 Install npm:
sudo apt-get install npm
  1. Install n
sudo npm install n -g
  1. Get latest version of node
sudo n latest

(2) remove and re-install particle-cli
sudo npm remove -g particle-cli
sudo npm install -g particle-cli


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

I setup a brand new computer again.

Step 1:
sudo apt-get install nodejs-legacy
sudo apt-get install npm
You wont get the latest version but we are going to upgrade them in a minute.

Step 2:
Update them.
sudo npm cache clean -f
sudo npm install -g n
sudo n latest

Step 3:
bash <( curl -sL https://particle.io/install-cli )
Wait a while and that's IT!!!


ref:
https://github.com/spark/particle-cli/issues/176
http://stackoverflow.com/questions/34974535/install-latest-nodejs-version-in-ubuntu-14-04
http://www.hostingadvice.com/how-to/update-node-js-latest-version/
https://docs.particle.io/guide/tools-and-features/cli/photon/