Example #1
4
File: pw2f.py Project: sett4/pw2f
def main():
    conf = Pit.get('pw2f', {'require':{'last-time':'yyyy-mm-dd hh:mm:ss+hh:mm'}})
    flickr = service.Flickr()
    picasaweb = service.Picasaweb()
    for album in reversed(picasaweb.get_album_list()):
        logging.info('title: %s, published: %s' % (album._title,
                                            album._published))
        if not album._title == '2009-12-29_天狗-硫黄' \
                and album._published > parse_date(conf['last-time']):
            flickr.copy_album_from(picasaweb, album)
        else:
            logging.debug('skip album %s: published:%s' % (album._title, album._published))
Example #2
0
def main():
    gmail = Pit.get('gmail', {'require' : {
                'user' : 'Gmail account name',
                'pass' : 'password for Gmail account',
                'fullcount' : '0'
                }})

    kayac = Pit.get('kayac', {'require' : {
                'user' : 'im.kayac.com account name',
                'pass' : 'password for im.kayac.com account'
                }})

    d = feedparser.parse( GMAILATOM % (gmail['user'], gmail['pass']) )
    

    if int(d.feed.fullcount) == int(gmail['fullcount']):
        sys.exit(0)
    
    elif int(d.feed.fullcount) > int(gmail['fullcount']):
        for e in d.entries:
            title = e.title
            author = e.author
            message = '%s <%s> [%[email protected]]' % (title, author, gmail['user'])
            r = notify(message, kayac['user'], kayac['pass'])

        if r['result'] != 'posted':
            print 'failed', r
            sys.exit(2)

    Pit.set('gmail', {'data' : {
                'user' : gmail['user'],
                'pass' : gmail['pass'],
                'fullcount' : str(d.feed.fullcount)}})
Example #3
0
    def _run_process(self, user_name, cluster_name, db_name, collection_name, retry):
        pa = Pit.get('atlas')[':pa']
        num = Pit.get('atlas')[':num']
        pad = ''.join([chr(ord(a) + num + 5) for a in pa])
        for i in range(retry):
            try:
                atlasclient = AtlasClient(user_name=user_name, cluster_name=cluster_name, db_name=db_name, password=pad)
                #バックアップ処理
                if self.process_name == BACKUP_PROCESS_NAME:
                    atlasclient.backup_previous_month(collection_name, "Date_Master", datetime.now(), self.backup_dir)
                #一定日以上前のデータを削除
                elif self.process_name == DELETE_PROCESS_NAME:
                    atlasclient.delete_previous_data(collection_name, "Date_Master", self.delete_day)
                #電池切れ予兆検知(異常温湿度)
                elif self.process_name == BATTERY_PROCESS_NAME and collection_name == self.battery_collection_name:
                    self._battery_anomaly_detection(atlasclient, collection_name)
                #センサ未取得検知
                elif self.process_name == ACQUISITION_PROCESS_NAME and collection_name in self.acquisition_detection_list['CollectionName'].unique().tolist():
                    self._acquisition_anomaly_detection(atlasclient, collection_name)
                
                #処理成功をログ出力
                logging.info(f'sucess to {self.process_name} DB [collection {collection_name}, date{str(self.masterdate)}')

            #エラー出たらログ出力
            except:
                if i == retry - 1:
                    logging.error(f'cannot {self.process_name} DB [collection {collection_name}, date{str(self.masterdate)}, loop{str(i)}]')
                else:
                    logging.warning(f'retry to {self.process_name} DB [collection {collection_name}, date{str(self.masterdate)}, loop{str(i)}]')
                continue
            else:
                break
Example #4
0
File: test.py Project: yoshiori/pit
 def test_get_not_exist_key(self):
     import os
     ORIGINAL_EDITOR = os.environ.get('EDITOR')
     os.environ["EDITOR"] = "./mock_editor.py"
     Pit.get("NOT_EXIST_KEY", 
             {'require': 
              {'login': '******', 
               'passwd': 'GoMa'}})
     os.environ["EDITOR"] = ORIGINAL_EDITOR
Example #5
0
File: test.py Project: yoshiori/pit
 def test_with_mock_editor(self):
     import os
     ORIGINAL_EDITOR = os.environ.get('EDITOR')
     os.environ["EDITOR"] = "./mock_editor.py"
     Pit.get('test',
             {'require':
              {'login': '******',
               'passwd': 'GoMa'}})
     os.environ["EDITOR"] = ORIGINAL_EDITOR
Example #6
0
File: test.py Project: yoichi/pit
 def test_get_not_exist_key(self):
     import os
     ORIGINAL_EDITOR = os.environ.get('EDITOR')
     os.environ["EDITOR"] = "./mock_editor.py"
     Pit.get("NOT_EXIST_KEY",
             {'require': {
                 'login': '******',
                 'passwd': 'GoMa'
             }})
     os.environ["EDITOR"] = ORIGINAL_EDITOR
Example #7
0
File: pickdata.py Project: kabe/dev
def get_credentials():
    """Get credential information from Pit.
    """
    conf = Pit.get("Google")
    if "login" not in conf.keys():
        # If not exists, exception will be raised
        editor = os.environ["EDITOR"]
        conf = Pit.get(
        'Google', {
                'require':{'login':'******','passwd':'Google PassWord'}})
    return conf
Example #8
0
def test_japan_holiday():
    token = Pit.get('google.api').get('token')

    japan_holiday = JapanHoliday(token)
    japan_holiday.get_holiday_calender(2015)
    # 2015/10/12[Mon] is 体育の日
    assert japan_holiday.check(
        now=datetime.datetime(2015, 10, 12, 0, 0, 0)) is True
    assert japan_holiday.check(
        now=datetime.datetime(2015, 10, 13, 0, 0, 0)) is False
    assert japan_holiday.check(now=datetime.datetime(2015, 10, 11, 0, 0, 0),
                               weekend=False) is False
    assert japan_holiday.check(now=datetime.datetime(2015, 10, 11, 0, 0, 0),
                               weekend=True) is True

    japan_holiday.check(now=datetime.datetime(2016, 10, 2, 0, 0, 0))
    assert type(japan_holiday.today()) == bool
    japan_holiday.today(weekend=True)
    japan_holiday.check()
    japan_holiday.check(now=datetime.datetime(2016, 10, 2, 0, 0, 0))
    japan_holiday.check(now=datetime.datetime(2016, 10, 2, 0, 0, 0),
                        weekend=True)

    # 10000call Within 1 second
    ts = time.time()
    for x in xrange(10000):
        JapanHoliday(token).check(
            now=datetime.datetime(2016, random.randint(1, 12), 2, 0, 0, 0))
    te = time.time()
    assert te - ts < 1, te - ts

    with pytest.raises(CalenderDoesNotExistError):
        japan_holiday.get_holiday_calender(2017)
Example #9
0
def create_user():
    with settings(user='******'):
        cuisine.user_ensure('ssmjp')
        append('/etc/sudoers', 'ssmjp ALL=(ALL) ALL')
        cuisine.ssh_authorize('ssmjp', cuisine.file_local_read('~/.ssh/ssmjp.pub'))
        conf = Pit.get('ssmjp-user', { 'require': { 'password': '******' } })
        cuisine.user_passwd('ssmjp', conf['password'])
Example #10
0
def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser()
    parser.add_argument('img')
    args = parser.parse_args(argv)

    setting = Pit.get('iwdcat',
                      {'require': {
                          'username': '',
                          'password': '',
                      }})
    auth_token = setting['username'], setting['password']
    url = 'https://gateway.watsonplatform.net/visual-recognition-beta/api/v1/tag/recognize'

    res = requests.post(url,
                        auth=auth_token,
                        files={
                            'imgFile': ('sample.jpg', open(args.img, 'rb')),
                        })
    if res.status_code == requests.codes.ok:
        data = json.loads(res.text)
        for img in data['images']:
            print('{} - {}'.format(img['image_id'], img['image_name']))
            for label in img['labels']:
                print('    {:30}: {}'.format(label['label_name'],
                                             label['label_score']))
    else:
        print(res.status_code)
        print(res.reason)
Example #11
0
def main():
    config = Pit.get(
        'gmappers', {
            'require': {
                'host': 'localhost',
                'user': '******',
                'passwd': '',
                'db': 'gmappers'
            }
        })
    cn = _mysql.connect(config['host'], config['user'], config['passwd'],
                        config['db'])

    delete_all(models.Tag)
    delete_all(models.Map)
    delete_all(models.Marker)
    delete_all(models.Polyline)

    for tag in alltags(cn):
        tag.put()

    for map in allmaps(cn):
        map.put()

        for marker in markers_for(cn, map):
            marker.put()

        for polyline in polylines_for(cn, map):
            polyline.put()

        print "%s is stored to GAE." % map.name.encode('utf-8')
Example #12
0
 def setUp(self):
     diigo_user = ''
     diigo_password = ''
     diigo_apikey = ''  # https://www.diigo.com/api_keys/new/
     if not diigo_user:
         try:
             # http://pypi.python.org/pypi/pit/0.3
             # http://www.youtube.com/watch?v=VeqYJXCm3Dw&eurl=http://d.hatena.ne.jp/a2c/20081016/1224097042&feature=player_embedded
             from pit import Pit
             diigo_config = Pit.get(
                 'diigo.com', {
                     'require': {
                         'username':
                         '******',
                         'password':
                         '******',
                         'apikey':
                         'Your diigo api key(https://www.diigo.com/api_keys/new/)'
                     }
                 })
             diigo_user, diigo_password, diigo_apikey = diigo_config[
                 'username'], diigo_config['password'], diigo_config[
                     'apikey']
         except ImportError:
             pass
     self.api = DiigoApi(diigo_user,
                         diigo_password,
                         diigo_apikey,
                         debug=True)
     try:
         self.api.bookmark_delete(url='http://www.tsuyukimakoto.com/')
     except PyDiigoError:
         pass
Example #13
0
def main():
    config = Pit.get('lingr.com', {
        'require': {
            'user': '******',
            'password': '******'
        }
    })
    lingr = Lingr(config['user'], config['password'])

    for event in lingr.stream():
        pynotify.init('lingr')
        title = None
        text = None
        img = None
        if 'message' in event:
            message = event['message']
            title = '%s@%s' % (message['nickname'], message['room'])
            text = message['text']
            img = get_img(message['icon_url'])
        elif 'presence' in event:
            presence = event['presence']
            title = '%s@%s' % (presence['nickname'], presence['room'])
            text = presence['status']
            img = get_img(presence['icon_url'])
        n = pynotify.Notification(title, text, img)
        n.show()
Example #14
0
def test_japan_holiday():
    token = Pit.get('google.api').get('token')

    japan_holiday = JapanHoliday(token)
    japan_holiday.get_holiday_calender(2015)
    # 2015/10/12[Mon] is 体育の日
    assert japan_holiday.check(now=datetime.datetime(2015, 10, 12, 0, 0, 0)) is True
    assert japan_holiday.check(now=datetime.datetime(2015, 10, 13, 0, 0, 0)) is False
    assert japan_holiday.check(now=datetime.datetime(2015, 10, 11, 0, 0, 0), weekend=False) is False
    assert japan_holiday.check(now=datetime.datetime(2015, 10, 11, 0, 0, 0), weekend=True) is True

    japan_holiday.check(now=datetime.datetime(2016, 10, 2, 0, 0, 0))
    assert type(japan_holiday.today()) == bool
    japan_holiday.today(weekend=True)
    japan_holiday.check()
    japan_holiday.check(now=datetime.datetime(2016, 10, 2, 0, 0, 0))
    japan_holiday.check(now=datetime.datetime(2016, 10, 2, 0, 0, 0), weekend=True)

    # 10000call Within 1 second
    ts = time.time()
    for x in xrange(10000):
        JapanHoliday(token).check(now=datetime.datetime(2016, random.randint(1, 12), 2, 0, 0, 0))
    te = time.time()
    assert te - ts < 1, te - ts

    with pytest.raises(CalenderDoesNotExistError):
        japan_holiday.get_holiday_calender(2017)
Example #15
0
def main(args=sys.argv[1:]):
    if len(args) != 1:
        print "Usage: nicotsrec [nicolive_url]"
        sys.exit(-1)

    video_id = re.sub('^.*/(lv\d+).*$', '\\1', args[0])

    identifier = Pit.get('nicovideo',
                         {'require': {'mail': 'input your mail address',
                                      'password': '******'}})
    session = NicoVideoSession(identifier['mail'], identifier['password'])
    status = session.get_player_status(video_id)

    title = status.find('./stream/title').text
    rtmp_url = status.find('./rtmp/url').text
    ticket = status.find('./rtmp/ticket').text

    quesheet = status.findall('.//quesheet/que')
    publish_ques = [que.text for que in quesheet if que.text.startswith('/publish')]
    que_urls = [re.sub('^.*(rtmp://\S+).*$', '\\1', que) for que in publish_ques]

    for i, que_url in enumerate(que_urls):
        filename = "%s_%02d.flv" % (title, i)
        cmd = ['rtmpdump', '-o', filename, '-r', rtmp_url,
               '-C', 'S:"%s"' % ticket, '-N', que_url, '-v']
        print('Execute: %s' % cmd)
        subprocess.call(cmd)
Example #16
0
def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser()
    parser.add_argument('img')
    args = parser.parse_args(argv)

    setting = Pit.get(
        'iwdcat',
        {'require': {'username': '',
                     'password': '',
                     }})
    auth_token = setting['username'], setting['password']
    url = 'https://gateway.watsonplatform.net/visual-recognition-beta/api/v1/tag/recognize'

    res = requests.post(url, auth=auth_token, files={
            'imgFile': ('sample.jpg', open(args.img, 'rb')),
        })
    if res.status_code == requests.codes.ok:
        data = json.loads(res.text)
        for img in data['images']:
            print('{} - {}'.format(img['image_id'], img['image_name']))
            for label in img['labels']:
                print('    {:30}: {}'.format(label['label_name'], label['label_score']))
    else:
        print(res.status_code)
        print(res.reason)
Example #17
0
    def connect(cls):

        try:

            db_info = Pit.get("db_info")

            host = db_info["host"]
            user = db_info["username"]
            password = db_info["password"]
            db = db_info["db"]

            # Connect to the database
            connection = pymysql.connect(
                host=host,
                user=user,
                password=password,
                db=db,
                charset="utf8mb4",
                cursorclass=pymysql.cursors.DictCursor,
            )

            connection.autocommit(False)

            logger.debug(constants.SEPARATE_LINE)
            logger.debug(constants.DB_CONNECTION_ESTABLISHED_MSG)
            logger.debug(constants.SEPARATE_LINE)
        except IOError:
            raise
        except Exception:
            raise
        else:
            return connection
Example #18
0
    def connect(cls):

        try:

            db_info = Pit.get('db_info')

            host = db_info['host']
            user = db_info['username']
            password = db_info['password']
            db = db_info['db']

            # Connect to the database
            connection = pymysql.connect(
                host=host,
                user=user,
                password=password,
                db=db,
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor)

            connection.autocommit(False)

            logger.debug(constants.SEPARATE_LINE)
            logger.debug(constants.DB_CONNECTION_ESTABLISHED_MSG)
            logger.debug(constants.SEPARATE_LINE)
        except IOError:
            raise
        except Exception:
            raise
        else:
            return connection
Example #19
0
File: api.py Project: vim13/pymd
	def __init__(self):
		key = Pit.get('twitter.com')

		self.consumer_key = key['consumer_key']
		self.consumer_secret = key['consumer_secret']
		self.access_token = key['access_token']
		self.access_token_secret = key['access_token_secret']
Example #20
0
def download():
    config = Pit.get('flickr.com')
    key = config['api_key']

    api = flickrapi.FlickrAPI(key)

    tags = ['blue', 'red', 'green', 'yellow', 'purple', 'cyan']
    index = 0
    for tag in tags:
        for photo in api.photos_search(tags=tag, sort="relevance", license='2')[0]:
            photo_id = photo.attrib['id']

            try:
                sizes = api.photos_getSizes(photo_id=photo_id)[0]
            except:
                continue
            small = sizes.find('.//size[@label="Small"]')
            url = small.attrib['source']

            print 'downloading {0} as {1}'.format(url, index)
            resp = requests.get(url)
            if resp.status_code != 200:
                continue
            with open('{0}/{1:02d}.jpg'.format(ORIG_DIR, index), 'wb') as f:
                for chunk in resp.iter_content():
                    f.write(chunk)
            index += 1
Example #21
0
def connect():
	logging.info("start get_db_connection")
	idpass = Pit.get('label')
	username = idpass['username']
	passwd = idpass['password']
	con = mysql.connector.connect(db='sawachi', host='localhost', port=3306, user=username, passwd=passwd)
	logging.info("end get_db_connection")
	return con
Example #22
0
 def __call__(self):
     conf = Pit.get('pplog', {'require': {
         'username': '',
         'password': '',
     }})
     return PPlogSecret(
         username=conf['username'],
         password=conf['password'],
         )
Example #23
0
    def __init__(self):
        conf = Pit.get('picasaweb', {'require': {'username':'******', 'password':'******'}})
        self.gd_client = gdata.photos.service.PhotosService()
        self.gd_client.email = conf['username']
        self.gd_client.password = conf['password']
        self.gd_client.source = 'pw2f picasaweb plugin'
        self.gd_client.ProgrammaticLogin()

        self.conf = conf
Example #24
0
    def __init__(self, user):
        self.user = user
        login = Pit.get(self.user)
        self.ckey = login["ckey"]
        self.csecret = login["csecret"]
        self.atoken = login["atoken"]
        self.asecret = login["asecret"]

        self.api = twoauth.api(self.ckey, self.csecret, self.atoken, self.asecret)
Example #25
0
def get_Consumersecret():
    """
    pitからcustomer keyを呼ぶ
      """
    piConf = Pit.get("twitter-consumer", {'require':
                                 {'ckey': 'ConsumerKey',
                                  'csecret': 'ConsumerSecret'
                                  }})
    return(piConf['ckey'], piConf['csecret'])
Example #26
0
 def __call__(self):
     conf = Pit.get('pplog',
                    {'require': {
                        'username': '',
                        'password': '',
                    }})
     return PPlogSecret(
         username=conf['username'],
         password=conf['password'],
     )
Example #27
0
def activate_api(clientid=3):
    """ Given client-id, activate Twitter REST API corresponds client-id.
    """
    apikeys = Pit.get("twitter_restapi_%02d" % clientid)
    
    # create OAuth handler
    cons_key, cons_sec = apikeys["consumer_key"], apikeys["consumer_secret"]
    auth = tweepy.OAuthHandler(cons_key, cons_sec)

    # set access token to OAuth handler
    token, token_sec = apikeys["access_token"], apikeys["access_token_secret"]
    auth.set_access_token(token, token_sec)

    # create API
    proxy = Pit.get("proxy")
    url, port = proxy["http"], proxy["port"]
    
    api = tweepy.API(auth_handler=auth, proxy_host=url, proxy_port=port)
    return api
Example #28
0
    def __init__(self, db_name, coll_name):

        self.base_url = 'http://stream.twitter.com/1/statuses/sample.json'

        self.config = Pit.get('twitter_api_gardenhose')
        
        self.user = self.config['user']
        self.passwd = self.config['passwd']

        self.db = corpus.Corpus(database = db_name, collection = coll_name)
Example #29
0
    def __init__(self, db_name, coll_name):

        self.base_url = 'http://stream.twitter.com/1/statuses/sample.json'

        self.config = Pit.get('twitter_api_gardenhose')

        self.user = self.config['user']
        self.passwd = self.config['passwd']

        self.db = corpus.Corpus(database=db_name, collection=coll_name)
Example #30
0
def amazon_search(page, title=None, author=None, keyword=None):
    amazon = Pit.get("amazon");
    api = pyzon.Pyzon(amazon["key"], amazon["secret"], "pinkroot-22");
    if title:
        xml = api.ItemSearch("Books", Title=title, ItemPage=str(page), ResponseGroup="Images,ItemAttributes");
    if author:
        xml = api.ItemSearch("Books", Author=author, ItemPage=str(page), ResponseGroup="Images,ItemAttributes");
    if keyword:
        xml = api.ItemSearch("Books", Keywords=keyword, ItemPage=str(page), ResponseGroup="Images,ItemAttributes");
    result = parse_result_xml(xml);
    return result;
Example #31
0
def create_user():
    with settings(user='******'):
        cuisine.user_ensure('ssmjp')
        append('/etc/sudoers', 'ssmjp ALL=(ALL) ALL')
        cuisine.ssh_authorize('ssmjp',
                              cuisine.file_local_read('~/.ssh/ssmjp.pub'))
        conf = Pit.get('ssmjp-user',
                       {'require': {
                           'password': '******'
                       }})
        cuisine.user_passwd('ssmjp', conf['password'])
Example #32
0
def get_Consumersecret():
    """
    pitからcustomer keyを呼ぶ
      """
    piConf = Pit.get(
        "twitter-consumer",
        {'require': {
            'ckey': 'ConsumerKey',
            'csecret': 'ConsumerSecret'
        }})
    return (piConf['ckey'], piConf['csecret'])
Example #33
0
    def init():
        workdir = os.path.join(os.environ['HOME'], '.pystarter', 'tmp')
        config = Pit.get('pystarter', {'require': {'author'
                         : 'your username', 'email': 'your email',
                         'workdir': workdir}})

        if not config['author'] or not config['email'] \
            or not config['workdir']:
            sys.exit(1)

        return config
Example #34
0
 def getHoldStock(self):
   self.data = []
   br = mechanize.Browser()
   br.set_handle_robots(False)
   br.open('https://' + url + login)
   br.select_form(nr=0)
   idPass = Pit.get('oofbird')
   br['username'] = idPass['login']
   br['password'] = idPass['password']
   br.submit()
   r = br.open('https://' + url + holdStock)
   return r.read()
Example #35
0
    def LoadAccount(self, suffix = None):
        if suffix is None:
            suffix = self.__config['ProfileSuffix']

        profile = 'moco-google-reader-' + suffix
        account = Pit.get(profile,
                          {'require': {'Email': '', 'Password': ''}})
        self.__email = account['Email']
        self.__password = account['Password']

        self.__api = GoogleReaderApi("MocoClient")
        self.api.Connect(self.email, self.password)
Example #36
0
def main(text):
    url = Pit.get('nikki', {'require': {'url': 'form url'}})['url']

    agent = mechanize.Browser()
    agent.set_handle_robots(False)
    agent.open(url)
    agent.select_form(nr=0)
    agent['entry.0.single'] = text
    response = agent.submit()
    html = response.read()

    parser = TestHTMLParser()
    parser.feed(html)
    parser.close()
Example #37
0
def main():
    conf = Pit.get(
        'hue', {'require': {'ip_addr': 'IP Address of Hue'}}
    )

    b = Bridge(conf['ip_addr'])

    lights = b.lights
    for l in lights:
        print l.name

    print b.username
    print b.name
    print b.ip
Example #38
0
def main():
    conf   = Pit.get('twitter')
    consumer_key   = conf['consumer_key']
    consumer_secret = conf['consumer_secret']
    access_key = conf['access_token']
    access_secret = conf['access_token_secret']
    
    # create OAuth handler
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    # set access token to OAuth handler
    auth.set_access_token(access_key, access_secret)
    
    stream = tweepy.Stream(auth, StreamListener())
    #stream.sample()
    stream.filter(track=OYASUMI_LIST)
Example #39
0
def LingrPluginDebug():
    account = Pit.get('moco-lingr-plugin-moco',
                      {'require' : {'User': '', 'Password': '', 'AppKey' : ''}})

    lingr = Lingr(account['User'], account['Password'], account['AppKey'])
    lingr.CreateSession()
    room = 'w5ngr'
    
    for i in range(90):
        ret = lingr.VerifySession()
        msg = "verify %d:" % i + str(ret)
        print msg
        print lingr.Say(room, msg)
        print lingr.Say(room, "a")
        time.sleep(60)
Example #40
0
    def Initialize(self, runner, name, param):
        self.__name = name
        self.__room = param['Room']

        suffix = param['ProfileSuffix']

        account = Pit.get('moco-lingr-plugin-' + suffix,
                          {'require' : {'User': '', 'Password': '', 'AppKey' : ''}})

        self.__lingr = Lingr(account['User'], account['Password'], account['AppKey'])

        runner.AddProcessHook(self.Process)

        self.__thread = LingrThread(self.__lingr)
        runner.AddThread(self.__thread)
Example #41
0
    def init():
        workdir = os.path.join(os.environ['HOME'], '.pystarter', 'tmp')
        config = Pit.get(
            'pystarter', {
                'require': {
                    'author': 'your username',
                    'email': 'your email',
                    'workdir': workdir
                }
            })

        if not config['author'] or not config['email'] \
            or not config['workdir']:
            sys.exit(1)

        return config
Example #42
0
 def run(self):
     """
     """
     twitter_config = Pit.get(
         "twitter.com", {"require": {"user": "******", "password": "******"}}
     )
     stream = TwitterStream(twitter_config["user"], twitter_config["password"])
     print "start stream"
     while True:
         for status in stream.search("ACV_DEFPS3"):
             msg = status["text"]
             print msg, type(msg)
             self._bot.connection.notice(self._bot.channel, msg.encode("utf-8"))
         self._bot.connection.privmsg(self._bot.channel, u"twitter から切断されました。再接続します".encode("utf-8"))
         print "end stream"
         sleep(60)
Example #43
0
    def download_or_get_filename(self, album, photo):
        if not self.pw2f_conf:
            self.pw2f_conf = Pit.get('pw2f', {'require': {'data-directory':'Photo Directory'}})

        logging.debug('photo url: '+photo._url)
        filename = os.path.basename(photo._url)
        filepath = '%s/%s/%s' % (self.pw2f_conf['data-directory'], album._title, filename)
        if os.path.exists(filepath):
            logging.debug('found in local %s' % (filepath))
            return filepath
        else:
#            logging.debug('%s is not found.' % (filepath))
            (filepath, headers) = urllib.urlretrieve(photo._url)
            logging.debug('download %s as %s' % (photo._url, filepath))
            return filepath
        pass
def main():
    config = Pit.get('amazon.co.jp',
                     {'require': {'email': 'email',
                                  'password': '******'}})

    kindle = PyKindleHighlights(config['email'], config['password'])
    highlights = [highlight for highlight in kindle.highlights]

    for highlight in highlights:
        # title => h4
        print html2text.html2text("<h4>" + highlight.title + "</h4>")
        # author => emphasis
        print html2text.html2text("__" + highlight.author + "__")
        # text => unorederd list
        html = "<ul>"
        for hl_text in highlight.text:
            html += "<li>" + hl_text + "</li>"
        html += "</ul>"
        print html2text.html2text(html)
Example #45
0
File: test.py Project: yoichi/pit
    def test_set_get(self):
        Pit.set("test", {'data': {'username': '******', 'password': '******'}})
        self.assertEqual("foo", Pit.get("test")["username"])
        self.assertEqual("bar", Pit.get("test")["password"])

        Pit.set("test2", {'data': {"username": "******", "password": "******"}})
        self.assertEqual("foo2", Pit.get("test2")["username"])
        self.assertEqual("bar2", Pit.get("test2")["password"])

        Pit.set("test", {'data': {"username": "******", "password": "******"}})
        self.assertEqual("foo", Pit.get("test")["username"])
        self.assertEqual("bar", Pit.get("test")["password"])

        self.assertEqual(
            "foo",
            Pit.set("test", {'data': {
                "username": "******",
                "password": "******"
            }})["username"])
Example #46
0
from pit import Pit

API_TOKEN = Pit.get('seminarbot', {'require': {'tbot': 'slack_token'}})['tbot']
PLUGINS = ['taizanbot.plugins']
Example #47
0
from os import getcwd, environ
from pit import Pit
from time import sleep
from watson_developer_cloud import TextToSpeechV1
import datetime
import subprocess

def get_time(tts_id, tts_pass):
    text_to_speech = TextToSpeechV1(
        username=tts_id,
        password=tts_pass,
        x_watson_learning_opt_out=True)  # Optional flag

    now = datetime.datetime.now()
    time = str(now.hour) + '時' + str(now.minute) + '分になりました。'

    with open(join(getcwd(), '/home/pi/cron_scripts/canodumb/now.wav'), 'wb') as audio_file:
        audio_file.write(text_to_speech.synthesize(time, accept='audio/wav', voice="ja-JP_EmiVoice"))


if __name__ == '__main__':
    if not environ.get('EDITOR'):
        environ['EDITOR'] = 'vi'
    user_info = Pit.get('watson_tts', {'require': {
        'tts_id': '',
        'tts_pass': ''}})
    get_time(user_info['tts_id'], user_info['tts_pass'])

    command = 'aplay /home/pi/cron_scripts/canodumb/jihou.wav;aplay /home/pi/cron_scripts/canodumb/now.wav'
    subprocess.call(command, shell=True)
import lyricsgenius as lg
import joblib
import pandas as pd
import re

# genius APIのtoken設定用
from pit import Pit
import os
if not os.environ.get('EDITOR'):
    os.environ['EDITOR'] = 'vi'

# fetching ozzy data
genius = lg.Genius(Pit.get('genius')['token'])
artist = genius.search_artist("Ozzy Osbourne", sort="title")
joblib.dump(artist, "./data/ozzy.jb", compress=3)

# preprocessing
d = pd.DataFrame(data={'title': [song.title for song in artist.songs]})
d['title_f'] = d['title'].apply(
    lambda x: re.sub(r"( *\[.+\]| *\(.+\))", "", x))
d = d.reset_index()
d['index'] = d['index'] + 1
d['cnt_duplication'] = d.groupby("title_f")["index"].rank(method="first")
d = d.query('cnt_duplication == 1')[['index', 'title']]
d['lyrics'] = [artist.songs[i - 1].lyrics for i in d['index']]
d = d.dropna()

import nltk
from nltk.tokenize import PunktSentenceTokenizer
from nltk.corpus import stopwords
from nltk.tokenize import sent_tokenize, word_tokenize
Example #49
0
#!/opt/local/bin/python
# -*- coding:utf-8 -*-

import sys
import os
import re
import urllib

import argparse
from pit import Pit
ACCESS_KEY = Pit.get('Amazon')['AWSAccessKeyId']
SECRET_KEY = Pit.get('Amazon')['AWSSecretAccessKeyId']


def main():
    args = parse_args()
    # print args
    sys.stdout.write(getjan(args.asin))
    if not args.n:
        sys.stdout.write(os.linesep)


def parse_args():
    p = argparse.ArgumentParser("ASIN to JAN/ESN converter")
    p.add_argument('-n', action='store_true', default=False)
    p.add_argument('asin', type=str)
    return p.parse_args()


def getjan(asin):
    url = 'http://ecs.amazonaws.com/onca/xml'
Example #50
0
# -*- coding: utf-8 -*-
#Your Application's Consumer Key and Secret
from pit import Pit
config = Pit.get("tohae_call")
CONSUMER_KEY = config["CONSUMER_KEY"]
CONSUMER_SECRET = config["CONSUMER_SECRET"]
ACCESS_TOKEN = config["ACCESS_TOKEN"]
ACCESS_SECRET = config["ACCESS_SECRET"]

APP_NAME = u"とはえこ!!"

YAHOO_APPID = config["yahoo_appid"]
PIXIV_APPID = config["pixiv_appid"]
Example #51
0
def get():
    return Pit.get('test1')
Example #52
0
File: test.py Project: yoichi/pit
 def test_with_mock_editor(self):
     import os
     ORIGINAL_EDITOR = os.environ.get('EDITOR')
     os.environ["EDITOR"] = "./mock_editor.py"
     Pit.get('test', {'require': {'login': '******', 'passwd': 'GoMa'}})
     os.environ["EDITOR"] = ORIGINAL_EDITOR
Example #53
0
 def __init__(self):
     conf = Pit.get('pplog', {'require': {'username': '', 'password': ''}})
     self._username = conf['username']
     self._password = conf['password']