ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

翻訳されている本ってなんか読みづらくね?

俺だけかね?(´・ω・`)

なんかすごく読みづらい。

しっかり読んだら理解できるけど、速読ができない。一度よくわからないことを放っておいたら、そのあとはもう頭のなかに入ってこない。

日本人が書いた本はすぐ読める。1時間から2時間ぐらいで読める。

が、今下の本を読んでいるんだけど。全然進まない。技術書はジャンルのせいでもあると思うけど。

入門 機械学習

入門 機械学習

How Google Works (ハウ・グーグル・ワークス)  ―私たちの働き方とマネジメント

How Google Works (ハウ・グーグル・ワークス) ―私たちの働き方とマネジメント

面白くないわけではない。すごく面白いんだけど、理解するのに時間がかかる -> 何度も読み返さないと(何故か)理解できない。

うーん。1週間に1冊のペースはまだまだかねー。

iPythonからRを実行する

今Jupyterって名前らしい。

iPythonからRが実行できるということを聞いたので、試してみる。

その時のメモ

これはRのコンソールから

install.packages(c('rzmq','repr','IRkernel','IRdisplay'),
  repos = c('http://irkernel.github.io/', getOption('repos')))

interface.cpp:22:10: fatal error: 'zmq.h' file not found
#include <zmq.h>
         ^
1 error generated.
make: *** [interface.o] Error 1
ERROR: compilation failed for package ‘rzmq’
* removing ‘/usr/local/lib/R/3.2/site-library/rzmq’

なんか入っていないから実行できないっぽい。

macのコンソールからインストール

$ brew install czmq zmq

またRのコンソールから実行

IRkernel::installspec()
 IRkernel::installspec() でエラー: 
  Jupyter or IPython 3.0 has to be installed but could neither run “jupyter” nor “ipython”, “ipython2” or “ipython3”.
             (Note that “ipython2” is just IPython for Python 2, but still may be IPython 3.0)

うむむ。。。

install.packages('devtools')

...
ERROR: dependency ‘xml2’ is not available for package ‘rversions’
* removing ‘/usr/local/lib/R/3.2/site-library/rversions’
ERROR: dependency ‘rversions’ is not available for package ‘devtools’
* removing ‘/usr/local/lib/R/3.2/site-library/devtools’

macコンソールからから実行

$ brew install xml2

もっかい

Error in dyn.load(file, DLLpath = DLLpath, ...) : 
   共有ライブラリ '/usr/local/lib/R/3.2/site-library/xml2/libs/xml2.so' を読み込めません: 
  dlopen(/usr/local/lib/R/3.2/site-library/xml2/libs/xml2.so, 6): Library not loaded: libxml2.2.dylib
  Referenced from: /usr/local/lib/R/3.2/site-library/xml2/libs/xml2.so
  Reason: image not found 
 エラー:  ロードに失敗しました 
 実行が停止されました 
ERROR: loading failed

(´;ω;`)ブワッ

調べてみる。

stackoverflow.com

あった。

$ pkg-config --libs --cflags  libxml2
Package libxml2 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libxml2.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libxml2' found

なんもない。じゃあインストール。

$ brew install libxml2

はいった!

もっかい

Error in dyn.load(file, DLLpath = DLLpath, ...) : 
   共有ライブラリ '/usr/local/lib/R/3.2/site-library/xml2/libs/xml2.so' を読み込めません: 
  dlopen(/usr/local/lib/R/3.2/site-library/xml2/libs/xml2.so, 6): Library not loaded: libxml2.2.dylib
  Referenced from: /usr/local/lib/R/3.2/site-library/xml2/libs/xml2.so
  Reason: image not found 
 エラー:  ロードに失敗しました 
 実行が停止されました 
ERROR: loading failed

not changed^q^

泣きそうなところを下記サイトに助けられました。

www.perfectlyrandom.org

やったこと

https://cran.r-project.org/web/packages/xml2/index.html

このサイトから、xml2のソースを取得する。

下記リンク(リンク切れになるかもしれませんので、本元から取得ください)

https://cran.r-project.org/src/contrib/xml2_0.1.2.tar.gz

んで、ダウンロードしたtar.gzのファイルを解答して、サイトの「SOLUTION 1」と「SOLUTION 2」を対応する。configureファイルを書き換えて、ビルドする。

んで、圧縮ファイルができるので、それをRコンソールから読み込む。

install.packages("xml2_0.1.2.tar.gz", repos=NULL, type="source")

それで、もっかいdevtoolsを読みだす。

install.packages('devtools')

...

*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded
* DONE (devtools)

やったーヾ(´∀`)ノキャッキャ

> IRkernel::installspec()
 IRkernel::installspec() でエラー: 
  Jupyter or IPython 3.0 has to be installed but could neither run “jupyter” nor “ipython”, “ipython2” or “ipython3”.
             (Note that “ipython2” is just IPython for Python 2, but still may be IPython 3.0)

(・ω・)

(やめようかな。。。)

あきらめようとしていたそのとき。

RをIPython Notebookから使う

この通りにやったらできました。。。なんだったんだろう。。。。

英単語勉強その3

conscious

意識している、意識的な、意識のある

phishing attacks

(ITの攻撃手法)フィッシングの事

come with

関連する

grievous

悲痛な、重大な、危険な、危ない

offender

犯罪者、違反者、不法行為

rake

読み流す、拾い読みする、拾読みする

rather

どちらかと言えば、相当に、いくぶん

innocuous

無害の、退屈な、罪のない、無害な、差し障りのない

assume

想定する、決めてかかる、思い込む、(責任を)取る、~と仮定する、推測する、仮定する、取る、考える、推定する、引き受ける、得る、見なす、決め込む、帯びる

【Python3】GPXファイルジェネレータ

d.hatena.ne.jp

こちらの方が作成したスクリプトをpython3にしました。ソースお借りいたしますm(_ _ )m

Forkしたかったけどgistの使い方がよくわからない。。。

#
# python drive.py "origin" ["waypoint" ... ] "destination"
#
# i.e. python drive.py "Union Square, San Francisco" "Ferry Building, San Francisco" 'Bay Bridge' SFO

import sys, json, os.path, pprint
from hashlib import md5
from urllib.request import urlopen
from math import radians, sin, cos, atan2, pow, sqrt
from urllib.parse import quote_plus
from xml.sax.saxutils import escape
from optparse import OptionParser

parser = OptionParser("Usage: %prog [options] origin [waypoint ...] destination")
parser.add_option(
  "--cache",
  dest="cache",
  help="cache the result of query for Google into DIR",
  metavar="DIR")

(options, args) = parser.parse_args()

if len(args) < 2:
  parser.error("incorrect number of arguments")

def urlForDirection(args):
  origin = args[0]
  destination = args[-1]

  url = "http://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&sensor=false"
  url = url % (quote_plus(origin), quote_plus(destination))

  if len(args) > 2:
    url += '&waypoints=' + quote_plus('|'.join(args[1:-1]))

  return url

def cachePath(url):
  return options.cache + '/' + md5.new(url).hexdigest() + '.drive'


def fetchDirection(url):
  data = None
  cache_path = None
  fetched = False

  if options.cache:
    cache_path = cachePath(url)
    if os.path.isfile(cache_path):
      with file(cache_path, 'r') as fp:
        data = json.load(fp)

  if not data:
    fp = urlopen(url)
    content = fp.read().decode('utf8')
    data = json.loads(content)
    fetched = True

  if options.cache and fetched:
    fp = file(cache_path, 'w')
    json.dump(data, fp)
    fp.close()

  if data.get('status') != 'OK':
    error('Bad data')

  route = data['routes'][0]
  return route['legs']

def namedWaypoint(coordinate, name):
  print('\t<wpt lat="%(lat).6f" lon="%(lng).6f">' % coordinate)
  print('\t\t<name>%s</name>' % escape(name))
  print('\t</wpt>')

def waypoint(coordinate):
  print('\t<wpt lat="%(lat).6f" lon="%(lng).6f"/>' % coordinate)

def decodePoly(pts):
  step1 = [ord(x) - 63 for x in pts]

  step2, vals = [], []
  for val in step1:
    vals.insert(0, val & 0x1f)
    if val < 0x20:
      val = 0
      for n in vals:
        val = (val << 5) + n
      if val % 2: val = ~(val - 1)
      val /= 2.0
      val /= 100000.0

      step2.append(val)
      vals = []

  step3 = []
  for lat, lng in zip(step2[0::2], step2[1::2]):
    if len(step3) > 0:
      lat += step3[-1]['lat']
      lng += step3[-1]['lng']
    step3.append({'lat':lat, 'lng':lng})

  return step3

def distanceBetweenPoints(a, b):
  lat1 = radians(a['lat'])
  lng1 = radians(a['lng'])
  lat2 = radians(b['lat'])
  lng2 = radians(b['lng'])

  R = 6371.0 * 1000 # radius of earth by km

  a = pow(sin((lat1 - lat2) / 2.0), 2) + pow(sin((lng1 - lng2) / 2.0), 2) * cos(lat1) * cos(lat2)

  c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a))

  return R * c # / 1.6 * 5280.0 # to mile, then to feet

def complementPoints(points, duration, distance):
  result = []

  for a, b in zip(points[0:-1], points[1:]):
    dd = distanceBetweenPoints(a, b)
    dt = duration * (dd / distance)

    t = 0.0
    lat = b['lat'] - a['lat']
    lng = b['lng'] - a['lng']
    while t < dt:
      r = t / dt
      pt = {'lat': a['lat'] + lat * r, 'lng': a['lng'] + lng * r}
      result.append(pt)
      t += 5

  result.append(points[-1])

  return result

def printGPX(legs):
  print('<?xml version="1.0"?>')
  print('<gpx version="1.1" creator="drive.py coded by basuke">')

  namedWaypoint(legs[0]['start_location'], legs[0]['start_address'])

  for leg in legs:
    for step in leg['steps']:
      start = step['start_location']
      end = step['end_location']
      duration = step['duration']['value']
      distance = step['distance']['value']

      decodePoly(step['polyline']['points'])
      points = decodePoly(step['polyline']['points'])
      points.insert(0, start)
      points.append(end)

      points = complementPoints(points, duration, distance)
      for pt in points:
        waypoint(pt)

    namedWaypoint(leg['end_location'], leg['end_address'])

  print('</gpx>')

url = urlForDirection(args)
legs = fetchDirection(url)
printGPX(legs)

ほとんど変更していません。

  • print -> print()
  • urllib2 -> urllib.request
  • md5 -> from hashlib import md5
  • json.load -> json.loads

ぐらいですかねー。