prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
<|fim_middle|>
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown") |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
<|fim_middle|>
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown") |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
<|fim_middle|>
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | send_message(msg['chat']['id'], 'Please include a reminder.') |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
<|fim_middle|>
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | text += '\n@' + msg['from']['username'] |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
<|fim_middle|>
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | delay = delay.replace('s', ' seconds') |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
<|fim_middle|>
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | delay = delay.replace('m', ' minutes') |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
<|fim_middle|>
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | delay = delay.replace('h', ' hours') |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
<|fim_middle|>
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | delay = delay.replace('d', ' days') |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
<|fim_middle|>
<|fim▁end|> | send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders) |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def <|fim_middle|>(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | to_seconds |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def <|fim_middle|>(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | run |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def <|fim_middle|>():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | cron |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.<|fim▁hole|> Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser<|fim▁end|> | |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
<|fim_middle|>
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | """
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
<|fim_middle|>
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
<|fim_middle|>
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | r'(\(x\))'
return t |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
<|fim_middle|>
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | r'((?!\(x\))).+'
return t |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
<|fim_middle|>
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | r'\n+'
t.lexer.lineno += len(t.value) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
<|fim_middle|>
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
<|fim_middle|>
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | self.lexer = lex.lex(module=self) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
<|fim_middle|>
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | """
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
<|fim_middle|>
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF") |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
<|fim_middle|>
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | "start : translation_unit"
p[0] = self.todo |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
<|fim_middle|>
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | """
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
<|fim_middle|>
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | """
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
<|fim_middle|>
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | self.parser = yacc.yacc(module=self, debug=0, write_tables=0) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
<|fim_middle|>
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | self.todo = Todo()
return self.parser.parse(data) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
<|fim_middle|>
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
<|fim_middle|>
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | raise SyntaxError("SyntaxError at EOF") |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
<|fim_middle|>
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | done = True
content = p[3] |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
<|fim_middle|>
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | done = False
content = p[2] |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def <|fim_middle|>(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | t_ID |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def <|fim_middle|>(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | t_DONE |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def <|fim_middle|>(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | t_TASK |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def <|fim_middle|>(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | t_newline |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def <|fim_middle|>(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | t_error |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def <|fim_middle|>(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | __init__ |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def <|fim_middle|>(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | p_error |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def <|fim_middle|>(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | p_start |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def <|fim_middle|>(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | p_translation_unit |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def <|fim_middle|>(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | p_translation_task |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def <|fim_middle|>(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def parse(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | __init__ |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># coding=utf8
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
DONE e.g. '(x)'
TASK e.g. 'This is a task'
"""
tokens = (
"ID",
"DONE",
"TASK",
)
t_ignore = "\x20\x09" # ignore spaces and tabs
def t_ID(self, t):
r'\d+\.([uU]|[lL]|[uU][lL]|[lL][uU])?'
t.value = int(t.value[:-1])
return t
def t_DONE(self, t):
r'(\(x\))'
return t
def t_TASK(self, t):
r'((?!\(x\))).+'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(self, t):
raise SyntaxError(
"Illegal character: '%s' at Line %d" % (t.value[0], t.lineno)
)
def __init__(self):
self.lexer = lex.lex(module=self)
class TodoParser(object):
"""
Parser for Todo format string, works with a todo lexer.
Parse string to Python list
todo_str = "1. (x) Write email to tom"
TodoParser().parse(todo_str)
"""
tokens = TodoLexer.tokens
def p_error(self, p):
if p:
raise SyntaxError(
"Character '%s' at line %d" % (p.value[0], p.lineno)
)
else:
raise SyntaxError("SyntaxError at EOF")
def p_start(self, p):
"start : translation_unit"
p[0] = self.todo
def p_translation_unit(self, p):
"""
translation_unit : translate_task
| translation_unit translate_task
|
"""
pass
def p_translation_task(self, p):
"""
translate_task : ID DONE TASK
| ID TASK
"""
if len(p) == 4:
done = True
content = p[3]
elif len(p) == 3:
done = False
content = p[2]
task = Task(p[1], content, done)
self.todo.append(task)
def __init__(self):
self.parser = yacc.yacc(module=self, debug=0, write_tables=0)
def <|fim_middle|>(self, data):
# reset list
self.todo = Todo()
return self.parser.parse(data)
lexer = TodoLexer() # build lexer
parser = TodoParser() # build parser
<|fim▁end|> | parse |
<|file_name|>DBtest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2.7
import os
import sys
this_dir = os.path.dirname(os.path.abspath(__file__))
trunk_dir = os.path.split(this_dir)[0]
sys.path.insert(0,trunk_dir)
from ikol.dbregister import DataBase
from ikol import var
if os.path.exists(var.DB_PATH):
os.remove(var.DB_PATH)
DB = DataBase(var.DB_PATH)
<|fim▁hole|>
DB.insertVideo("KDk2341oEQQ","loLWOCl7nlk","test")
DB.insertVideo("KDktIWeoE23","loLWOCl7nlk","testb")
print DB.getAllVideosByPlaylist("loLWOCl7nlk")
print DB.getVideoById("KDk2341oEQQ")<|fim▁end|> |
DB.insertPlaylist("loLWOCl7nlk","test")
DB.insertPlaylist("loLWO357nlk","testb") |
<|file_name|>DBtest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2.7
import os
import sys
this_dir = os.path.dirname(os.path.abspath(__file__))
trunk_dir = os.path.split(this_dir)[0]
sys.path.insert(0,trunk_dir)
from ikol.dbregister import DataBase
from ikol import var
if os.path.exists(var.DB_PATH):
<|fim_middle|>
DB = DataBase(var.DB_PATH)
DB.insertPlaylist("loLWOCl7nlk","test")
DB.insertPlaylist("loLWO357nlk","testb")
DB.insertVideo("KDk2341oEQQ","loLWOCl7nlk","test")
DB.insertVideo("KDktIWeoE23","loLWOCl7nlk","testb")
print DB.getAllVideosByPlaylist("loLWOCl7nlk")
print DB.getVideoById("KDk2341oEQQ")<|fim▁end|> | os.remove(var.DB_PATH) |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:<|fim▁hole|> return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())<|fim▁end|> | |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
<|fim_middle|>
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | """
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
<|fim_middle|>
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | """
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
<|fim_middle|>
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.len |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
<|fim_middle|>
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
<|fim_middle|>
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
<|fim_middle|>
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | """
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]]) |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
<|fim_middle|>
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.formatted_address |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
<|fim_middle|>
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.__unicode__() |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
<|fim_middle|>
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.return_next() |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
<|fim_middle|>
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.__unicode__().encode('utf8') |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
<|fim_middle|>
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.return_next() |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
<|fim_middle|>
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.len |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
<|fim_middle|>
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | """
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng'] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
<|fim_middle|>
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.coordinates[0] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
<|fim_middle|>
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.coordinates[1] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
<|fim_middle|>
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | """
Returns the full result set in dictionary format
"""
return self.data |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
<|fim_middle|>
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | """
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address'] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
<|fim_middle|>
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return self.current_data['formatted_address'] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
<|fim_middle|>
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
<|fim_middle|>
<|fim▁end|> | """Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__()) |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
<|fim_middle|>
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | """Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
<|fim_middle|>
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | """Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url) |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
<|fim_middle|>
<|fim▁end|> | """Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__()) |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
<|fim_middle|>
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | raise StopIteration |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
<|fim_middle|>
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next() |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
<|fim_middle|>
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next() |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
<|fim_middle|>
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | attribute = GeocoderResult.attribute_mapping[attribute] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
<|fim_middle|>
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return elem[prop] |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def <|fim_middle|>(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __init__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def <|fim_middle|>(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __len__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def <|fim_middle|>(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __iter__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def <|fim_middle|>(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | return_next |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def <|fim_middle|>(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __getitem__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def <|fim_middle|>(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __unicode__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def <|fim_middle|>(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __str__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def <|fim_middle|>(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __next__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def <|fim_middle|>(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __str__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def <|fim_middle|>(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | next |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def <|fim_middle|>(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | count |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def <|fim_middle|>(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | coordinates |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def <|fim_middle|>(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | latitude |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def <|fim_middle|>(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | longitude |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def <|fim_middle|>(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | raw |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def <|fim_middle|>(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | valid_address |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def <|fim_middle|>(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | formatted_address |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def <|fim_middle|>(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __getattr__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def <|fim_middle|>(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __init__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def <|fim_middle|>(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def __unicode__(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __str__ |
<|file_name|>pygeolib.py<|end_file_name|><|fim▁begin|>import sys
import collections
class GeocoderResult(collections.Iterator):
"""
A geocoder resultset to iterate through address results.
Exemple:
results = Geocoder.geocode('paris, us')
for result in results:
print(result.formatted_address, result.location)
Provide shortcut to ease field retrieval, looking at 'types' in each
'address_components'.
Example:
result.country
result.postal_code
You can also choose a different property to display for each lookup type.
Example:
result.country__short_name
By default, use 'long_name' property of lookup type, so:
result.country
and:
result.country__long_name
are equivalent.
"""
attribute_mapping = {
"state": "administrative_area_level_1",
"province": "administrative_area_level_1",
"city": "locality",
"county": "administrative_area_level_2",
}
def __init__(self, data):
"""
Creates instance of GeocoderResult from the provided JSON data array
"""
self.data = data
self.len = len(self.data)
self.current_index = 0
self.current_data = self.data[0]
def __len__(self):
return self.len
def __iter__(self):
return self
def return_next(self):
if self.current_index >= self.len:
raise StopIteration
self.current_data = self.data[self.current_index]
self.current_index += 1
return self
def __getitem__(self, key):
"""
Accessing GeocoderResult by index will return a GeocoderResult
with just one data entry
"""
return GeocoderResult([self.data[key]])
def __unicode__(self):
return self.formatted_address
if sys.version_info[0] >= 3: # Python 3
def __str__(self):
return self.__unicode__()
def __next__(self):
return self.return_next()
else: # Python 2
def __str__(self):
return self.__unicode__().encode('utf8')
def next(self):
return self.return_next()
@property
def count(self):
return self.len
@property
def coordinates(self):
"""
Return a (latitude, longitude) coordinate pair of the current result
"""
location = self.current_data['geometry']['location']
return location['lat'], location['lng']
@property
def latitude(self):
return self.coordinates[0]
@property
def longitude(self):
return self.coordinates[1]
@property
def raw(self):
"""
Returns the full result set in dictionary format
"""
return self.data
@property
def valid_address(self):
"""
Returns true if queried address is valid street address
"""
return self.current_data['types'] == ['street_address']
@property
def formatted_address(self):
return self.current_data['formatted_address']
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
class GeocoderError(Exception):
"""Base class for errors in the :mod:`pygeocoder` module.
Methods of the :class:`Geocoder` raise this when something goes wrong.
"""
#: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes
#: for information on the meaning of these status codes.
G_GEO_OK = "OK"
G_GEO_ZERO_RESULTS = "ZERO_RESULTS"
G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT"
G_GEO_REQUEST_DENIED = "REQUEST_DENIED"
G_GEO_MISSING_QUERY = "INVALID_REQUEST"
def __init__(self, status, url=None, response=None):
"""Create an exception with a status and optional full response.
:param status: Either a ``G_GEO_`` code or a string explaining the
exception.
:type status: int or string
:param url: The query URL that resulted in the error, if any.
:type url: string
:param response: The actual response returned from Google, if any.
:type response: dict
"""
Exception.__init__(self, status) # Exception is an old-school class
self.status = status
self.url = url
self.response = response
def __str__(self):
"""Return a string representation of this :exc:`GeocoderError`."""
return 'Error %s\nQuery: %s' % (self.status, self.url)
def <|fim_middle|>(self):
"""Return a unicode representation of this :exc:`GeocoderError`."""
return unicode(self.__str__())
<|fim▁end|> | __unicode__ |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
class Referral(Note):
"""A record of a particular patient's referral to a particular center."""
STATUS_SUCCESSFUL = 'S'
STATUS_PENDING = 'P'
STATUS_UNSUCCESSFUL = 'U'
# Status if there are no referrals of a specific type
# Used in aggregate_referral_status
NO_REFERRALS_CURRENTLY = "No referrals currently"
REFERRAL_STATUSES = (
(STATUS_SUCCESSFUL, 'Successful'),
(STATUS_PENDING, 'Pending'),
(STATUS_UNSUCCESSFUL, 'Unsuccessful'),
)
location = models.ManyToManyField(ReferralLocation)
comments = models.TextField(blank=True)
status = models.CharField(
max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING)
kind = models.ForeignKey(
ReferralType,
help_text="The kind of care the patient should recieve at the "
"referral location.")
def __str__(self):
"""Provides string to display on front end for referral.
For FQHC referrals, returns referral kind and date.
For non-FQHC referrals, returns referral location and date.
"""
formatted_date = self.written_datetime.strftime("%D")
if self.kind.is_fqhc:
return "%s referral on %s" % (self.kind, formatted_date)
else:
location_names = [loc.name for loc in self.location.all()]
locations = " ,".join(location_names)
return "Referral to %s on %s" % (locations, formatted_date)
@staticmethod
def aggregate_referral_status(referrals):
referral_status_output = ""
if referrals:
all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL
for referral in referrals)
if all_successful:
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
referral_status_output = Referral.NO_REFERRALS_CURRENTLY
return referral_status_output
class FollowupRequest(Note, CompletableMixin):
referral = models.ForeignKey(Referral)
contact_instructions = models.TextField()
MARK_DONE_URL_NAME = 'new-patient-contact'
ADMIN_URL_NAME = ''
def class_name(self):
return self.__class__.__name__
def short_name(self):
return "Referral"
def summary(self):
return self.contact_instructions
def mark_done_url(self):
return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:referral_followuprequest_change',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral)
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
appointment_location = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")
no_show_reason = models.ForeignKey(
NoShowReason,
blank=True,
null=True,
help_text="If the patient didn't go to the appointment, why not?")
def short_text(self):
"""Return a short text description of this followup and what happened.
Used on the patient chart view as the text in the list of followups.
"""
<|fim▁hole|> if self.pt_showed == self.PTSHOW_YES:
text = "Patient went to appointment at " + locations + "."
else:
if self.has_appointment == self.PTSHOW_YES:
text = ("Patient made appointment at " + locations +
"but has not yet gone.")
else:
if self.contact_status.patient_reached:
text = ("Successfully contacted patient but the "
"patient has not made an appointment yet.")
else:
text = "Did not successfully contact patient"
return text<|fim▁end|> | text = ""
locations = " ,".join(map(str, self.appointment_location.all())) |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
class Referral(Note):
<|fim_middle|>
class FollowupRequest(Note, CompletableMixin):
referral = models.ForeignKey(Referral)
contact_instructions = models.TextField()
MARK_DONE_URL_NAME = 'new-patient-contact'
ADMIN_URL_NAME = ''
def class_name(self):
return self.__class__.__name__
def short_name(self):
return "Referral"
def summary(self):
return self.contact_instructions
def mark_done_url(self):
return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:referral_followuprequest_change',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral)
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
appointment_location = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")
no_show_reason = models.ForeignKey(
NoShowReason,
blank=True,
null=True,
help_text="If the patient didn't go to the appointment, why not?")
def short_text(self):
"""Return a short text description of this followup and what happened.
Used on the patient chart view as the text in the list of followups.
"""
text = ""
locations = " ,".join(map(str, self.appointment_location.all()))
if self.pt_showed == self.PTSHOW_YES:
text = "Patient went to appointment at " + locations + "."
else:
if self.has_appointment == self.PTSHOW_YES:
text = ("Patient made appointment at " + locations +
"but has not yet gone.")
else:
if self.contact_status.patient_reached:
text = ("Successfully contacted patient but the "
"patient has not made an appointment yet.")
else:
text = "Did not successfully contact patient"
return text
<|fim▁end|> | """A record of a particular patient's referral to a particular center."""
STATUS_SUCCESSFUL = 'S'
STATUS_PENDING = 'P'
STATUS_UNSUCCESSFUL = 'U'
# Status if there are no referrals of a specific type
# Used in aggregate_referral_status
NO_REFERRALS_CURRENTLY = "No referrals currently"
REFERRAL_STATUSES = (
(STATUS_SUCCESSFUL, 'Successful'),
(STATUS_PENDING, 'Pending'),
(STATUS_UNSUCCESSFUL, 'Unsuccessful'),
)
location = models.ManyToManyField(ReferralLocation)
comments = models.TextField(blank=True)
status = models.CharField(
max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING)
kind = models.ForeignKey(
ReferralType,
help_text="The kind of care the patient should recieve at the "
"referral location.")
def __str__(self):
"""Provides string to display on front end for referral.
For FQHC referrals, returns referral kind and date.
For non-FQHC referrals, returns referral location and date.
"""
formatted_date = self.written_datetime.strftime("%D")
if self.kind.is_fqhc:
return "%s referral on %s" % (self.kind, formatted_date)
else:
location_names = [loc.name for loc in self.location.all()]
locations = " ,".join(location_names)
return "Referral to %s on %s" % (locations, formatted_date)
@staticmethod
def aggregate_referral_status(referrals):
referral_status_output = ""
if referrals:
all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL
for referral in referrals)
if all_successful:
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
referral_status_output = Referral.NO_REFERRALS_CURRENTLY
return referral_status_output |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
class Referral(Note):
"""A record of a particular patient's referral to a particular center."""
STATUS_SUCCESSFUL = 'S'
STATUS_PENDING = 'P'
STATUS_UNSUCCESSFUL = 'U'
# Status if there are no referrals of a specific type
# Used in aggregate_referral_status
NO_REFERRALS_CURRENTLY = "No referrals currently"
REFERRAL_STATUSES = (
(STATUS_SUCCESSFUL, 'Successful'),
(STATUS_PENDING, 'Pending'),
(STATUS_UNSUCCESSFUL, 'Unsuccessful'),
)
location = models.ManyToManyField(ReferralLocation)
comments = models.TextField(blank=True)
status = models.CharField(
max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING)
kind = models.ForeignKey(
ReferralType,
help_text="The kind of care the patient should recieve at the "
"referral location.")
def __str__(self):
<|fim_middle|>
@staticmethod
def aggregate_referral_status(referrals):
referral_status_output = ""
if referrals:
all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL
for referral in referrals)
if all_successful:
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
referral_status_output = Referral.NO_REFERRALS_CURRENTLY
return referral_status_output
class FollowupRequest(Note, CompletableMixin):
referral = models.ForeignKey(Referral)
contact_instructions = models.TextField()
MARK_DONE_URL_NAME = 'new-patient-contact'
ADMIN_URL_NAME = ''
def class_name(self):
return self.__class__.__name__
def short_name(self):
return "Referral"
def summary(self):
return self.contact_instructions
def mark_done_url(self):
return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:referral_followuprequest_change',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral)
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
appointment_location = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")
no_show_reason = models.ForeignKey(
NoShowReason,
blank=True,
null=True,
help_text="If the patient didn't go to the appointment, why not?")
def short_text(self):
"""Return a short text description of this followup and what happened.
Used on the patient chart view as the text in the list of followups.
"""
text = ""
locations = " ,".join(map(str, self.appointment_location.all()))
if self.pt_showed == self.PTSHOW_YES:
text = "Patient went to appointment at " + locations + "."
else:
if self.has_appointment == self.PTSHOW_YES:
text = ("Patient made appointment at " + locations +
"but has not yet gone.")
else:
if self.contact_status.patient_reached:
text = ("Successfully contacted patient but the "
"patient has not made an appointment yet.")
else:
text = "Did not successfully contact patient"
return text
<|fim▁end|> | """Provides string to display on front end for referral.
For FQHC referrals, returns referral kind and date.
For non-FQHC referrals, returns referral location and date.
"""
formatted_date = self.written_datetime.strftime("%D")
if self.kind.is_fqhc:
return "%s referral on %s" % (self.kind, formatted_date)
else:
location_names = [loc.name for loc in self.location.all()]
locations = " ,".join(location_names)
return "Referral to %s on %s" % (locations, formatted_date) |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
class Referral(Note):
"""A record of a particular patient's referral to a particular center."""
STATUS_SUCCESSFUL = 'S'
STATUS_PENDING = 'P'
STATUS_UNSUCCESSFUL = 'U'
# Status if there are no referrals of a specific type
# Used in aggregate_referral_status
NO_REFERRALS_CURRENTLY = "No referrals currently"
REFERRAL_STATUSES = (
(STATUS_SUCCESSFUL, 'Successful'),
(STATUS_PENDING, 'Pending'),
(STATUS_UNSUCCESSFUL, 'Unsuccessful'),
)
location = models.ManyToManyField(ReferralLocation)
comments = models.TextField(blank=True)
status = models.CharField(
max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING)
kind = models.ForeignKey(
ReferralType,
help_text="The kind of care the patient should recieve at the "
"referral location.")
def __str__(self):
"""Provides string to display on front end for referral.
For FQHC referrals, returns referral kind and date.
For non-FQHC referrals, returns referral location and date.
"""
formatted_date = self.written_datetime.strftime("%D")
if self.kind.is_fqhc:
return "%s referral on %s" % (self.kind, formatted_date)
else:
location_names = [loc.name for loc in self.location.all()]
locations = " ,".join(location_names)
return "Referral to %s on %s" % (locations, formatted_date)
@staticmethod
def aggregate_referral_status(referrals):
<|fim_middle|>
class FollowupRequest(Note, CompletableMixin):
referral = models.ForeignKey(Referral)
contact_instructions = models.TextField()
MARK_DONE_URL_NAME = 'new-patient-contact'
ADMIN_URL_NAME = ''
def class_name(self):
return self.__class__.__name__
def short_name(self):
return "Referral"
def summary(self):
return self.contact_instructions
def mark_done_url(self):
return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:referral_followuprequest_change',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral)
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
appointment_location = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")
no_show_reason = models.ForeignKey(
NoShowReason,
blank=True,
null=True,
help_text="If the patient didn't go to the appointment, why not?")
def short_text(self):
"""Return a short text description of this followup and what happened.
Used on the patient chart view as the text in the list of followups.
"""
text = ""
locations = " ,".join(map(str, self.appointment_location.all()))
if self.pt_showed == self.PTSHOW_YES:
text = "Patient went to appointment at " + locations + "."
else:
if self.has_appointment == self.PTSHOW_YES:
text = ("Patient made appointment at " + locations +
"but has not yet gone.")
else:
if self.contact_status.patient_reached:
text = ("Successfully contacted patient but the "
"patient has not made an appointment yet.")
else:
text = "Did not successfully contact patient"
return text
<|fim▁end|> | referral_status_output = ""
if referrals:
all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL
for referral in referrals)
if all_successful:
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
referral_status_output = Referral.NO_REFERRALS_CURRENTLY
return referral_status_output |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
class Referral(Note):
"""A record of a particular patient's referral to a particular center."""
STATUS_SUCCESSFUL = 'S'
STATUS_PENDING = 'P'
STATUS_UNSUCCESSFUL = 'U'
# Status if there are no referrals of a specific type
# Used in aggregate_referral_status
NO_REFERRALS_CURRENTLY = "No referrals currently"
REFERRAL_STATUSES = (
(STATUS_SUCCESSFUL, 'Successful'),
(STATUS_PENDING, 'Pending'),
(STATUS_UNSUCCESSFUL, 'Unsuccessful'),
)
location = models.ManyToManyField(ReferralLocation)
comments = models.TextField(blank=True)
status = models.CharField(
max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING)
kind = models.ForeignKey(
ReferralType,
help_text="The kind of care the patient should recieve at the "
"referral location.")
def __str__(self):
"""Provides string to display on front end for referral.
For FQHC referrals, returns referral kind and date.
For non-FQHC referrals, returns referral location and date.
"""
formatted_date = self.written_datetime.strftime("%D")
if self.kind.is_fqhc:
return "%s referral on %s" % (self.kind, formatted_date)
else:
location_names = [loc.name for loc in self.location.all()]
locations = " ,".join(location_names)
return "Referral to %s on %s" % (locations, formatted_date)
@staticmethod
def aggregate_referral_status(referrals):
referral_status_output = ""
if referrals:
all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL
for referral in referrals)
if all_successful:
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
referral_status_output = Referral.NO_REFERRALS_CURRENTLY
return referral_status_output
class FollowupRequest(Note, CompletableMixin):
<|fim_middle|>
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
appointment_location = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")
no_show_reason = models.ForeignKey(
NoShowReason,
blank=True,
null=True,
help_text="If the patient didn't go to the appointment, why not?")
def short_text(self):
"""Return a short text description of this followup and what happened.
Used on the patient chart view as the text in the list of followups.
"""
text = ""
locations = " ,".join(map(str, self.appointment_location.all()))
if self.pt_showed == self.PTSHOW_YES:
text = "Patient went to appointment at " + locations + "."
else:
if self.has_appointment == self.PTSHOW_YES:
text = ("Patient made appointment at " + locations +
"but has not yet gone.")
else:
if self.contact_status.patient_reached:
text = ("Successfully contacted patient but the "
"patient has not made an appointment yet.")
else:
text = "Did not successfully contact patient"
return text
<|fim▁end|> | referral = models.ForeignKey(Referral)
contact_instructions = models.TextField()
MARK_DONE_URL_NAME = 'new-patient-contact'
ADMIN_URL_NAME = ''
def class_name(self):
return self.__class__.__name__
def short_name(self):
return "Referral"
def summary(self):
return self.contact_instructions
def mark_done_url(self):
return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:referral_followuprequest_change',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.