示例#1
0
def main():
    global bot
    global uid

    # Read config file
    parser = SafeConfigParser()

    # Open the file with the correct encoding
    with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), SETTINGSFILE), 'r', encoding='utf-8') as f:
        parser.readfp(f)

    try:
        # Create access to bot
        bot = telepot.Bot(parser.get('Telegram', 'token'))
        bot.message_loop(handle)
        uid = parser.get('Telegram', 'uid')
        bot.sendMessage(uid, text=u"Start %s\n%s\n%s" % (os.path.basename(sys.argv[0]), version.__version__, datetime.datetime.now()))
    except:
        print u'Cannot access Telegram. Please do /start'
        sys.exit(1)

    global DATABASE
    DATABASE = parser.get('Database', 'File')

    # Keep the program running.
    while 1:
        time.sleep(10)
示例#2
0
def parse_config():
    """Function to parse the config file for PETRARCH."""
    config_file = glob.glob('config.ini')
    parser = ConfigParser()
    print os.path.dirname(sys.executable)
    if config_file:
        print 'Found a config file in working directory.'
        parser.read(config_file)
        try:
            cwd = os.getcwd()
            actors_file = parser.get('Dictionary Files', 'actors')
            verbs_file = parser.get('Dictionary Files', 'verbs')
            actors_file = os.path.join(cwd, 'dictionaries', actors_file)
            verbs_file = os.path.join(cwd, 'dictionaries', verbs_file)
            direct = parser.get('StanfordNLP', 'stanford_dir')
            stanfordnlp = os.path.expanduser(direct)
            return actors_file, verbs_file, stanfordnlp
        except Exception, e:
            print 'Problem parsing config file. {}'.format(e)
def auth():
    parser = ConfigParser.ConfigParser()
    parser.read('config.ini')
    
    OAUTH_TOKEN = parser.get('twitter', 'OAUTH_TOKEN') 
    OAUTH_SECRET = parser.get('twitter', 'OAUTH_SECRET')
    CONSUMER_KEY = parser.get('twitter', 'CONSUMER_KEY')
    CONSUMER_SECRET = parser.get('twitter', 'CONSUMER_SECRET')
    print "[+] Authenticating..."
    try:
        t = Twitter(
                    auth=OAuth(
                               OAUTH_TOKEN, 
                               OAUTH_SECRET, 
                               CONSUMER_KEY, 
                               CONSUMER_SECRET
                              )
                   )
        print "[+] Authentication Succesful!"
        return t
    except Exception, e:
        print "[!] Error authentcating: ", e
        exit()
示例#4
0
def testlocationquery():
    date = '2015-11-01'
    data = locationquery(date)
    newdata = json.loads(data)

    for i in newdata:
        time = i['time']
        coordinates = i['coordinates']
        home = parser.get('google', 'home')
        pt1 = geopy.Point(home)
        pt2 = geopy.Point(coordinates)
        dist = geopy.distance.distance(pt1, pt2).m
        if dist < 150:
            print str(time) + " - " + str(dist)
示例#5
0
def read_main_conf(config_file):
    options = {}
    parser = SafeConfigParser()
    fd = open(config_file, 'r')
    parser.readfp(fd)
    fd.close()

    sec = parser.sections()
    # we'll read "generic" for db information and "r" for start_date and "bicho" for backend
    for s in sec:
        if not(s in ["generic","r","bicho","bicho_1"]):
            continue
        options[s] = {}
        opti = parser.options(s)
        for o in opti:
            options[s][o] = parser.get(s, o)
    return options
示例#6
0
import simplejson

"""
	ARGVS:
	1 - "repos.csv"

	NEED:
	- github_account.conf
"""

ORG_NAME = 'usc-csci104-spring2015'
CSV_FILENAME = sys.argv[1]

parser = SafeConfigParser()
parser.read("github_account.conf")
githubUsername = parser.get("github", "username")
githubPassword = parser.get("github", "password")

def hint(text, color='34'):
	return '\t\033[{}m{}\033[0m'.format(color, text)

def githubPost(url, payload):
	""" Send a POST request to GitHub via API """
	r = requests.post(url, data=simplejson.dumps(payload), auth=(githubUsername, githubPassword))
	res = simplejson.loads(r.content)
	if r.status_code == 201 or r.status_code == 200:
		return res
	else:
		details = ""
		if "errors" in res:
			for e in res["errors"]:
示例#7
0
def main():
    global newdayalert

    initializetz()

    # Read config file
    parser = SafeConfigParser()

    # Open the file with the correct encoding
    with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), SETTINGSFILE), 'r', encoding='utf-8') as f:
        parser.readfp(f)

    DATABASE = parser.get('Database', 'File')

    try:
        # Create access to bot
        bot = telepot.Bot(parser.get('Telegram', 'token'))
        uid = parser.get('Telegram', 'uid')
        # bot.sendMessage(uid, text=u"Start %s\n%s\n%s" % (os.path.basename(sys.argv[0]), version.__version__, datetime.datetime.now()))
    except:
        print u'Cannot access Telegram. Please do /start'
        sys.exit(1)

    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row

    #sellstock('NASDAQ:QLIK', 10, 30,None,conn)

    c = conn.cursor()

    #Check if it is time to buy or sell in active strategies
    for stock in c.execute("""
                select strategies.*, stocks.name, stocks.symbolgoogle, stocks.symbolyahoo, stocks.exchangeid, stocks.lastquotestamp
                from strategies, stocks
                where strategies.stockid=stocks.id and strategies.active='True';
                """):

        #Check if market open
        if not(checkifmarketopen(stock["exchangeid"], stock['symbolgoogle'], stock['name'],conn)):
            continue

        symbol = str(stock["symbolgoogle"])
        minreturn = float(stock['minreturn'])
        lowcount = int(stock['lowcount'])

        c1 = conn.cursor()
        c1.execute("""
                  select portfolio.*, stocks.lastquotestamp
                  from portfolio, stocks
                  where portfolio.stockid=:id and portfolio.stockid=stocks.id
                  """, {'id':stock['stockid']})
        stockinportfolio = c1.fetchone()

        try:
            qty = float(stockinportfolio['qty'])
            buyprice = float(stockinportfolio['cost'])
        except:
            qty = 0
            buyprice = 0

        try:
            lasttradedatetime = dateutil.parser.parse(stock['lastquotestamp'])
        except:
            lasttradedatetime = None

        #Get current quote
        quote = getQuotes(symbol)[0]
        correcteddate = quote["LastTradeDateTimeLong"]
        #parse uses posix stype for timezone offsets. ISO requires inversion in sign!!
        if correcteddate.find('+'):
            correcteddate=correcteddate.replace('+', '-')
        elif correcteddate.find('-'):
            correcteddate=correcteddate.replace('-', '+')
        datetradenow = dateutil.parser.parse(correcteddate, tzinfos=tzd) #get current last trade time on market
        nowquotevalue = float(quote['LastTradePrice']) #get last quote

        newdayalert = False

        if (lasttradedatetime is None) or datetradenow.date()!=lasttradedatetime.date():
            #New Day!
            bot.sendMessage(uid, text=u"New Day for stock %s" % stock['name'])
            if VERBOSE:
                print "New Day for stock %s" % stock['name']
            newdayalert = True

        if newdayalert:
            #Number of days descending reached, and opend low
            if checkiftimetobuy(stock['symbolyahoo'], lowcount, datetradenow, nowquotevalue):
                bot.sendMessage(uid, text=u"Time to BUY %s (%s) Price = %8.3f" % (stock['name'], symbol, nowquotevalue))
                if VERBOSE:
                    print "Time to BUY %s (%s) Price = %8.3f" % (stock['name'], symbol, nowquotevalue)

            checkifdividendday(datetradenow.date() ,conn)
            checkifsplitday(datetradenow.date() ,conn)

            c2 = conn.cursor()
            c2.execute("UPDATE stocks SET lastquotestamp = ?, lastquote = ?  WHERE id = ?;",  (datetradenow.isoformat(), nowquotevalue, stock['stockid'])) #update last quote timestamp
            conn.commit()

        if qty>0 and nowquotevalue>=(1+minreturn)*buyprice and newdayalert:
            newdayalert = False
            bot.sendMessage(uid, text=u"Time to SELL %s (%s) Qty = %8.2f Price = %8.3f" % (stock['name'], symbol, qty, nowquotevalue))
            if VERBOSE:
                print "Time to SELL %s (%s) Qty = %8.2f Price = %8.3f" % (stock['name'], symbol, qty, nowquotevalue)

    #Update quotes in tracked stocks
    for stock in c.execute("select * from stocks where tracked='True'"):
        if not(checkifmarketopen(stock["exchangeid"], stock['symbolgoogle'], stock['name'],conn)):
            continue

        nowutc = datetime.datetime.utcnow().replace(tzinfo = pytz.utc)
        lastdateplus = dateutil.parser.parse(stock['lastquotestamp']) + datetime.timedelta( minutes=int(stock['interval'] ))
        if (stock['lastquotestamp'] is None) or (lastdateplus< nowutc):
            timestamp, nowquotevalue = savequote(int(stock['id']), stock['lastquotestamp'], conn)

    conn.commit()
import json
from ConfigParser import SafeConfigParser
from simple_salesforce import Salesforce
import openpyxl
from openpyxl.styles import PatternFill, Border, Side, Font
import dateutil.parser
from pytz import timezone
import pytz
from datetime import datetime, timedelta

### Personal Credentials
parser = SafeConfigParser()
parser.read('salesforce.conf')
sf_url = parser.get('SalesForce', 'url')
sf_usr = parser.get('SalesForce', 'username')
sf_pwd = parser.get('SalesForce', 'password')
sf_tkn = parser.get('SalesForce', 'token')
sf_account = parser.get('SalesForce', 'account')
sf_cloud = parser.get('SalesForce', 'cloud')
last_time = parser.get('SalesForce', 'last_time')
now = parser.get('SalesForce', 'now')
tz = parser.get('SalesForce', 'tz')
duration = int(parser.get('SalesForce', 'duration'))
report_file_name = parser.get('SalesForce', 'report_file_name')

### L1 Variables
font_size = 10
default_font = Font(name="Open Sans", size=font_size)
defautl_font_hyperlink = Font(name="Open Sans",
                              size=font_size,
                              underline="single",
示例#9
0
def main():
    global newdayalert

    initializetz()

    # Read config file
    parser = SafeConfigParser()

    # Open the file with the correct encoding
    with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                  SETTINGSFILE),
                     'r',
                     encoding='utf-8') as f:
        parser.readfp(f)

    DATABASE = parser.get('Database', 'File')

    try:
        # Create access to bot
        bot = telepot.Bot(parser.get('Telegram', 'token'))
        uid = parser.get('Telegram', 'uid')
        # bot.sendMessage(uid, text=u"Start %s\n%s\n%s" % (os.path.basename(sys.argv[0]), version.__version__, datetime.datetime.now()))
    except:
        print u'Cannot access Telegram. Please do /start'
        sys.exit(1)

    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row

    # sellstock('NASDAQ:QLIK', 10, 30,None,conn)

    c = conn.cursor()

    # Check if it is time to buy or sell in active strategies
    for stock in c.execute("""
                select strategies.*, stocks.name, stocks.symbolgoogle, stocks.symbolyahoo, stocks.exchangeid, stocks.lastquotestamp
                from strategies, stocks
                where strategies.stockid=stocks.id and strategies.active='True';
                """):

        # Check if market open
        if not (checkifmarketopen(stock["exchangeid"], stock['symbolgoogle'],
                                  stock['name'], conn)):
            continue

        symbol = str(stock["symbolgoogle"])
        minreturn = float(stock['minreturn'])
        lowcount = int(stock['lowcount'])

        c1 = conn.cursor()
        c1.execute(
            """
                  select portfolio.*, stocks.lastquotestamp
                  from portfolio, stocks
                  where portfolio.stockid=:id and portfolio.stockid=stocks.id
                  """, {'id': stock['stockid']})
        stockinportfolio = c1.fetchone()

        try:
            qty = float(stockinportfolio['qty'])
            buyprice = float(stockinportfolio['cost'])
        except:
            qty = 0
            buyprice = 0

        try:
            lasttradedatetime = dateutil.parser.parse(stock['lastquotestamp'])
        except:
            lasttradedatetime = None

        # Get current quote
        quote = getQuotes(symbol)[0]
        correcteddate = quote["LastTradeDateTimeLong"]
        # parse uses posix stype for timezone offsets. ISO requires inversion in sign!!
        if correcteddate.find('+'):
            correcteddate = correcteddate.replace('+', '-')
        elif correcteddate.find('-'):
            correcteddate = correcteddate.replace('-', '+')
        datetradenow = dateutil.parser.parse(
            correcteddate,
            tzinfos=tzd)  # get current last trade time on market
        nowquotevalue = float(quote['LastTradePrice'])  # get last quote

        newdayalert = False

        if (lasttradedatetime is
                None) or datetradenow.date() != lasttradedatetime.date():
            # New Day!
            bot.sendMessage(uid, text=u"New Day for stock %s" % stock['name'])
            if VERBOSE:
                print "New Day for stock %s" % stock['name']
            newdayalert = True

        if newdayalert:
            # Number of days descending reached, and opend low
            if checkiftimetobuy(stock['symbolyahoo'], lowcount, datetradenow,
                                nowquotevalue):
                bot.sendMessage(uid,
                                text=u"Time to BUY %s (%s) Price = %8.3f" %
                                (stock['name'], symbol, nowquotevalue))
                if VERBOSE:
                    print "Time to BUY %s (%s) Price = %8.3f" % (
                        stock['name'], symbol, nowquotevalue)

            checkifdividendday(datetradenow.date(), conn)
            checkifsplitday(datetradenow.date(), conn)

            c2 = conn.cursor()
            c2.execute(
                "UPDATE stocks SET lastquotestamp = ?, lastquote = ?  WHERE id = ?;",
                (datetradenow.isoformat(), nowquotevalue,
                 stock['stockid']))  # update last quote timestamp
            conn.commit()

        if qty > 0 and nowquotevalue >= (1 +
                                         minreturn) * buyprice and newdayalert:
            newdayalert = False
            bot.sendMessage(
                uid,
                text=u"Time to SELL %s (%s) Qty = %8.2f Price = %8.3f" %
                (stock['name'], symbol, qty, nowquotevalue))
            if VERBOSE:
                print "Time to SELL %s (%s) Qty = %8.2f Price = %8.3f" % (
                    stock['name'], symbol, qty, nowquotevalue)

    # Update quotes in tracked stocks
    for stock in c.execute("select * from stocks where tracked='True'"):
        if not (checkifmarketopen(stock["exchangeid"], stock['symbolgoogle'],
                                  stock['name'], conn)):
            continue

        nowutc = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
        lastdateplus = dateutil.parser.parse(
            stock['lastquotestamp']) + datetime.timedelta(
                minutes=int(stock['interval']))
        if (stock['lastquotestamp'] is None) or (lastdateplus < nowutc):
            timestamp, nowquotevalue = savequote(int(stock['id']),
                                                 stock['lastquotestamp'], conn)

    conn.commit()
示例#10
0
for title,items in recs:
	oldest = None
	newest = None
	for item in items:
#		print "                 %-40.40s %-40.40s %-20.20s %s %s" % (item.title, item.subtitle, item.programid, item.starttime, item.filesize)
		if oldest is None:
			oldest = item
		elif item.starttime < oldest.starttime:
			oldest = item

		if newest is None:
			newest = item
		elif item.starttime > newest.starttime:
			newest = item

#	oldest.filesize = newest.filesize
	eps[`newest.starttime.timestamp()` + "_" + `newest.chanid`] = oldest


user= parser.get("top", "ApacheUser")
pw= parser.get("top", "ApachePassword")

i = 0
for key in sorted(eps.iterkeys()):
	oldest = eps[key]
	print "%-40.40s %-40.40s %-20.20s %s %s MB" % (oldest.title, oldest.subtitle, oldest.programid, oldest.starttime, oldest.filesize / 1024 / 1024)
	if i < (len(eps) - episodes):
		os.system("curl -s --data \"ajax=yes&delete=yes&chanid=%s&starttime=%d&forgetold=\" http://%s:%s@localhost/mythweb/tv/recorded" % (oldest.chanid, oldest.recstartts.timestamp(), user, pw))
		print "deleted"
	i = i+1
def safeGet(parser, section, option):
    """ Safely gets a value from config parser. If value is not present - returns None
    """
    if parser.has_option(section, option):
        return parser.get(section, option).strip()
    return None
                        status=200,
                        mimetype="application/json")

    generated_function.__name__ = func.__name__
    return generated_function


app = Flask(__name__, static_url_path=os.path.abspath('static/'))
CORS(app)
# Flags and Initialization
"""Reads the config file"""
try:
    # Try to open the config file and parse it
    parser = configparser.RawConfigParser()
    parser.read('ghdata.cfg')
    host = parser.get('Server', 'host')
    port = parser.get('Server', 'port')
    try:
        dbstr = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(
            parser.get('Database', 'user'), parser.get('Database', 'pass'),
            parser.get('Database', 'host'), parser.get('Database', 'port'),
            parser.get('Database', 'name'))
        ghtorrent = ghdata.GHTorrent(dbstr=dbstr)
    except Exception as e:
        print("Failed to connect to database (" + str(e) + ")")
    publicwww = ghdata.PublicWWW(
        public_www_api_key=parser.get('PublicWWW', 'APIKey'))
    if (parser.get('Development', 'developer') == '1'
            or os.getenv('FLASK_DEBUG') == '1'):
        DEBUG = True
    else:
示例#13
0
from configparser import ConfigParser
import urllib.request
import dateutil.parser
import json
import os
from timezonefinder import TimezoneFinder
from datetime import datetime, timedelta
import pytz
import csv
import xml.etree.ElementTree as ET
import sqlite3

parser = ConfigParser()
parser.read('../slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky', 'key')

gps_logs_directory = '../gps_logs/'

tf = TimezoneFinder()


def write_runs_to_csv(logs_directory):
    """Writes basic activity data from all GPS files in directory to a .csv file"""

    all_gps_files = os.listdir(logs_directory)

    with open('running.csv', 'w') as csv_file:
        file_writer = csv.writer(csv_file, delimiter=',',
                                 quotechar='|', quoting=csv.QUOTE_MINIMAL)

        file_writer.writerow(
示例#14
0
def init():
    """Reads the config file"""
    try:
        # Try to open the config file and parse it
        parser = configparser.RawConfigParser()
        parser.read('ghdata.cfg')
        host = parser.get('Database', 'host')
        port = parser.get('Database', 'port')
        user = parser.get('Database', 'user')
        password = parser.get('Database', 'pass')
        db = parser.get('Database', 'name')
        public_www_api_key = parser.get('PublicWWW', 'APIKey')
        debug = parser.get('Development', 'developer')
        try:
            global client
            client = GHDataClient(db_host=host,
                                  db_port=port,
                                  db_user=user,
                                  db_pass=password,
                                  db_name=db,
                                  public_www_api_key=public_www_api_key,
                                  debug=debug)
        except:
            print('Couldn\'t start. Double check ghdata.cfg for errors.')

    except:
        # Uh-oh. Save a new config file.
        print('Failed to open config file.')
        config = configparser.RawConfigParser()
        config.add_section('Database')
        config.set('Database', 'host', '127.0.0.1')
        config.set('Database', 'port', '3306')
        config.set('Database', 'user', 'root')
        config.set('Database', 'pass', 'root')
        config.set('Database', 'name', 'ghtorrent')
        config.add_section('PublicWWW')
        config.set('PublicWWW', 'APIKey', '0')
        config.add_section('Development')
        config.set('Development', 'developer', '0')
        # Writing our configuration file to 'example.cfg'
        with open('ghdata.cfg', 'w') as configfile:
            config.write(configfile)
        print('Default config saved to ghdata.cfg')
        sys.exit()

    if (client.DEBUG):
        # Serve the front-end files in debug mode to make it easier for developers to work on the interface
        # @todo: Figure out why this isn't working.
        @app.route('/')
        def root():
            return app.send_static_file('frontend/index.html')

        @app.route('/scripts/<path>')
        def send_scripts(path):
            return send_from_directory('frontend/scripts', path)

        @app.route('/styles/<path>')
        def send_styles(path):
            return send_from_directory('frontend/styles', path)

        app.debug = True

    app.run(debug=client.DEBUG)
示例#15
0
def main():
    # Read config file
    parser = SafeConfigParser()

    # Open the file with the correct encoding
    with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                  SETTINGSFILE),
                     'r',
                     encoding='utf-8') as f:
        parser.readfp(f)

    global DATABASE
    DATABASE = parser.get('Database', 'File')

    if VERBOSE:
        print "Start %s\n%s\n%s" % (os.path.basename(
            sys.argv[0]), version.__version__, datetime.datetime.now())

    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    # get quotes for all stocks marked to track
    for row in c.execute("select * from stocks where tracked='True';"):

        stockid = row["id"]
        stockname = row["name"]

        if VERBOSE:
            print "\n"

        if not (monitorstock.checkifmarketopen(
                row["exchangeid"], row["symbolgoogle"], stockname, conn)):
            if VERBOSE:
                print "Stock market CLOSED for %s(%s)" % (row["symbolgoogle"],
                                                          stockname)

                c1 = conn.cursor()
                c1.execute(
                    "select MAX(timestamp), value from quotes where stockid=:id",
                    {'id': row['id']})
                newquote = c1.fetchone()
                quote = newquote['value']
                newtimestamp = newquote['MAX(timestamp)']
                print "LAST quote available in database for %s(%s) of %s @%s" % (
                    row["symbolgoogle"], stockname, quote, newtimestamp)
            continue

        if not (row["lastquotestamp"] is None):
            timestamp = dateutil.parser.parse(
                row["lastquotestamp"]
            )  # get last quote timestamp and parse into time object
        else:
            timestamp = None
        interval = row["interval"]

        now = datetime.datetime.utcnow().replace(
            tzinfo=pytz.utc
        )  # get current date and time in UTC with  timezone info
        if (timestamp is None) or (now > timestamp + datetime.timedelta(
                minutes=interval)):  # see if it is time to get a new quote
            newtimestamp, quote = monitorstock.savequote(
                int(stockid), timestamp, conn)

            if VERBOSE:
                print "Got NEW quote for %s(%s) of %s @%s" % (
                    row["symbolgoogle"], stockname, quote, newtimestamp)
        else:
            if VERBOSE:
                c1 = conn.cursor()
                c1.execute(
                    "select MAX(timestamp), value from quotes where stockid=:id",
                    {'id': row['id']})
                newquote = c1.fetchone()
                quote = newquote['value']
                newtimestamp = newquote['MAX(timestamp)']
                print "RECENT quote available in database for %s(%s) of %s @%s" % (
                    row["symbolgoogle"], stockname, quote, newtimestamp)
            content = 'From the archive: ' + content
        elif post_type == 'Archive' and len(tweet_text) > 102:
            content = 'From the archive: ' + social_queue[n][0]

        buffer_post(platform, content, page_url)

        n = +1


def main_proc():
    generate_media_queue()
    daily_loads()


global cursor

parser = ConfigParser()
parser.read("whconfig.ini")

wh_host = parser.get('MYSQL', 'host')
wh_user = parser.get('MYSQL', 'user')
wh_pass = parser.get('MYSQL', 'password')

conn = mysql.connect(host=wh_host,
                     user=wh_user,
                     password=wh_pass,
                     database='NovaraWH')

cursor = conn.cursor()

main_proc()
示例#17
0
#!/usr/bin/env python

import os, sys, re
from dateutil import parser
import json
import tweepy
from pymongo import MongoClient
from helper_functions import _get_config, _logger

parser = _get_config()
CONSUMER_KEY = parser.get('Keys', 'consumer_key')
CONSUMER_SERECT = parser.get('Keys', 'consumer_serect')
ACCESS_TOKEN = parser.get('Keys', 'access_token')
ACCESS_SERECT = parser.get('Keys', 'access_secret')
MONGO_HOST = parser.get(
    'Mongodb', 'host'
)  # Use 'mongodb://localhost/twitter_collect_db' assuming you store data into a local database twitter_collect_db
SOUTH = parser.getfloat('Area', 'south')
WEST = parser.getfloat('Area', 'west')
NORTH = parser.getfloat('Area', 'north')
EAST = parser.getfloat('Area', 'east')
LOCATIONS = [WEST, SOUTH, EAST, NORTH]


def mongodb_store(created_at, text, id_str, user_id, user_name, lat, lon,
                  lang):
    client = MongoClient(MONGO_HOST)
    db = client.twitter_collect_db
    data_mongo = {}
    data_mongo['id_str'] = id_str
    data_mongo['user_name'] = user_name
示例#18
0
	# If there are any projects with time in the entry list
	# this function simply creates a list of the job numbers
	if len(entrylist.keys())>0:
		jobslist = sorted(list(set(reduce(lambda x,y:x+y,[entrylist[x].keys() for x in sorted(entrylist.keys())]))))
	else:
		jobslist = {}
		errorlist.append("Warning: No time entries found")

	return json.dumps({'jobs' : jobslist, 'entries' : entrylist, 'errors' : errorlist, 'listbyjob': listbyjob }, sort_keys=True, indent=4)
	#print json.dumps(entrylist)

if __name__ == "__main__":
	parser = SafeConfigParser()
	parser.read('simple.ini')

	try:
		weekending = dateutil.parser.parse(sys.argv[1])
	except:
		weekending = datetime.datetime.now()

	try:
		apikey = sys.argv[2]
	except:
		try:
			apikey = parser.get('toggl','apikey')
		except:
			print "Failed"
			exit()

	print convert_json(weekending,apikey)
示例#19
0
 def _parse_config(self, config_file_path):
     parser = ConfigParser.ConfigParser()
     parser.read(config_file_path)
     options = parser.options('Options')
     for option in options:
         self.__dict__[option] = parser.get('Options', option)
示例#20
0
            actors_file = parser.get('Dictionary Files', 'actors')
            verbs_file = parser.get('Dictionary Files', 'verbs')
            actors_file = os.path.join(cwd, 'dictionaries', actors_file)
            verbs_file = os.path.join(cwd, 'dictionaries', verbs_file)
            direct = parser.get('StanfordNLP', 'stanford_dir')
            stanfordnlp = os.path.expanduser(direct)
            return actors_file, verbs_file, stanfordnlp
        except Exception, e:
            print 'Problem parsing config file. {}'.format(e)
    else:
        cwd = os.path.abspath(os.path.dirname(__file__))
        config_file = os.path.join(cwd, 'default_config.ini')
        parser.read(config_file)
        print 'No config found. Using default.'
        try:
            actors_file = parser.get('Dictionary Files', 'actors')
            verbs_file = parser.get('Dictionary Files', 'verbs')
            actors_file = os.path.join(cwd, 'dictionaries', actors_file)
            verbs_file = os.path.join(cwd, 'dictionaries', verbs_file)
            direct = parser.get('StanfordNLP', 'stanford_dir')
            stanfordnlp = os.path.expanduser(direct)
            return actors_file, verbs_file, stanfordnlp
        except Exception, e:
            print 'Problem parsing config file. {}'.format(e)


def main():
    """Main function"""
    actors, verbs, stanford_dir = parse_config()

    cli_args = parse_cli_args()