Hatena::ブログ(Diary)

万年素人からGeekへの道 このページをアンテナに追加 RSSフィード Twitter

□僕のAndroidアプリ □NGUI翻訳 □僕の翻訳した本 □僕のChrome拡張 □ひな祭りFacebookアプリ □タワーディフェンスゲーム! □お薦めアプリ

2012-05-05 Saturday このエントリーを含むブックマーク このエントリーのブックマークコメント

web2pyとFacebookでSocialGraph

Mining the Social Web by Matthew A. Russell, Copyright 2011 Matthew A. Russell, 978-1449388348』

から引用

・facebook__fql_query.py

依存モジュールコメントアウトした

# -*- coding: utf-8 -*-

import sys
from urllib import urlencode
import json
import urllib2
#from facebook__login import login #<=ここはコメントアウトした


class FQL(object):

    ENDPOINT = 'https://api.facebook.com/method/'

    def __init__(self, access_token=None):
        self.access_token = access_token

    def _fetch(cls, url, params=None):
        conn = urllib2.urlopen(url, data=urlencode(params))
        try:
            return json.loads(conn.read())
        finally:
            conn.close()

    def query(self, q):
        if q.strip().startswith('{'):
            return self.multiquery(q)
        else:
            params = dict(query=q, access_token=self.access_token, format='json')
            url = self.ENDPOINT + 'fql.query'
            return self._fetch(url, params=params)

    def multiquery(self, q): 
        params = dict(queries=q, access_token=self.access_token, format='json')
        url = self.ENDPOINT + 'fql.multiquery'
        return self._fetch(url, params=params)


# Sample usage...

if __name__ == '__main__':
    try:
        ACCESS_TOKEN = open('out/facebook.access_token').read()
        Q = sys.argv[1]
    except IOError, e:
        try:

            # If you pass in the access token from the Facebook app as a command line
            # parameter, be sure to wrap it in single quotes so that the shell
            # doesn't interpret any characters in it. You may also need to escape-
            # the # character

            ACCESS_TOKEN = sys.argv[1]
            Q = sys.argv[2]
        except IndexError, e:
            print >> sys.stderr, \
                "Could not either find access token in 'facebook.access_token' or parse args."
            ACCESS_TOKEN = login()
            Q = sys.argv[1]

    fql = FQL(access_token=ACCESS_TOKEN)
    result = fql.query(Q)
    print json.dumps(result, indent=4)

↑これでFQLをつかえるように拝借した。

web2py/site-packages/に入れた。

お次は

・models/db.py

class FaceBookAccount(OAuthAccount):
    """OAuth impl for FaceBook"""
    YOUR_CLIENT_ID = os.environ.get('FB_ID', "default")
    YOUR_CLIENT_SECRET = os.environ.get('FB_SECRET', "default")
    AUTH_URL="https://graph.facebook.com/oauth/authorize"
    TOKEN_URL="https://graph.facebook.com/oauth/access_token"
    def __init__(self, g): 
        OAuthAccount.__init__(self, g,
                              self.YOUR_CLIENT_ID,
                              self.YOUR_CLIENT_SECRET,
                              self.AUTH_URL,
                              self.TOKEN_URL)
        self.graph = None
    # override function that fetches user info
    def get_user(self):
        "Returns the user using the Graph API"
        if not self.accessToken():
            return None
        if not self.graph:
            self.graph = GraphAPI((self.accessToken()))
            # get global access token(ここでアクセストークンを入れる)
            session.access_token = self.accessToken()
        try:
            user = self.graph.get_object("me")
            return dict(first_name = user['first_name'],
                        last_name = user['last_name'],
                        username = user['id'])
        except GraphAPIError:
            self.session.token = None
            self.graph = None
            return None
## use the above class to build a new login form
auth.settings.login_form=FaceBookAccount(globals())
auth.settings.registration_requires_verification = False
auth.settings.actions_disabled = ['change_password', 'request_reset_password', 'retrieve_username', 'register']

・controllers/test.py

ここでfacebook__fql_queryをインポートして使う

from facebook__fql_query import FQL
def index():
    q = "select target_id form connection where source_id = me() and target_type = 'user'"
    fql = FQL(session.access_token)
    my_friends = [str(t['target_id']) for t in fql.query(q)]
    return dict(my_friends=my_friends)

・views/test/index.html

{{extend 'layout.html'}}
{{for my_friend in my_friends:}}<div>{{=my_friend}}</div>{{pass}}

f:id:shinriyo:20120505182230p:image

↑のエラー・・・


しかたないので、「my_friends」をコメントアウトしてビューに出ししてみる

・controllers/test.py

from facebook__fql_query import FQL 

def index():
    q = "select target_id form connection where source_id = me() and target_type = 'user'"
    my_access_token = session.access_token #<=これがあるのか?
    fql = FQL(session.access_token)
    #my_friends = [str(t['target_id']) for t in fql.query(q)]
    #return dict(my_friends=my_friends)
    return dict(my_access_token=my_access_token)

こうした

・views/test/index.html

{{extend 'layout.html'}}
<h2>アクセストークンを表示</h2>
{{=my_access_token}}

ブラウザには「None」・・・

f:id:shinriyo:20120505182123p:image

web2py画面の項目に直接sessionの値を設定する

コントローラ

グローバル変数のsession.test

def display_form():
    form=FORM('Your name:',
              INPUT(_type='text', _name='test', _value=session.test),
              INPUT(_type='submit'))

XCodeVIMプラグイン

http://www.corsofamily.net

・説明

http://www.corsofamily.net/jcorso/vi/#download

・まずはフォルダ作る sudoやらないとだめ

sudo mkdir /Library/InputManagers

ダウンロードして解凍した「ViInputManager」を移動

sudo mv ViInputManager-v0.3.2/ViInputManager/ /Library/InputManagers/

・ViInputManagerを実行可能にしない

※フルパスだとこうなる。公式の説明には「Contents」がないので注意。

chmod a-x /Library/InputManagers/ViInputManager/ViInputManager.bundle/Contents/MacOS/ViInputManager 

・DefaultKeyBinding.dicをホームの「~/Library/KeyBindings/」のなかへ

mkdir ~/Library/KeyBindings/
 mv ViInputManager-v0.3.2/DefaultKeyBinding.dict ~/Library/KeyBindings/

動かない・・

こちらの日本語の説明を見たが、ログインログアウトが必要かも?

http://groundwalker.com/blog/2007/06/mac_vi_input_manager_plugin.html

メモ:「Emacs実践入門」技術評論社

まず入ってるバージョンMacOSXでやった)

emacs -version
Last login: Fri May  4 21:03:22 on ttys002
shinriyo:emacs-23.4 shinriyo$ emacs -version
GNU Emacs 22.1.1
Copyright (C) 2007 Free Software Foundation, Inc.
GNU Emacs comes with ABSOLUTELY NO WARRANTY.
You may redistribute copies of Emacs
under the terms of the GNU General Public License.
For more information about these matters, see the file named COPYING.

GUIなしのインストール

curl -O http://ftp.gnu.org/pub/gnu/emacs/emacs-23.4.tar.gz
tar vxf emacs-23.4.tar.gz 
cd cd emacs-23.4
./configure --without-x
make
sudo make install

cocos2d-xのシューティングチュートリアル

http://www.raywenderlich.com/11338/cocos2d-x-for-ios-and-android-space-game

「space game resources ZIP file」って書いてるとこからZIPを落として中身をXCodeへ。

「Classes\HelloWorldScene.h」を開いて

private:
	cocos2d::CCSpriteBatchNode * _batchNode;
	cocos2d::CCSprite * _ship;

を追加

class HelloWorld : public cocos2d::CCLayer
{
public:
	// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
	virtual bool init();  
	// there's no 'id' in cpp, so we recommand to return the exactly class pointer
	static cocos2d::CCScene* scene();

	// a selector callback
	virtual void menuCloseCallback(CCObject* pSender);
	// implement the "static node()" method manually
	LAYER_NODE_FUNC(HelloWorld);
private:
	cocos2d::CCSpriteBatchNode * _batchNode;
	cocos2d::CCSprite * _ship;
};

「HelloWorldScene.cpp」を開いてinit()メソッド中の2のコメントの中身消してこうする

「 3. add your codes below.」は消してもいいが、消さなくてもどうせreturnされる

※「HelloWorldScene.cpp」は先程の「HelloWorldScene.h」を開いた状態で「crtol+command+↑」もOK

bool HelloWorld::init()
{
	//////////////////////////////
	// 1. super init first
	if ( !CCLayer::init() )
	{
		return false;
	}

	/////////////////////////////
	// 2. add a menu item with "X" image, which is clicked to quit the program
	//    you may modify it.
    _batchNode = CCSpriteBatchNode::batchNodeWithFile("Sprites.pvr.ccz");
    this->addChild(_batchNode);
    CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Sprites.plist");
    
    _ship = CCSprite::spriteWithSpriteFrameName("SpaceFlier_sm_1.png");
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    _ship->setPosition(ccp(winSize.width * 0.1, winSize.height * 0.5));
    _batchNode->addChild(_ship, 1);
    return true;

・HelloWorldScene.hのクラス定義の前へ「USING_NS_CC;」を記載

USING_NS_CC;

class HelloWorld : public cocos2d::CCLayer
{

さらに「private:」に「CCParallaxNode」「CCSprite」型のそれぞれの追加

private:
	cocos2d::CCSpriteBatchNode * _batchNode;
	cocos2d::CCSprite * _ship;
    CCParallaxNode *_backgroundNode;  
    CCSprite *_spacedust1;
    CCSprite *_spacedust2;
    CCSprite *_planetsunrise;
    CCSprite *_galaxy;
    CCSprite *_spacialanomaly;
    CCSprite *_spacialanomaly2;

Thread1 signal: "SIGABRT"

※.xibファイルとの紐付けがおかし場合に出る。