Geofencing

GoogleAPIClient, GeoFence(Latitude, Longitude, Radius, Expiration)
ArrayList -> GeoFencingRequest (addGeoFences)

create a new App in Android Studio
add the services libraries to buildgradle
edit App.manifest to use the service libraries

edit layout.xml file
add an onClick Handler to this button
call it ‘addGeofencesButtonHandler’

create a GeoFenceTransitionsIntentService class extends IntentService
Add constructor and onCreate() overrides
create onHandleIntent override take Intent as parameter, return void

onHandleIntent(Intent intent) method
Get geofence data from the intent
check for Errors!

onHandleIntent(Intent intent) method
Get the transition type
1. for Enter
2. for Exit

List<Geofence> triggeringGeofences = geofencingEvent

write a sendNotification helper method it should take a string and send a notification with that string

public final class Constant {
	private Constants(){
	}
}

public static final HashMap<String, LatLng> BAY_AREA_LANDMARKS =
	new HashMap<String, LatLng();>
		static {}
private GeofencingRequest getGeofencingRequest(){
}

private PendingIntent getGeofencePendingIntent(){
	Intent intent = new Intent();
	return PendingIntent.getService();
}

Building onReceive()

Received a Context and an Intent
ArrayList
getParcelableArrayListExtra()
Iterate throught ArrayList
– getType() -DetectedActivity code
– getConfidence()

Setting up the Client
onStart()/ onStop()
onPause()
Get LocalBroadcastManager and Unregister our receiver
onResume()
Get LocalBroadcastManager and register our receiver
Use same IntentFilter name(BROADCAST_ACTION)

@Override
protected void onStart(){
	super.onStart();
	mGoogleApiClient.connect();
}

@Override
protected void onStop(){
	super.onStop();
	mGoogleApiClient.disconnect();
}

Implementing Buttons
requestActivityUpdatesButtonHandler
.requestActivityUpdates()
The API Client, Interval in ms
A Pending Intent – getActivityDetectionPendingIntent()
removeActivityUpdatesHandler
.removeActivityUpdates()
API Client & Pending Intent

Asynchronous Stuff

Using IntentService

Activity: StartService
onHandleIntent IntentService

package lmoroney.com.hogeactivity;

import android.app.IntentService;

public class DetectedActivitiesIntentService {
	protected statid final String TAG = "detection_is";
	public DetectedActivitiesIntentService(){
		// Use the TAG to name the worker thread.
		super(TAG);
	}
}

Get ActivityRecognitionResult
Use .getProbableActivities() to get Array
create a new Intent to send results
Add activities to Intent
Use a LocalBroadcastManager

Editing the Main Activity
on the class declaration
implement onConnectionCallbacks
and onConnectionFailedLsitener
Within the Class
Implement onConnected
Implement onConnectionSuspended
Implement onConnectionFailed

public class MainActivity extends ActionBarActivity
	implements GoogleApiClient.ConnectionCallbacks,
	GoogleApiClient.OnConnectionFailedListener {

	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public void onConnected(Bundle connectionHint){	
	}

	@Override
	public void onConnectionFailed(ConnectionResult result){
	}
}

The Receiver Class
class that extends BroadcastReceiver
works best as a nested class on MainActivity
Create ActivityDetectionBroadcastReciever
– make it nested
– extends BroadcastReceiver
– Override onReceive(Context, Intent

public class ActivityDetectionBroadcastReceiver extends BroadcastReceiver {
	protected static final String TAG = "receiver";

	public void onReceiver(Context context, Intent intent){
	
	}
}

Going deeper with location

Steps
1. specify using Google Services
2. Access fine location

To have connection callbacks
– implements ConnectionCallbacks, OnConnectionFailedListener

@Override
public void onConnected(Bundle bundle){
	super.onStart();
	mGoogleApiClient.connect();
}
@Override
protected void onStop(){
	super.onStop();
	if(mGoogleApiClient.isConnected()) {
		mGoogleApiClient.disconnected();
	}
}
@Override
protected void onConnected(Bundle connectionHint){
	mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
	if(mLastLocation!=null){
	 mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
	 mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
	}
}

Setting up
-create App
-edit the Layout
-Add String.xml
-Update Build.gradle and AnxdroidManifest.xml

Different Priority Values

setInterval(period);
mil second

PRIORITY_BALANCED_POWER_ACCURACY
PRIORITY_HIGH_ACCURACY
PRIORUTY_LOW_POWER
PRIORITY_NO_POWER

steps to use Location Services
1. create a GoogleApiClient
that uses the Location Services API
2. Extend activity with the GoogleApiClientConnectionCallbacks
callbacks
3. Extend activity with the GoogleApiClient.OnConnectionFailedListener
Listener in case the connection fails
4. Extend activity with the LocationListener
listener for lacation updates
5. After connecting the GoogleApiClient
wait for the onConnected
callback
6. In this callback, set up onLocationChanged
callback, and in this can capture location information

Getting Started with Location

Location Provider
– Fused Location Provider: GPS, Satellites, Cellular Connection, WiFi Network
– Activity Recognition:

Google Api Client
Location Services: GoogleApiClientConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener

OnConnected
OnLocationChanged

asynchronous programming

Fine and Coarse Location
Fine Location: GPS Cell and WiFi
Coarse Location: Cell and WiFi

in order to use the Google API Client
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener

@Override
protected void onStart()
	super.onStart();
	// Connect the Client
	mGoogleApiClient.connect();

@Override
protected void onStop()
	// Disconnect the Client
	mGoogleApiClient.disconnect();
	super.onStop();

Starting App

build.gradle
compile ‘com.google.android.gms:play-service:7+’

AndroidManifest.xml

<meta-data android:name="com.google.android.gms.version"
	android:value="@integer/google_play_services_version" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Asynchronous Programming Model
OnCreate, OnStart
Location Services
OnConnectionFailed, OnConnectionSuspended, OnConnected, OnLocationChanged

Asynchronous programming steps
1. create a GoogleApiClient that uses desired API
2. Extend activity with the ConnectionCallbacks
3. Extend activity with the OnConnectionFailedListener in case the connection fails
4. After connecting the GoogleApiClient wait for the onConnected callback
5. Follow the requirements of specific API

Groundwork

<title>My Website</title>
<div id="introduction">
	<p>
	welcome to my website!
	</p>
</div>
<div id="image-gallery">
	<p>
	This is my cat!
	<img src="cat.jpg" alt="Meow!">
	<a href="https://en.wikipedia.org/wiki/Cat">Learn more about cats!</a>
	</p>
</div>

while continue_crawl(search_history, target_url):
continue_crawl([‘https://en.wikipedia.org/wiki/Floating_point’], ‘https://en.wikipedia.org/wiki/Philosophy’)

def continue_crawl(search_history, target_url, max_steps=25):
	if search_history[-1] == target_url:
		print("We've found the target article!")
		return False
	elif len(search_history) > max_steps:
		print("The serach has gone on suspiciously long, aborting search!")
		return False
	elif search_history[-1] in search_history[:-1]:
		print("We've arrived at an article we've already seen, aborting search!")
		return False
	else:
		return True
import time
import urllib

import bs4
import requests

start_url = "https://en.wikipedia.org/wiki/Special:Random"
target_url = "https://en.wikipedia.org/wiki/Philosophy"

def find_first_link(url):
	response = requests.get(url)
	html = response.text
	soup = bs4.BeautifulSoup(html, "html.parser")

	content_div = soup.find(id="mw-content-text").find(class_="mw-parser-output")

	article_link = None

	for element in content_div.find_all("p", recursive=False):

		if element.find("a", recursive=False):
			article_link = element.find("a", recursive=False).get('href')

	if not article_link:
		return

	return first_link

def continue_crawl(search_history, target_url, max_steps=25):
	if search_history[-1] == target_url:
		print("We've found the target article!")
		return False
	elif len(search_history) > max_steps:
		print("The search has gone on suspiciously long, aborting search!")
		return False
	elif search_history[-1] in search_history[:-1]:
		print("We've arrived at an article we've already seen, aborting search!")
		return False
	else:
		return True

article_chain = [start_url]

while continue_crawl(article_chain, target_url):
	print(article_chain[-1])

	first_link = find_first_link(article_chain[-1])
	if not first_link:
		print("We've arrived at an article with no links, aborting search!")
		break

	article_chain.append(first_link)

	time.sleep(2)

Reading from a File

f = open('/my_path/my_file.txt', 'r')
with open('/my_path/my_file.txt', 'r') as f:
	file_data = f.read()

camelot_lines = []
with open("camelot.txt") as f:
	for line in f:
		camelot_lines.append(line.strip())

print(camelot_lines)
def create_cast_list(filename):
	cast_list = []
	with open(filename) as f:

		for line in f:
			line_data = line.split(',')
			cast_list.append(line_data[0])
		return cast_list

The Python Standard Library is organised into parts called modules. Many modules are simply Python files, like the Python scripts you’ve already used and written. In order to be able to use the code contained in a module we must import it, either in the interactive interpreter or in a Python script of our own.

The syntax for importing a module is simply import package_name.

>>> import math
>>> print(math.factorial(3))
6

from module_name import object_name
e.g.
from collections import defaultdict

>>> import multiprocessing as mp
>>> mp.cpu_count()
4

import an individual item from a module and give it a different name
from module_name import object_name as different_name
from csv import reader as csvreader

Python Standard Library
csv, collections, random, string, re, math, os, os.path, sys, json

word_file = “words.txt”
word_list = []

with open(word_file, ‘r’) as words:
for line in words:
word = line.strip().lower()
if 3 < len(word) < 8 word_list.append(word) [/python] [python] def generate_password(): return random.choice(word_list) + random.choice(word_list) + random.choice(word_list) def generate_password(): return str().join(random.sample(word_list,3)) [/python]

Tuple

>>> print(type(AngkorWat))

>>> print("Angkor wat is at latitude: {}".format(AngkorWat[0]))
Angkor wat is at latitude: 13.4125
>>> print("Angkor wat is at longitude: {}".format(AngkorWat[1]))
Angkor wat is at longitude: 103.866667
>>> dimensions = 52, 40, 100
>>> length, width, height = dimensions
>>> print("the dimensions are {}x{}x{}".format(length, width, height))
the dimensions are 52x40x100
world_heritage_locations = {(13.4125, 103.866667): "Angkor Wat",
						(25.73333, 32.6): "Ancident Thebes",
						(30.330556, 35.4433330): "Petra",
						(-13.116667, -72.583333): "Machu Picchu"}
def box(width, height, symbol):
	print(symbol * width)

	for _ in range(height-2):
		print(symbol + " " * (width-2) + symbol)

	print(symbol + width)
def print_list(l, numbered, bullet_character):
	for index, element in enumerate(l):
		if numbered:
			print("{}: {}".format(index+1, element))
		else:
			print("{} {}".format(bullet_character, element))

def word_count(document, search_term):
“”” Count how many times search_term appears in document. “””
words = document.split()
answer = 0
for word in words:
if word == search_term:
answer += 1
return answer

def nearest_square(limit):
“”” Find the largest square number smaller than limit.”””
answer = 0
while (answer+1)**2 < limit: answer += 1 return answer**2 [/python]