Friday, November 2, 2018

API fun


Rest lacked standards
https://dzone.com/articles/rest-api-documentation-part-1

in general an API has various “resources” that you access through “endpoints.” The endpoints give you access to the resource. (But terminology isn’t standard, so expect variety.
https://idratherbewriting.com/learnapidoc/docapis_resource_descriptions.html

The endpoints indicate how you access the resource, and the method used with the endpoint indicates the allowed interactions (such as GET, POST, or DELETE) with the resource...Path parameters (represent them through curly braces) are part of the endpoint itself, and are not optional.
https://idratherbewriting.com/learnapidoc/docapis_resource_endpoints.html


Parameters are options you can pass with the endpoint (such as specifying the response format or the amount returned) to influence the response. There are four types of parameters: header parameters, path parameters, query string parameters, and request body parameters
https://idratherbewriting.com/learnapidoc/docapis_doc_parameters.html

curl is a command-line utility that lets you execute HTTP requests with different parameters and methods. Instead of going to web resources in a browser’s address bar, you can use the command line to get these same resources, retrieved as text.
https://idratherbewriting.com/learnapidoc/docapis_install_curl.html


REST APIs follow an architectural style, not a specific standard. However, there are several REST specifications that have been developed to try to provide some standards about how REST APIs are described.
https://idratherbewriting.com/learnapidoc/pubapis_rest_specification_formats.html


With OpenAPI (Swagger), instead of XML, you have set of JSON objects, with a specific schema that defines their naming, order, and contents. This JSON file (often expressed in YAML instead of JSON) describes each part of your API. By describing your API in a standard format, publishing tools can programmatically ingest the information about your API and display each component in a stylized, interactive display.
https://idratherbewriting.com/learnapidoc/pubapis_swagger_intro.html










Swagger editor
http://editor.swagger.io/

YAML refers to “YAML Ain’t Markup Language,”

https://swagger.io/tools/swagger-codegen/ is one of the code generators , but SmartBear who does SoapUI is supported.

display framework that reads an OpenAPI specification document and generates an interactive documentation website. This tutorial shows you how to use the Swagger UI interface and how to integrate an OpenAPI specification document into the standalone distribution of Swagger UI
https://idratherbewriting.com/learnapidoc/pubapis_swagger.html








The link for a good example
https://howtodoinjava.com/swagger2/swagger-spring-mvc-rest-example/

Or making a rest call using RestTemplate programatically:
https://spring.io/guides/gs/consuming-rest/

For example, I did this project example https://spring.io/guides/gs/rest-service/ and converted it to swaggerness and got json format with http://localhost:8080/v2/api-docs . Was able to get yaml with https://www.json2yaml.com/


Building a back-end API layer introduces a whole new area of challenges that goes beyond implementing just endpoints. You now have clients which will now be using your API. Your clients will need to know how to interact with your API. In SOAP-based web services, you had a WSDL to work with. This gave API developers an XML-based contract, which defined the API. However, with RESTFul web services, there is no WSDL. Thus your API documentation becomes more critical. API documentation should be structured so that it’s informative, succinct, and easy to read. But best practices on, how you document your API, its structure, what to include and what not to is altogether a different subject that I won’t be covering here"
https://dzone.com/articles/spring-boot-restful-api-documentation-with-swagger
https://www.infoq.com/presentations/doc-restful-api


API First Swagger Top Down approach
https://www.easyitblog.info/2017/01/08/api-first-approach-with-swagger/
"There are a lot of good API design tools. Here are some useful comcparisons"


need to add spec for API. How can we do this in Apigee, do we have option to create swagger documentation for REST service in Apigee or we have to use other tool to prepare documentation and create spec in Apigee by importing doc created using third party tool, if documentation is out of box solution in Apigee. If Api documentation possible in Apigee. Please share how to implement this.
https://community.apigee.com/questions/53011/rest-service-documentation.html

https://community.apigee.com/articles/25770/openapi-spec-swagger-spec-generator-a-tool-to-gene.html using SmartDocs The tool you can use is http://specgen.apistudio.io/


https://swagger.io/tools/

https://www.xoriant.com/blog/product-engineering/swagger-specification-code-generation.html

Sunday, February 11, 2018

Vision Video


Getting started with video:
http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html#display-video


The following example will load up a video from disk . It uses the VideoCapture object.
  • Its argument can be either the device index or the name of a video file. Device usually is the index is just the number to specify which camera to use.  This line below sets the video source to use an existing file.


#------------------------------------------------------------
import numpy as np
import cv2 as cv
cap = cv.VideoCapture('output.mp4')
while(cap.isOpened()):
       ret, frame = cap.read()
       gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
       cv.imshow('frame',gray)
       if cv.waitKey(1) & 0xFF == ord('q'):
             break
cap.release()
cv.destroyAllWindows()

#------------------------------------------------------------

[link]  - tweak for VideoCapture

VideoWriter([filename, fourcc, fps, frameSize, isColor)
  • filename – Name of the output video file.
  • fourcc – 4-character code of codec used to compress the frames. 
  • fps – Framerate of the created video stream.
  • frameSize – Size of the video frames.
  • isColor – If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames (the flag is currently supported on Windows only).


The read() function

  • reads one frame from the video source, which in this example is the webcam. 

This returns two things:
  • The actual video frame read (one frame on each loop) 
  • A return code (True/False). If frame is read correctly.  It tells us if we have run out of frames, which will happen if we are reading from a file. This doesn’t matter when reading from the webcam, since we can record forever, so we will ignore it.
Reading from web camera:

#------------------------------------------------------------
while(True):  
     # Capture frame-by-frame  
     ret, frame = cap.read()  
    # frame come here  
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)  
 
    # Display the resulting frame  
    cv.imshow('frame',gray)  
    if cv.waitKey(1) & 0xFF == ord('q'):      
          break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

#------------------------------------------------------------


Saving images from video camera input to a file:

#------------------------------------------------------------

import cv2
import numpy as np
#This line sets the video source to the default webcam, which OpenCV
cap = cv2.VideoCapture(0)
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH);
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT);
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4',fourcc, 15.0, (int(w),int(h)))

while True:
        ret,frame = cap.read()
        #---------for gray video--------
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        out.write(frame)

        #Display the resulting frame
        cv2.imshow('myvideo',frame)
        cv2.imshow('myvideo',gray)
        cv2.waitKey(0)      
        k = cv2.waitKey(0) & 0xFF
        if k == ord('q'):    # wait for 'q' key to exit break
                break
cap.release()
out.release()
cv2.destroyAllWindows()


#------------------------------------------------------------

Saturday, February 10, 2018

Vision Overview

In my earlier Python post I mentioned how easy is to install Open CV

OpenCV is the most popular library for computer vision. Originally written in C/C++, it now provides bindings for Python. OpenCV uses machine learning algorithms to search for faces within a picture. For something as complicated as a face, there isn’t one simple test that will tell you if it found a face or not. Instead, there are thousands of small patterns/features that must be matched. The algorithms break the task of identifying the face into thousands of smaller, bite-sized tasks, each of which is easy to solve
Here is what you can do with OpenCV

Well before we start mentioning the provided examples on web site, it is good to have the API search tool - i.e. reading and writing images API


Here as part of the gui features we will read an image from disk. Likewise, we can write a copy of the image to the disk.

Here are some of the methods we will use:

imread
  • file name
  • flag on way image should be read
imshow
  • named window name
  • image
imwrite
  • file name on disk
  • image



#------------------------------------------------------------
import cv2
import numpy as np

#practice numpy
#https://www.w3resource.com/python-exercises/numpy/index.php#EDITOR

# IMREAD_GRAYSCALE = 0
# IMREAD_COLOR = 1
# IMREAD_UNCHANGED = -1

 img = cv2.imread('img.JPG',cv2.IMREAD_GRAYSCALE)

# ----------showing with opencv.........

cv2.imshow('my image',img)
k = cv2.waitKey(0) & 0xFF

if k == 27: # wait for ESC key to exit
      cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
       cv2.imwrite('img2.JPG',img) # writing the image
       cv2.destroyAllWindows()

#------------------------------------------------------------





  •  mouse as paint brush
  •             https://docs.opencv.org/master/db/d5b/tutorial_py_mouse_handling.html


    Wednesday, February 7, 2018

    python everywhere

    Python seems like the hot thing. I have been learning and experimenting.

    I use The following package manager for macOS:  https://brew.sh/

     /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 

    use example: - brew install python

    anaconda https://www.youtube.com/watch?v=8JiWEZEnJ40

    Install anaconda:

    • https://repo.continuum.io/archive/Anaconda3-4.2.0-Windows-x86_64.exe 
    • https://repo.continuum.io/archive/Anaconda3-4.2.0-MacOSX-x86_64.pkg


    condo update anaconda

    to install opencv:

    conda install --channel https://conda.anaconda.org/menpo opencv3

    confirm the install from python command line
            import cv2
            cv2.__version__

    spyder is an IDE for perl - for macOs from the cmd line enter to start it:
                spyder&

    console : print "hello"
    editor: run by select f9
    inspector : debugging

    see spyder perl tutorial https://www.youtube.com/watch?v=J5GevIHNctM


    http://www.numpy.org/
    • https://www.w3resource.com/python-exercises/numpy/index.php

      https://www.scipy.org


    active state
    python tutorial https://pythonprogramming.net/introduction-to-python-programming/

    https://www.youtube.com/watch?list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&time_continue=163&v=IX6mc9l6tY4

    https://www.youtube.com/watch?v=5aP9Bl9hcqI

    https://docs.cs50.net/2016/fall/notes/8/week8.html
    https://www.cs.cornell.edu/courses/cs1110/2017fa/lectures/index.php 
    python class http://stanfordpython.com/#lecture
    http://arc-ts.umich.edu/mini-course-introduction-to-python-sept-11-14/ python https://stanford.edu/~schmit/cme193/ python

    https://github.com/wgong/py4kids

    Monday, December 15, 2014

    Firebase

    firebase joins google - g+ page  why

    three way binding:

    We can synchronize our data back to Firebase by using the following methods provided by the $firebase object.


    • $add(value)
    • $remove([key])
    • $save([key])
    • $save()
    • $child(key)
    • $set(value)


    create a free account

    Once you are logged in, you can view your url  on https://www.firebase.com/account/#/

    https://www.firebase.com/tutorial/

    https://www.firebase.com/docs/web/quickstart.html

    https://www.firebase.com/docs/

    plunkr demo #1

    https://www.firebase.com/docs/web/guide/understanding-data.html

    Friday, December 5, 2014

    client side reorder list

    I am looking into jquery ui drag and drop grid row

    http://jqueryui.com/sortable/

    Enable a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items share draggable properties

    http://api.jqueryui.com/sortable/

    options:
    items: Specifies which items inside the element should be sortable
    handle:Restricts sort start click to the specified element.

    events:
    stop( event, ui )Type: sortstop This event is triggered when sorting has stopped


    example : http://plnkr.co/edit/jpxc42tF55jktfI3upTE?p=preview 














    Tuesday, November 18, 2014

    Links i have learned about lately


    https://github.com/gregturn/spring-a-gram - Spring Boot, Spring Data, Spring Rest and JQuery UI (see GalleryRepository class , PagingAndSortingRepository)

    Nodevember
    - http://nodevember.org/#speakers
    - http://nodevember.org/#speakers

    Angular sub topics

    A few weeks ago I used angular to create a sample app.  That was a good experience. In keeping with learning more Angular,  I came a cross a podcast blog Adventures in Angular. The first episode i listened to was http://devchat.tv/adventures-in-angular/angular-meetups-with-matt-zabriskie-and-sharon-diorio . This talk had training videos sessions:

    Meetup Angular and bootstrap - see Plunkr
    Utah Angular user group
    Testing with Angular

    Pluralsight has training on bootstrap 3 as well.

    Sunday, November 9, 2014

    Polymer Step by Step



    Create Elements page : https://www.polymer-project.org/docs/start/creatingelements.html
    • npm install -g bower
    • bower init
    • bower install --save Polymer/polymer
    • bower install --save Polymer/core-elements
    • bower install --save Polymer/paper-elements
    • bower install --save Polymer/core-ajax

    Chrome Dev Editor

    index.html:
    bower_components/
    elements/

    index.html:
    <!DOCTYPE html><html>
    <head>
    <!-- 1. Load platform support before any code that touches the DOM. -->
    <script src="bower_components/platform/platform.js"></script>
    <!-- 2. Load the component using an HTML Import -->
    <link rel="import" href="elements/my-element.html"> </head>
    <body>
    <!-- 3. Declare the element by its tag. -->
    <my-element></my-element>
    </body>
    </html>

    elements/my-element.html:

             <link rel="import" href="../bower_components/polymer/polymer.html"> 
             <link rel="import" href="../bower_components/core-ajax/core-ajax.html"> 
             <polymer-element name="my-element" noscript>
               <template> 
                 <span>I'm <b>my-element</b>. This is my Shadow DOM.</span>
                 <core-ajax url="https://api.github.com/users/angular" auto response="{{resp}}">
                 </core-ajax> 
                 <textarea value="{{resp}}"></textarea> 
               </template> 
             </polymer-element>

    elements/proto-element.html:

    <link rel="import" href="../bower_components/polymer/polymer.html">
    <link rel="import" href="../bower_components/core-ajax/core-ajax.html">

    <polymer-element name="proto-element">
    <template>
          <span>I'm <b>proto-element</b>. Check out my prototype.</span>
    </template>
    <script> Polymer({
                                    ready: function() {
                                            // properties and methods here
                                        }
                                 });
    </script>
    </polymer-element>

    API Guide


    GDG Triangle Polymer Introduction

                   [ core-elements.html#core-toolbar ] :

                  <body unresolved> 
                    <core-toolbar>
                        <div>Toolbar</div> 
                    </core-toolbar> 
                  </body>
              [ paper-elements.html#paper-tabs ]

               <body unresolved fullbleed> 
                  <core-toolbar class="medium-tall"> 
                        <paper-icon-button icon="menu"> </paper-icon-button> 
                        <div flex>Title</div> 
                        <paper-icon-button icon="search"></paper-icon-button> 
                        <paper-icon-button icon="more-vert"></paper-icon-button> 
                        <div class="bottom fit" horizontal layout> 
                              <paper-tabs selected="0" flex style="max-width: 600px;"> 
                                   <paper-tab>ITEM ONE</paper-tab> 
                                   <paper-tab>ITEM TWO</paper-tab> 
                                    <paper-tab>ITEM THREE</paper-tab>
                               </paper-tabs> 
                       </div> 
                 </core-toolbar> 
             </body>

    Polymer Player

    https://github.com/kylebuch8/PolymerPlayer/blob/master/index.html
    https://github.com/kylebuch8/PolymerPlayer/blob/master/components/player-song/player-song.html

    https://github.com/kylebuch8/PolymerPlayer/blob/master/components/player-songs/player-songs.html

        <template repeat="{{sng, i in songs}}">
           <div class="song" needZ?="{{song.title === sng.title}}"> 
                 <div hero-id="{{sng.title}}" hero>
                      <div class="bg" style="background-image: url(images/{{sng.img}});"> 
                             <player-color-thief song="{{sng}}"></player-color-thief>
                      </div> 
                      <div class="footer" style="background-color: {{sng.dominantColor}}; color: {{sng.textColor}};"> 
                            <span class="title">{{sng.title}}</span>
                            <br> <small>{{sng.artist}}</small> 
                     </div> 
               </div> 
           </div> 
    </template>

    https://github.com/flatiron/director

    https://github.com/kylebuch8/PolymerPlayer/blob/master/components/player-songs/player-color-thief.html

    <polymer-element name="player-color-thief" attributes="song">

    Saturday, November 1, 2014

    DevFest at American Underground 2014

    The Dev Fest is organized by  Luke Dary  +Luke Dary .  Next GDG meeting possibly will  be held in the Google office in Chapel Hill. Udacity will be partnering to do Android development course thru GDG.

    Polymer  #itshackademic

    polymer-project.org

    Intro Video

    Rob Dodson - Core Icons

    what problems solving?   css is global , phone/tablets,smart tvs  etc  Front end development so it works on all devices. i.e Tabs should be easy, not easy to plop in anywhere. old frameworks can be a challenge,

    <paper-tabs>
    <paper-tab>one</paper-tab>

    tip: do a  view source of gmail
    table soup, div soup
    web components
    -  required to have dash in name to be custom element (otherwise show as unknown)
    - paper tab (material design )
    - resusable
    -  templates -native client side  , parsed, does not render, content inert til cloned/used,
    - shadow dom - browser not rendering all, chrome has ability to show hidden structure you dont usually see
    - html imports <link rel="import" href="bootstrap.html">      vulcanize - tool to concat your dependencies and do it once
    - custom elements : use existing, extend others, encapsulated css customelements.io


    http://itshackademic.com/

    https://www.polymer-project.org/docs/start/getting-the-code.html


    https://www.polymer-project.org/docs/start/creatingelements.html


    Thursday, October 30, 2014

    Next Web

    I recently watched Eric Bidelman's talk from Google I/O 2013 on Web Components.  This talk was on the Future of the web platform. This talk reminds me of Angular methodology where you are adding custom tags to HTML.

    As well  Peter Gasston talks about web components and CSS. Example of video player which runs on javascript, html, css.  If you show hidden dom, you can see markup.

    Show shadow dom in web tools under wrench:





    shadow root, host, dom

    shadow root:
    var newroot  = $(foo).createShadowRoot(), newElem =  '<h2<test</h2>' ;

    newroot.innerHTML = newElem ;

    <div id ="foo"><h1> First</h1></div>

    div tag  is the shadow host, and h1 text replaces h2 with test.


    widget example: <div id ="foo"><h1> First</h1></div>
    want it but in different color
    encapsulation - has all it needs contains within itslef, nothing gets in, nothing gets out
    encapsulation in html is iframe today - issues extra network, multiplee rendering, cross orgin conflicts
    better encapsulation is web components
    reusable web components - shadowdom, templates,  custom tags

    templates - put stuff in it

    <template id ="foo"><h2> First</h2></template>
    <div id ="bar"><h1>text 2</h1></div>

    mark up inside is inert - does nothing, does not get loaded

    inside template known as content

    var test = $(foo).content.cloneNode(true), bar = document.getElementById('bar');
    bar.appendChild(test);

    puts template inside bar div tag  - template active

    share templates across multiple files using import



    4 main areas (Shadow DOM gives encapsulation, templates or chunk of markup that later you can stamp out your elements, custom tags, html imports that can be reused via CDN URLs):



    HTML templates:
    Template out your markup 
    Put dom in it
    Parsed not rendered - won't run until you stamp it out, same for media
    Hidden from document, cant traverse into,  its in its own context

    Content property - document fragment , clone it, stamp it out, see whats in it

    Example:


    Clone it is what stamps it out (here it runs script when that happens):

    http://www.webcomponentsshift.com/#15

    New spec for html templates  : chrome supports it.


    Shadow dom (Secret markup in elements):
    markup encapsulation, DOM encapsulation, css style boundary protection, no bleeding in, style boundaries, exposes to developers mechanics browser vendors use to create their html elements

    iframe has it but bloated, hard to use  (extra network requests needed, multiple rendering contexts)




    Dom nodes can host hidden dom

    hidden dom  can't be accessed by outside  javscript





    Hidden document fragment

    Using markup to control it

    Browser vendors been holding out

    http://www.webcomponentsshift.com/#23



    Filled in markup

    Shadow dom gets rendered


    Style things

    This time add styling make it red



    @host

    Host element provide default styles






    Custom elements (require hyphen)

    Ability to define new elements

    Plunkr example 






    Using js html.prototype 

    http://www.webcomponentsshift.com/#35



    Html imports




    Saturday, October 11, 2014

    Just took a Bower

    Tool for easily manage the 3rd party client side libraries within your code.

    The old school process is to browse, download, extract zip, find files, copy, links to files in html.

    Bower eliminates most of this Its for client side files, but can do any type of files. Bower calls the files modules Packages

    Bower calls into Github to get files

     npm install -g bower

     bowser install <proj>

     Dist directory js and minified one

     Add it to your project in script tag

     Get rid of something
       bower uninstall <proj>

     Updating projects (i.e. multiple)

    bower update

    Might need to be careful

    One at a time

    bower install <proj>

    What packages?

    bower list

    bower search <proj>

    http://bower.io/search/

    bower.json file
    - name,  version, main, dependencies

    bower init
    - prompted to create json file

    .bowerrc
    - directory:relative path to folder

    bower install
    bower install <project> --save
    bower uninstall <project> --save


    Related post : [http://bloomonclientside.blogspot.com/2013/11/bower-is-package-manager-for-installing.html]

    Thursday, October 2, 2014

    Android Mobile Coursera class has started

    I am signed up with 140,000 other students for  the "Programming Mobile Applications for Android Handheld Systems" training class starting now.

    The teacher is Dr. Adam Porter

    Preview lectures

    Asignments

    Lecture 1 slides

    3 Applications
    2 Application Framework
    1 Native System Libraries (Native DK) / Runtime (Davlik - Core Libraries)
    0 Linux Kernel

    3 : Contacts, Phone, Browser, Home app, etc

    2: reusable software that many applications will need like Package Manager , Window Manager, View System (common user interface elements such as Tabs, Lists, grids, text boxes, buttons, textview ), Resource Manager (non-compiled code resources: strings, graphics, & layout files), Content Providers, Activity Manager,  Location Manager

    1 : core performance sensitive activities on device (native dev kit) such as C library, surface manager, media manager webkit etc. / File packaged with other resources and installed on device. Dalvik VM executes the Dex Bytecode file when invoked on device. Dalvik VM designed to be resource constrained environment with slower cpu, less memory, limited battery life System C library .

    0 : Standard services - Provides infrastructure mechanisms to manage mobile device resources. Android specific such as power management, Android Shared memory, Binder, etc

    Use the Hierarchy Perspective after the program is launched :


    here is some sample output(click on your activity on the left):



    The Traceview within DDMS can be pressed to start when a debug tracepoint is hit, which starts the profiling. After profiling is started, let it run through, and then click the same button to end the profiling.  The botton to start/stop is shown:



    After hitting the end button, the output is shown (timeline view on top and profile view on bottom):



    Method profiling - select class, start it, then do something on device with app, click stop:



    This first week includes:
     1. The Week 1 Quiz. Sixteen or so questions to help you make sure you've followed my lectures.

    2. Two Labs.
     a) Lab - Learn to Submit - A very simple assignment designed to make sure that you can submit work to the Coursera system for grading

    "To do this assignment, simply create a one-line text file with the name of your home country and nothing else. Make sure you are creating a real text file, not, for example a .rtf file" Then click on the submit button to select and upload that text file."

     b) Lab - Development Environment - A more involved Lab to help you set up your Development Environment and to familiarize yourself with it.



    Intel Hardware Accelerated Execution Manager(HAXM)


    AndroidManifest.xml:

    Define your package :
    package="course.examples.theanswer"

    Define your Actvity:
    <activity
                android:name="course.examples.theanswer.TheAnswer"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
    
    
    
    Define your layout in answer_layout :
    <RelativeLayout...
    <TextView
            android:id="@+id/answer_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="24sp" />"
    
    
    set your layout and access your widget
       setContentView(R.layout.answer_layout);
       TextView answerView = (TextView) findViewById(R.id.answer_view);
       answerView.setText("The answer to life, the universe and everything is:\n\n"+ output);
    
    

    calculator  with 2 EditText , TextView widgets and a Button with on click listener:
            final EditText value1 = (EditText) findViewById(R.id.value1);
            final EditText value2 = (EditText) findViewById(R.id.value2);
    
            final TextView result = (TextView) findViewById(R.id.result);
    
            Button addButton = (Button) findViewById(R.id.addValues);
            addButton.setOnClickListener(new OnClickListener() {
    
                public void onClick(View v) {
                    try {
                        int val1 = Integer.parseInt(value1.getText().toString());
                        int val2 = Integer.parseInt(value2.getText().toString());
    
                        Integer answer = val1 + val2;
                        result.setText(answer.toString());
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "Failed to add numbers", e);
                    }
                }
            });



    JUNIT Test of Layout
     LayoutTests extends ActivityInstrumentationTestCase2<MainActivity>
        public LayoutTests() {
            super("com.mamlambo.article.simplecalc", MainActivity.class);
        }
    
        protected void setUp() throws Exception {
            super.setUp();
    
            MainActivity mainActivity = getActivity();


    1 – Log.i(…, …) – Sends an INFO LogCat message
    2 – Log.d(…, …) – Sends a DEBUG LogCat message
    3 – Log.e(…, …) – Sends an ERROR LogCat message
    4 – Log.v(…, …) – Sends a VERBOSE LogCat message

    http://developer.android.com/reference/android/util/Log.html

    import android.util.Log

     private final String TAG = "TheAnswer";

     Log.i(TAG, "Printing the answer to life");


    settings custom locale:

    http://developer.android.com/training/basics/supporting-devices/languages.html

    values/ strings.xml
      <string name="hello_world">Hello world! My Name is David.</string>

    values-es/ strings.xml 


       <string name="hello_world">Hola Mundo! Me llamo es David!</string>
    layout/activity_main.xml:
    
    TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" 
    
    


    https://code.google.com/p/simple-calc-unit-testing/downloads/detail?name=FullCodeDownload.zip&can=2&q=

    3. The Getting to Know You Survey - This is only graded activity for the week. We'd like to get some information about you to help us know more about who you are, your background and your expectations for the course.
    http://help.coursera.org/customer/portal/articles/1329059-how-can-i-keep-track-of-course-deadlines-
    https://class.coursera.org/android-001/api/course/calendar

    Tuesday, September 30, 2014

    Polymer

    Polymer approach:
    Elements are pretty great. They’re the building blocks of the web. Unfortunately, as web apps got more complex, we collectively outgrew the basic set of elements that ships in browsers. Our solution was to replace markup with gobs of script. In that shift, we’ve lost the elegance of the element. Polymer returns to our roots. We think the answer is not gobs of script, but rather to build more powerful elements. A set of powerful new technologies called Web Components makes this possible.

    Custom Elements:
    Embracing the philosophy means a web app becomes a collection of well-defined, reusable components.




    Using Elements



    Creating Elements

    https://www.youtube.com/watch?v=5b5O5cclPbk (web components overview)

    - https://github.com/KamiQuasi/wc-overview
    - natively without polyfills



    Intro Polymer
    - easier to create custom elements
    - quiz application demo app w paper elements
    - inimation 60 frames / sec

    https://www.youtube.com/watch?v=3CJcHJGZfws (web components and polymer overview)



    http://www.polymer-project.org/resources/video.html




    http://www.polymer-project.org/docs/start/tutorial/intro.html
    http://www.html5rocks.com/en/tutorials/webcomponents/template/
    https://www.youtube.com/watch?v=eJZx9c6YL8k
    http://www.polymer-project.org/docs/polymer/polymer.html#altregistration
    http://www.polymer-project.org/docs/polymer/databinding.html
    http://www.polymer-project.org/docs/polymer/databinding-advanced.html#autobinding

    https://github.com/Polymer/observe-js

    Android information and devlopment resources

    The Android javadoc is great reference material:
    http://developer.android.com/reference/packages.html

    The Android Application components another important resource: 
    http://developer.android.com/guide/components/index.html

    The Android Welcome page
    http://developer.android.com/about/index.html

    The Android Open Source Project
    http://source.android.com/


    Linux Kernel: Standard services - Provides infrastructure mechanisms to manage mobile device resources
     •  Security
    •  Memory, process, & thread management
     • Network & File I/O
     • Device driver framework (pluggable devices)
    Android specific includes power management, Android Shared memory, low memory killer, Binder (Inter Process communication) , alarm driver, debugger, logger
    http://en.wikipedia.org/wiki/Android_(operating_system)#Linux_kernel


    Native System Libraries (C/C++ Native DK) core performance sensitive activities on device
    System C library - (std os system calls such as process/thread creation, memory allocation, mathemetical) bionic libc
    • Surface Manager  - (updating the display) display management
    • Media Framework  - (playback) audio/video streaming
    • FreeType  - library for rendering fonts
    • Webkit - (rendering and display web pages ) web browser engine
    • OpenGL ES, SGL - graphics engines
    • SQLite - relational database engine
    • SSL  - secure sockets layer
    http://developer.android.com/tools/sdk/ndk/index.html

    Runtime (part of System libraries layer)
    Davlik virtual machine executes the android apps, code written in java compiled into series of bytecode files , Davlik dx program transforms java classes into single Dex bytecode file  (classes.dex). File packaged with other resources and installed on device. Dalvik VM executes the Dex Bytecode file when invoked on device.
    Dalvik VM designed to be resource constrained environment with slower cpu, less memory, limited battery life
    http://en.wikipedia.org/wiki/Dalvik_(software)
    Core Libraries
    • Core Java classes (building blocks)
    • android.* (application lifecycle)
    • java.*, javax.* (data structures, concurrency, I/O)
    • junit.* (unit testing)
    • org.*  (internet/ web services)
    org.json.*, org.xml.*
    http://en.wikipedia.org/wiki/Comparison_of_Java_and_Android_API

    Application Framework - reusable software that many applications will need
    Package Manager  - Manages application packages on device such as info about apps
    Window Manager  - Manages top-level window’s look & behavior (notification bar, main application window, sub-menus/dialogs)
    View System  - common user interface elements such as Tabs, Lists, grids, text boxes, buttons, textview
    Resource Manager - Manages non-compiled code resources: strings, graphics, & layout filesContent Providers  - Inter-application data sharing (i.e. databases)
    Activity Manager - Application lifecycle & common navigation stack
    Telephony Manager - State of telephony services
    Location Manager - Access to system location services
    Notification Manager - Notify users when events occur
    https://sites.google.com/site/io/inside-the-android-application-framework

    Application - built in apps. Can substitute apps.
    Home, Contacts, Phone, Browser, Email

    Activity : Represents a single screen with a user interface (view user interface) - see Activity class
    activity lifecycle or http://developer.android.com/reference/android/app/Activity.html
    - Can be started by creating an Intent object & passing it to startActivity()
    - Parameters can be passed as “extras” to the Intent used to start the Service
    - Apps can have multiple Activities

    Service -operation in background, can bind to other services or Activities. For performing long-running operations or to access remote resources. Extends the Service class.
    Started Service – Often performs a single operation & usually doesn’t return a result to the caller directly
    Bound Service – Offers a client-server interface that allows components to interact with the Service
    http://developer.android.com/guide/components/services.html

    Content Provider - Manages a shared set of application data , Never accessed directly,
    but via a Content Resolver
    Consistent access to data (i.e. Rest, Crud operations)
    Data store backing options like SQLite, Web, File systems
    Can consume data from other content providers
    Extends the ContentProvider class
    http://developer.android.com/guide/topics/providers/content-providers.html

    Broadcast Receiver - A component that responds to system-wide Intent broadcast announcements
    - Supports complex Intent filtering
    - delivered asynchronously to all receivers
    Extends BroadcastReceiver class
    http://developer.android.com/reference/android/content/BroadcastReceiver.html

    Intents - messages (i.e. events) that link application components together
    http://developer.android.com/guide/components/intents-filters.html

    https://sites.google.com/site/io/anatomy--physiology-of-an-android


    ADT Bundle:
    latest android platform
    eclipse and ADT plugin
    latest image for emulator
    additional dev tools
    http://developer.android.com/sdk/index.html

    Emulator:
    network/speed latencies
    battery power
    location coordinates

    telnet localhost port# (i.e. 5554)

    slow network:
    network speed edge
    network speed full
    power capacity 5

    power status not-charging

    geo fix 0.0 40.0

    sms send 3015555555 "msg"

    call port number other emulator
    http://developer.android.com/tools/devices/emulator.html

    Davlik debug Monitor service (DDMS) perspective

    - file explorer
    - logcat
    - button in ddms to start and stop profiling at debug tracept

    Open perspective -> Hierarchy view





    http://developer.android.com/guide/index.html
    http://developer.android.com/training/index.html
    http://www.androiddevtools.com/
    http://www.dre.vanderbilt.edu/~schmidt/cs282/
    http://www.cs.swarthmore.edu/~aviv/classes/s13/cs71/
    http://www.cs.odu.edu/~cs495/
    http://www.vogella.com/tutorials/android.html
    http://www.cs.unibo.it/projects/android/2013/index.html#links
    http://liisp.uncc.edu/mbapps/
    http://www.stanford.edu/class/cs193a/
    http://cs76.tv/2012/spring/
    https://www.youtube.com/watch?v=RNaOWBBvAGo



    Thursday, September 25, 2014

    Web Components 101

    I recently watched Eric Bidelman's talk from Google I/O 2013 on Web Components.  This talk was on the Future of the web platform. This talk reminds me of Angular methodology where you are adding custom tags to HTML.

    4 main areas (Shadow DOM gives encapsulation, templates or chunk of markup that later you can stamp out your elements, custom tags, html imports that can be reused via CDN URLs):











    HTML templates:
    Template out your markup 
    Put dom in it
    Parsed not rendered - won't run until you stamp it out, same for media
    Hidden from document, cant traverse into,  its in its own context

    Content property - document fragment , clone it, stamp it out, see whats in it

    Example:


    Clone it is what stamps it out (here it runs script when that happens):











    New spec for html templates  : chrome supports it.




    Shadow dom (Secret markup in elements):
    markup encapsulation, DOM encapsulation, css style boundary protection, no bleeding in, style boundaries, exposes to developers mechanics browser vendors use to create their html elements

    iframe has it but bloated, hard to use  (extra network requests needed, multiple rendering contexts)











    Dom nodes can host hidden dom

    hidden dom  can't be accessed by outside  javscript


    Show shadow dom in web tools under wrench:







    Hidden document fragment

    Using markup to control it

    Browser vendors been holding out
















    Filled in markup

    Shadow dom gets rendered


    Style things

    This time add styling make it red











    @host

    Host element provide default styles




















    Custom elements (require hyphen)

    Ability to define new elements

    Plunkr example 





















































    Using js html.prototype 

























































    Html imports