hexsha
stringlengths 40
40
| size
int64 3
1.03M
| ext
stringclasses 10
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 3
972
| max_stars_repo_name
stringlengths 6
130
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
972
| max_issues_repo_name
stringlengths 6
130
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
116k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
972
| max_forks_repo_name
stringlengths 6
130
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 3
1.03M
| avg_line_length
float64 1.13
941k
| max_line_length
int64 2
941k
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2b4b523dc3affd3f0fdb8ee01aec0662e90656e0
| 2,395
|
py
|
Python
|
ost/s1/burst_batch.py
|
EOX-A/OpenSarToolk
|
b0c24065cef282cb433b5f0c14eb535c6c7cbf0c
|
[
"MIT"
] | 1
|
2020-04-03T17:01:16.000Z
|
2020-04-03T17:01:16.000Z
|
ost/s1/burst_batch.py
|
EOX-A/OpenSarToolk
|
b0c24065cef282cb433b5f0c14eb535c6c7cbf0c
|
[
"MIT"
] | 10
|
2020-05-29T16:21:17.000Z
|
2021-03-05T12:23:57.000Z
|
ost/s1/burst_batch.py
|
EOX-A/OpenSarToolk
|
b0c24065cef282cb433b5f0c14eb535c6c7cbf0c
|
[
"MIT"
] | 1
|
2021-09-24T10:53:39.000Z
|
2021-09-24T10:53:39.000Z
|
import os
import logging
from godale._concurrent import Executor
from ost.s1.burst_to_ard import burst_to_ard
from ost.s1 import burst_inventory
logger = logging.getLogger(__name__)
# ---------------------------------------------------
# Global variable
PRODUCT_LIST = [
'bs.HH', 'bs.VV', 'bs.HV', 'bs.VH',
'coh.VV', 'coh.VH', 'coh.HH', 'coh.HV',
'pol.Entropy', 'pol.Anisotropy', 'pol.Alpha'
]
def bursts_to_ards(
burst_gdf,
config_dict,
executor_type='concurrent_processes',
max_workers=1
):
logger.info('Processing all single bursts to ARD')
proc_inventory = burst_inventory.prepare_burst_inventory(burst_gdf, config_dict)
# we update max_workers in case we have less gpt_max_workers
# then cpus available
if max_workers > os.cpu_count():
max_workers = os.cpu_count()
if max_workers == 1 or len(burst_gdf) == 1:
config_dict['gpt_max_workers'] = os.cpu_count()
elif max_workers <= os.cpu_count():
config_dict['gpt_max_workers'] = int(os.cpu_count() / len(burst_gdf))
elif len(burst_gdf) <= max_workers:
config_dict['gpt_max_workers'] = int(max_workers / len(burst_gdf))
max_workers = int(len(burst_gdf))
out_files = {'bs': [], 'ls': [], 'coh': [], 'pol': []}
# now we run with godale, which works also with 1 worker
if max_workers == 1 or len(burst_gdf) == 1:
for burst in proc_inventory.iterrows():
burst_id, burst_date, out_bs, \
out_ls, out_pol, out_coh, error = burst_to_ard(
burst=burst,
config_dict=config_dict
)
out_files['bs'].append(out_bs)
out_files['ls'].append(out_ls)
out_files['coh'].append(out_coh)
out_files['pol'].append(out_pol)
else:
executor = Executor(executor=executor_type, max_workers=max_workers)
for task in executor.as_completed(
func=burst_to_ard,
iterable=proc_inventory.iterrows(),
fargs=[config_dict]
):
burst_id, burst_date, out_bs, \
out_ls, out_pol, out_coh, error = task.result()
out_files['bs'].append(out_bs)
out_files['ls'].append(out_ls)
out_files['coh'].append(out_coh)
out_files['pol'].append(out_pol)
return out_files
| 34.214286
| 84
| 0.601253
|
2b794864d957482deb4258d96cda4b6704a6e69d
| 510
|
py
|
Python
|
基础教程/A1-Python与基础知识/算法第一步/ExampleCodes/chapter15/15-11_15-12.py
|
microsoft/ai-edu
|
2f59fa4d3cf19f14e0b291e907d89664bcdc8df3
|
[
"Apache-2.0"
] | 11,094
|
2019-05-07T02:48:50.000Z
|
2022-03-31T08:49:42.000Z
|
基础教程/A1-Python与基础知识/算法第一步/ExampleCodes/chapter15/15-11_15-12.py
|
microsoft/ai-edu
|
2f59fa4d3cf19f14e0b291e907d89664bcdc8df3
|
[
"Apache-2.0"
] | 157
|
2019-05-13T15:07:19.000Z
|
2022-03-23T08:52:32.000Z
|
基础教程/A1-Python与基础知识/算法第一步/ExampleCodes/chapter15/15-11_15-12.py
|
microsoft/ai-edu
|
2f59fa4d3cf19f14e0b291e907d89664bcdc8df3
|
[
"Apache-2.0"
] | 2,412
|
2019-05-07T02:55:15.000Z
|
2022-03-30T06:56:52.000Z
|
from Utilities import partition_v2
def q_sort_iteration(arr, low, high):
if low >= high:
return
regions = [[low, high]]
i = 0
while i < len(regions):
low = regions[i][0]
high = regions[i][1]
p = partition_v2(arr, low, high)
if p != -1:
regions.append([low, p - 1])
regions.append([p + 1, high])
i += 1
return
# 下面是 代码15-12
arr = [2, 1, 5, 8, 7, 13, 26, 4, 39, 0]
q_sort_iteration(arr, 0, len(arr) - 1)
print(arr)
| 20.4
| 41
| 0.517647
|
80e31ebf5434345054a827dc131d528ef254bed6
| 256
|
py
|
Python
|
cart/context_processors.py
|
itzomen/E-shop
|
a37e4cc90bbfd598273410b167969fd4edf5fb1f
|
[
"MIT"
] | 4
|
2020-07-13T10:23:04.000Z
|
2020-11-06T04:42:28.000Z
|
cart/context_processors.py
|
itzomen/E-shop
|
a37e4cc90bbfd598273410b167969fd4edf5fb1f
|
[
"MIT"
] | 7
|
2021-04-08T19:24:02.000Z
|
2022-03-12T00:38:34.000Z
|
cart/context_processors.py
|
itzomen/E-shop
|
a37e4cc90bbfd598273410b167969fd4edf5fb1f
|
[
"MIT"
] | 1
|
2020-08-11T19:11:03.000Z
|
2020-08-11T19:11:03.000Z
|
from .models import Cart
def cart(request):
try:
if(request.user.id):
cart = Cart.objects.get(user=request.user)
return {'cart': cart}
# handles anonymous user
return {}
except:
return {}
| 23.272727
| 54
| 0.535156
|
b0592789441a13f70ca2d0d78eca5bb4e7b8b353
| 2,936
|
py
|
Python
|
tests/conftest.py
|
vytas7/falcon-multipart-tests
|
ec761223e9f9b49b82c82f77cb211c0dbad2b318
|
[
"Apache-2.0"
] | 2
|
2019-10-07T17:34:19.000Z
|
2019-10-16T21:16:51.000Z
|
tests/conftest.py
|
vytas7/falcon-multipart-tests
|
ec761223e9f9b49b82c82f77cb211c0dbad2b318
|
[
"Apache-2.0"
] | null | null | null |
tests/conftest.py
|
vytas7/falcon-multipart-tests
|
ec761223e9f9b49b82c82f77cb211c0dbad2b318
|
[
"Apache-2.0"
] | null | null | null |
import functools
import io
import os
import pytest
from falcon.media.multipart import MultipartForm, MultipartParseOptions
from falcon.util.reader import BufferedReader
try:
from falcon.cyutil.reader import BufferedReader as CyBufferedReader
except ImportError:
CyBufferedReader = None
PARSE_OPTIONS = MultipartParseOptions()
FORM1_BOUNDARY = b'BOUNDARYxxxxxxxxxxxxxxxxxxxxxxx'
FORM1_MIB_SIZE = int(os.environ.get('TEST_FORM_MIB_SIZE', '5120'))
FORM1 = (
b'--BOUNDARYxxxxxxxxxxxxxxxxxxxxxxx\r\n'
b'Content-Disposition: form-data; name="file"; filename="bytes"\r\n'
b'Content-Type: application/x-falcon\r\n\r\n' +
b'123456789abcdef\n' * 64 * 1024 * FORM1_MIB_SIZE +
b'\r\n'
b'--BOUNDARYxxxxxxxxxxxxxxxxxxxxxxx\r\n'
b'Content-Disposition: form-data; name="empty"\r\n'
b'Content-Type: text/plain\r\n\r\n'
b'\r\n'
b'--BOUNDARYxxxxxxxxxxxxxxxxxxxxxxx--\r\n'
)
STREAM1 = io.BytesIO(FORM1)
@functools.lru_cache(maxsize=65536)
def _part_factory(index):
base_offset, exponent = divmod(index, 1000)
return str((1337 + base_offset) ** (exponent + 1)).rstrip('L').encode()
PARSE_OPTIONS_MANY_PARTS = MultipartParseOptions()
PARSE_OPTIONS_MANY_PARTS.max_body_part_count = 1024 * 1024
FORM2_BOUNDARY = b'boundary--many-parts--'
FORM2_PART_COUNT = 65536
_part_template = (
'Content-Disposition: form-data; name="part{}"\r\n'
'Content-Type: application/x-falcon-peregrine\r\n\r\n'
)
FORM2 = (
b'--boundary--many-parts--\r\n' +
b''.join(
(
_part_template.format(index).encode() +
_part_factory(index) +
b'\r\n--boundary--many-parts--\r\n'
)
for index in range(FORM2_PART_COUNT)
) +
b'Content-Disposition: form-data; name="empty"\r\n'
b'Content-Type: text/plain\r\n\r\n'
b'\r\n'
b'--boundary--many-parts----\r\n'
)
STREAM2 = io.BytesIO(FORM2)
def stream_factory(stream_type, bsize, stream, length):
if stream_type == 'cythonized' and CyBufferedReader is None:
pytest.skip('cythonized BufferedReader is unavailable')
stream.seek(0)
cls = BufferedReader if stream_type == 'stream' else CyBufferedReader
return cls(stream.read, length, bsize)
@pytest.fixture
def form1():
def _factory(stream_type, bsize):
stream = stream_factory(stream_type, bsize, STREAM1, len(FORM1))
return MultipartForm(stream, FORM1_BOUNDARY, len(FORM1), PARSE_OPTIONS)
return _factory
@pytest.fixture
def expected_size1():
return FORM1_MIB_SIZE * 1024 ** 2
@pytest.fixture
def form2():
def _factory(stream_type, bsize):
stream = stream_factory(stream_type, bsize, STREAM2, len(FORM2))
return MultipartForm(
stream, FORM2_BOUNDARY, len(FORM2), PARSE_OPTIONS_MANY_PARTS)
return _factory
@pytest.fixture
def part_factory2():
return _part_factory
@pytest.fixture
def expected_parts2():
return FORM2_PART_COUNT
| 26.214286
| 79
| 0.700613
|
e516a10c07c3c50a1a25ecc7a9d457d1a8d90a0c
| 7,581
|
py
|
Python
|
ansible/venv/lib/python2.7/site-packages/ansible/modules/network/ios/ios_command.py
|
gvashchenkolineate/gvashchenkolineate_infra_trytravis
|
0fb18850afe0d8609693ba4b23f29c7cda17d97f
|
[
"MIT"
] | null | null | null |
ansible/venv/lib/python2.7/site-packages/ansible/modules/network/ios/ios_command.py
|
gvashchenkolineate/gvashchenkolineate_infra_trytravis
|
0fb18850afe0d8609693ba4b23f29c7cda17d97f
|
[
"MIT"
] | null | null | null |
ansible/venv/lib/python2.7/site-packages/ansible/modules/network/ios/ios_command.py
|
gvashchenkolineate/gvashchenkolineate_infra_trytravis
|
0fb18850afe0d8609693ba4b23f29c7cda17d97f
|
[
"MIT"
] | null | null | null |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = """
---
module: ios_command
version_added: "2.1"
author: "Peter Sprygada (@privateip)"
short_description: Run commands on remote devices running Cisco IOS
description:
- Sends arbitrary commands to an ios node and returns the results
read from the device. This module includes an
argument that will cause the module to wait for a specific condition
before returning or timing out if the condition is not met.
- This module does not support running commands in configuration mode.
Please use M(ios_config) to configure IOS devices.
extends_documentation_fragment: ios
notes:
- Tested against IOS 15.6
options:
commands:
description:
- List of commands to send to the remote ios device over the
configured provider. The resulting output from the command
is returned. If the I(wait_for) argument is provided, the
module is not returned until the condition is satisfied or
the number of retries has expired. If a command sent to the
device requires answering a prompt, it is possible to pass
a dict containing I(command), I(answer) and I(prompt).
Common answers are 'y' or "\\r" (carriage return, must be
double quotes). See examples.
required: true
wait_for:
description:
- List of conditions to evaluate against the output of the
command. The task will wait for each condition to be true
before moving forward. If the conditional is not true
within the configured number of retries, the task fails.
See examples.
aliases: ['waitfor']
version_added: "2.2"
match:
description:
- The I(match) argument is used in conjunction with the
I(wait_for) argument to specify the match policy. Valid
values are C(all) or C(any). If the value is set to C(all)
then all conditionals in the wait_for must be satisfied. If
the value is set to C(any) then only one of the values must be
satisfied.
default: all
choices: ['any', 'all']
version_added: "2.2"
retries:
description:
- Specifies the number of retries a command should by tried
before it is considered failed. The command is run on the
target device every retry and evaluated against the
I(wait_for) conditions.
default: 10
interval:
description:
- Configures the interval in seconds to wait between retries
of the command. If the command does not pass the specified
conditions, the interval indicates how long to wait before
trying the command again.
default: 1
"""
EXAMPLES = r"""
tasks:
- name: run show version on remote devices
ios_command:
commands: show version
- name: run show version and check to see if output contains IOS
ios_command:
commands: show version
wait_for: result[0] contains IOS
- name: run multiple commands on remote nodes
ios_command:
commands:
- show version
- show interfaces
- name: run multiple commands and evaluate the output
ios_command:
commands:
- show version
- show interfaces
wait_for:
- result[0] contains IOS
- result[1] contains Loopback0
- name: run commands that require answering a prompt
ios_command:
commands:
- command: 'clear counters GigabitEthernet0/1'
prompt: 'Clear "show interface" counters on this interface \[confirm\]'
answer: 'y'
- command: 'clear counters GigabitEthernet0/2'
prompt: '[confirm]'
answer: "\r"
"""
RETURN = """
stdout:
description: The set of responses from the commands
returned: always apart from low level errors (such as action plugin)
type: list
sample: ['...', '...']
stdout_lines:
description: The value of stdout split into a list
returned: always apart from low level errors (such as action plugin)
type: list
sample: [['...', '...'], ['...'], ['...']]
failed_conditions:
description: The list of conditionals that have failed
returned: failed
type: list
sample: ['...', '...']
"""
import time
from ansible.module_utils._text import to_text
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.common.parsing import Conditional
from ansible.module_utils.network.common.utils import transform_commands, to_lines
from ansible.module_utils.network.ios.ios import run_commands
from ansible.module_utils.network.ios.ios import ios_argument_spec, check_args
def parse_commands(module, warnings):
commands = transform_commands(module)
if module.check_mode:
for item in list(commands):
if not item['command'].startswith('show'):
warnings.append(
'Only show commands are supported when using check mode, not '
'executing %s' % item['command']
)
commands.remove(item)
return commands
def main():
"""main entry point for module execution
"""
argument_spec = dict(
commands=dict(type='list', required=True),
wait_for=dict(type='list', aliases=['waitfor']),
match=dict(default='all', choices=['all', 'any']),
retries=dict(default=10, type='int'),
interval=dict(default=1, type='int')
)
argument_spec.update(ios_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
warnings = list()
result = {'changed': False, 'warnings': warnings}
check_args(module, warnings)
commands = parse_commands(module, warnings)
wait_for = module.params['wait_for'] or list()
try:
conditionals = [Conditional(c) for c in wait_for]
except AttributeError as exc:
module.fail_json(msg=to_text(exc))
retries = module.params['retries']
interval = module.params['interval']
match = module.params['match']
while retries > 0:
responses = run_commands(module, commands)
for item in list(conditionals):
if item(responses):
if match == 'any':
conditionals = list()
break
conditionals.remove(item)
if not conditionals:
break
time.sleep(interval)
retries -= 1
if conditionals:
failed_conditions = [item.raw for item in conditionals]
msg = 'One or more conditional statements have not been satisfied'
module.fail_json(msg=msg, failed_conditions=failed_conditions)
result.update({
'stdout': responses,
'stdout_lines': list(to_lines(responses)),
})
module.exit_json(**result)
if __name__ == '__main__':
main()
| 32.676724
| 82
| 0.664424
|
c72f4048f11a759c4ed22abcc5859996ff15bfba
| 10,997
|
py
|
Python
|
TestParametersALL/surface_PSO2 - Test Parameters.py
|
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
|
0efa9606d355be0035385701479148e6f1bb7710
|
[
"BSD-2-Clause"
] | null | null | null |
TestParametersALL/surface_PSO2 - Test Parameters.py
|
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
|
0efa9606d355be0035385701479148e6f1bb7710
|
[
"BSD-2-Clause"
] | null | null | null |
TestParametersALL/surface_PSO2 - Test Parameters.py
|
induraj2020/A7--Optimization-of-Surface-Area-in-land-for-construction
|
0efa9606d355be0035385701479148e6f1bb7710
|
[
"BSD-2-Clause"
] | null | null | null |
from scipy import *
from math import *
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.path import Path
import matplotlib.patches as patches
import sys
import pyclipper
from functools import *
import time
fig = plt.figure()
canv = fig.add_subplot(1,1,1)
canv.set_xlim(0,500)
canv.set_ylim(0,500)
## PARAMETERS:
Nb_Cycles_LST = [10000] # [500, 1000, 1500, 5000, 10000, 20000]
Nb_Indiv_LST = [5, 7, 10, 15, 20] #[5] # [5, 7, 10, 15, 20]
psi_LST = [0.7] # [0.2, 0.4, 0.5, 0.7, 0.8]
c1_LST = [0.2] # [0.2, 0.8, 1.0, 1.5, 2.0]
c2_LST = [0.8] # [0.2, 0.8, 1.0, 1.5, 2.0]
numTests = 30 # Number of test to Statistics Analysis.
( polygone, maxPolArea ) = ( ((10,10),(10,400),(400,400),(400,10)) , 152100)
# ( polygone, maxPolArea )= ( ((10,10),(10,300),(250,300),(350,130),(200,10)) , 81100)
# ( polygone, maxPolArea ) =( ((50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)) , 52500)
# ( polygone, maxPolArea ) =( ((50,50),(50,400),(220,310),(220,170),(330,170),(330,480),(450,480),(450,50)) , 116650)
anglemin = 0.01
anglemax = 89.99
def poly2list(polygone):
polygonefig = list(polygone)
polygonefig.append(polygonefig[0])
return polygonefig
def dessine(polyfig, rectfig , iteration, pause=0.01):
global canv, codes
canv.clear()
codes = [Path.MOVETO]
for i in range(len(polyfig) - 2):
codes.append(Path.LINETO)
codes.append(Path.CLOSEPOLY)
path = Path(polyfig, codes)
patch = patches.PathPatch(path, facecolor='orange', lw=2)
canv.add_patch(patch)
canv.autoscale_view()
codes = [Path.MOVETO]
for i in range(len(rectfig) - 2):
codes.append(Path.LINETO)
codes.append(Path.CLOSEPOLY)
path = Path(rectfig, codes)
patch = patches.PathPatch(path, facecolor='grey', lw=2)
canv.add_patch(patch)
plt.title("Aire: {} Aire/Max: {}% Iteration: {}".format(round(aire(rectfig[:-1]), 2), round((aire(rectfig[:-1])/maxPolArea)*100,1), iteration) )
plt.draw()
plt.pause(pause)
def dispRes(best_route, best_dist):
print("Pos = {}".format(best_route))
print("Area = {}".format(best_dist))
def drawStats(Htemps, Hbest, parametersSTR, titleName):
fig2 = plt.figure(2,figsize=(9,6))
plt.subplot(1,1,1)
plt.plot(Htemps, Hbest, label=parametersSTR) #plt.semilogy
plt.title(titleName)
plt.xlabel('Iterations')
plt.ylabel('Distance')
plt.legend()
def drawBoxPlot(BoxPlotData, xValues, xLabel, titleName):
fig3 = plt.figure(3,figsize=(6,6))
plt.subplot(1,1,1)
sns.boxplot( x=xValues, y=BoxPlotData, palette="Blues")
# plt.boxplot(BoxPlotData)
# plt.xticks(range(1, len(BoxPlotData)+1), xLables)
plt.title(titleName)
plt.xlabel(xLabel)
plt.ylabel('Percentage Area Best Rectangule')
plt.legend()
def PolygonArea(corners):
n = len(corners) # of corners
area = 0.0
for i in range(n):
j = (i + 1) % n
area += corners[i][0] * corners[j][1]
area -= corners[j][0] * corners[i][1]
area = abs(area) / 2.0
return area
def getBornes(polygone):
lpoly = list(polygone)
return reduce(lambda acc,e: (min(e[0],acc[0]),max(e[0],acc[1]),min(e[1],acc[2]),max(e[1],acc[3])),lpoly[1:],(lpoly[0][0],lpoly[0][0],lpoly[0][1],lpoly[0][1]))
def initPop(nb,polygone):
return [initUn(polygone) for i in range(nb)]
def initUn(polygone):
global xmin,xmax,ymin,ymax;
anglemin = 1
anglemax = 89
boolOK = False
while boolOK==False:
xo=random.uniform(xmin,xmax) # centre point x coord
yo=random.uniform(ymin,ymax) # centre point y coord
xa=xo+pow(-1,random.randint(0,1))*random.uniform(10,min(xo-xmin,xmax-xo)) # corner A - x coord
ya=yo+pow(-1,random.randint(0,1))*random.uniform(10,min(yo-ymin,ymax-yo)) # corner A - y coord
angle = random.uniform(anglemin,anglemax) # angle
pos=[round(xa),round(ya),round(xo),round(yo),angle] # all above are put together
rect=post2rect(pos) # using all above, we generate rectangle
boolOK = verifcontrainte(rect, polygone) # to verify if all these 4 points are within polygone
ev = aire(post2rect(pos)) # finding area of the rect formed
return {'vit': [0,0,0,0,0], 'pos': pos, 'fit': ev, 'bestfit': ev, 'bestpos': pos, 'bestvois': [0,0,0,0,0]}
def post2rect(pos):
xa, ya = pos[0], pos[1] # point A
xo, yo = pos[2], pos[3] # point o
angle = pos[-1] # angle in degree
alpha = pi * angle / 180 # angle in radian
xd = cos(alpha)*(xa-xo) - sin(alpha)*(ya-yo) + xo # generating point d
yd = sin(alpha)*(xa-xo) + cos(alpha)*(ya-yo) + yo
xc, yc = 2*xo - xa, 2*yo - ya # generating point c
xb, yb = 2*xo - xd, 2*yo - yd # generating point b
return ((round(xa),round(ya)),(round(xb),round(yb)),(round(xc),round(yc)),(round(xd),round(yd)))
def verifcontrainte(rect, polygone):
try:
pc = pyclipper.Pyclipper()
pc.AddPath(polygone, pyclipper.PT_SUBJECT, True)
pc.AddPath(rect, pyclipper.PT_CLIP, True)
clip = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
return (clip!=[]) and (len(clip[0])==len(rect)) and all(list(map(lambda e:list(e) in clip[0], rect)))
except pyclipper.ClipperException:
return False
def aire(p1):
l= length(p1[0],p1[1])
b= breath(p1[1],p1[2])
return l*b
def length(a,b):
return abs(a[1]-b[1])
def breath(b,c):
return abs(b[0]-c[0])
def getBest(population):
return dict(reduce(lambda acc, e: bestPartic(acc,e),population[1:],population[0]))
def bestPartic(p1,p2):
if (p1["fit"] > p2["fit"]):
return p1
else:
return p2
def update(particle, bestParticle):
nv = dict(particle)
if (particle["fit"] > particle["bestfit"]):
nv['bestpos'] = particle["pos"][:]
nv['bestfit'] = particle["fit"]
nv['bestvois'] = bestParticle["bestpos"][:]
return nv
def move(particle,psi,c1,c2):
nv= dict(particle)
tu_velocity1= particle['vit']
tu_velocity1= times(psi,tu_velocity1)
tu_loc_velocity= minus(particle['bestpos'],particle['pos'])
tu_loc_velocity= times(c1*random.uniform(0,1),tu_loc_velocity)
tu_gro_velocity= minus(particle['bestvois'],particle['pos'])
tu_gro_velocity= times(c1*random.uniform(0,1),tu_gro_velocity)
velocity1_comb = add_list(tu_velocity1,tu_loc_velocity)
final_velocity = add_list(tu_gro_velocity, velocity1_comb)
final_move = add_list(final_velocity,particle['pos'])
pos = [round(final_move[0]), round(final_move[1]), round(final_move[2]), round(final_move[3]), final_move[4]]
rect = post2rect(pos)
boolOK = verifcontrainte(rect, polygone)
if boolOK==True:
nv['vit'] = final_velocity
nv['pos'] = pos
nv['fit'] = aire(post2rect(pos))
return nv
else:
return nv
def times(parameter,tu_velocity):
new_velocity=[parameter*element for element in tu_velocity]
return new_velocity
def minus(vel1,vel2):
vel = []
for i in range(len(vel1)):
vel.append(round(vel1[i] - vel2[i]))
return vel
def add_list(v1,v2):
new=[]
for i in range(len(v1)):
new.append(v1[i]+v2[i])
return new
def metropolis(ch1,dist1,ch2,dist2,T):
global best_route, best_dist, x, y
delta = dist1 - dist2
if delta <= 0:
if dist1 <= best['fit']:
best['bestfit'] = dist1
best['fit'] = dist1
best['bestpos'] = ch1[:]
best['pos'] = ch1[:]
return (ch1, dist1)
else:
if random.uniform(0,1) > exp(-delta/T):
return (ch2, dist2)
else:
return (ch1, dist1)
def main_PSO(Nb_Cycles, Nb_Indiv, psi, c1, c2 ):
global best
Htemps = []
Hbest = []
pos = initPop(Nb_Indiv,polygone)
best = getBest(pos)
best_cycle = best
polygonefig = poly2list(polygone)
k=0
z=0
no_iteration=0
ltaboo=10
best_of_best=[0]
best_of_best[0]=best.copy()
for z in range(Nb_Cycles):
pos=[update(e,best_cycle) for e in pos]
pos=[move(e,psi,c1,c2) for e in pos]
best_cycle=getBest(pos)
if best_cycle['bestfit']>best_of_best[0]['bestfit']: # Update Best_of_Best
best_of_best[0]=best_cycle.copy()
if(best_cycle['bestfit']>best['bestfit']):
best=best_cycle
else:
no_iteration=0
rand_pos = initUn(polygone)
(best_cycle['bestpos'], best_cycle['fit']) = metropolis(rand_pos['pos'], rand_pos['fit'], best['bestpos'], best['bestfit'],0.1) #10000000
if z % 10 == 0:
# dessine(polygonefig, poly2list(post2rect(best_of_best[0]["bestpos"])), z)
Htemps.append(z)
Hbest.append(best_of_best[0]['bestfit'])
Htemps.append(z)
Hbest.append(best_of_best[0]['bestfit'])
# dessine(polygonefig, poly2list(post2rect(best_of_best[0]["bestpos"])), z,1)
dispRes(best_of_best[0]['bestpos'], best_of_best[0]['bestfit'])
# titleName = ' NbPar: ' + str(Nb_Indiv) + ' PSI: ' + str(psi) + ' C1: ' + str(c1)
# parameterName = ' C2: ' + str(c2) + ' Average BestArea:' + str( round((aire(poly2list(post2rect(best_of_best[0]["bestpos"]))[:-1])/maxPolArea)*100,1) ) + "%"
# drawStats(Htemps, Hbest, parameterName, titleName)
return ( round((aire(poly2list(post2rect(best_of_best[0]["bestpos"]))[:-1])/maxPolArea)*100,1) )
# MAIN PART
xmin,xmax,ymin,ymax = getBornes(polygone)
HLastBest = []
HComputationTime = []
BoxPlotData = []
for Nb_Cycles in Nb_Cycles_LST:
for Nb_Indiv in Nb_Indiv_LST:
for psi in psi_LST:
for c1 in c1_LST:
for c2 in c2_LST:
HAvgBest = []
for i in range(numTests):
start_time = time.time()
HAvgBest.append( main_PSO(Nb_Cycles, Nb_Indiv, psi, c1, c2) ) #Run PSO
HComputationTime.append( time.time() - start_time )
BoxPlotData.append( HAvgBest )
# drawTimeVS(Nb_particleLST, timeSolutionMEAMLST, parameterName )
titleName = 'NbTest:' + str(numTests) + ' PSI: ' + str(psi) + ' C1: ' + str(c1) + ' C2: ' + str(c2)
print(BoxPlotData)
print(Nb_Indiv_LST)
drawBoxPlot(BoxPlotData, Nb_Indiv_LST, 'NbParticles', titleName)
print(HComputationTime)
plt.show()
| 37.152027
| 164
| 0.58425
|
b191331a4b52d3df10e740c700a6a4ee94d6c32d
| 13,808
|
py
|
Python
|
api/python/quilt3/main.py
|
NathanDeMaria/quilt
|
894c98c23fd4788b90ef75ff1b547c6258e5ccce
|
[
"Apache-2.0"
] | null | null | null |
api/python/quilt3/main.py
|
NathanDeMaria/quilt
|
894c98c23fd4788b90ef75ff1b547c6258e5ccce
|
[
"Apache-2.0"
] | null | null | null |
api/python/quilt3/main.py
|
NathanDeMaria/quilt
|
894c98c23fd4788b90ef75ff1b547c6258e5ccce
|
[
"Apache-2.0"
] | null | null | null |
"""
Parses the command-line arguments and runs a command.
"""
import argparse
import subprocess
import time
import sys
import dns.resolver
import requests
from . import api, session
from . import __version__ as quilt3_version
from .session import open_url
from .util import get_from_config, catalog_s3_url, catalog_package_url, QuiltException, PhysicalKey, \
fix_url, get_package_registry
from .registry import app
def cmd_config(catalog_url):
"""
Configure quilt3 to a Quilt stack
"""
if catalog_url is None:
existing_catalog_url = get_from_config('navigator_url')
if existing_catalog_url is not None:
print(existing_catalog_url)
else:
print('<None>')
else:
api.config(catalog_url)
def cmd_config_default_registry(default_remote_registry):
"""
Configure the default remote registry for quilt3
"""
api.config(default_remote_registry=default_remote_registry)
print(f"Successfully set the default remote registry to {default_remote_registry}")
def _test_url(url):
try:
response = requests.get(url)
if response.ok:
return True
return False
except requests.exceptions.ConnectionError:
return False
def _launch_local_catalog():
""""
Launches a docker container to run nginx hosting
the Quilt catalog on localhost:3000
"""
open_config = api._config()
command = ["docker", "run", "--rm"]
env = dict(REGISTRY_URL="http://localhost:5000",
S3_PROXY_URL=open_config["s3Proxy"],
ALWAYS_REQUIRE_AUTH="false",
CATALOG_MODE="LOCAL",
SSO_AUTH="DISABLED",
PASSWORD_AUTH="ENABLED",
API_GATEWAY=open_config["apiGatewayEndpoint"],
BINARY_API_GATEWAY=open_config["binaryApiGatewayEndpoint"])
for var in [f"{key}={value}" for key, value in env.items()]:
command += ["-e", var]
command += ["-p", "3000:80", "quiltdata/catalog"]
subprocess.Popen(command)
def _launch_local_s3proxy():
""""
Launches an s3 proxy (via docker)
on localhost:5002
"""
dns_resolver = dns.resolver.Resolver()
command = ["docker", "run", "--rm"]
# Workaround for a Docker-for-Mac bug in which the container
# ends up with a different DNS server than the host.
# Workaround #2: use only IPv4 addresses.
# Note: leaving this code in though it isn't called so that it
# can be reintroduced once Docker-for-Mac DNS works reliably.
# TODO: switch back to this local s3proxy or remove this function
if sys.platform == 'darwin':
nameservers = [ip for ip in dns_resolver.nameservers if ip.count('.') == 3]
command += ["--dns", nameservers[0]]
command += ["-p", "5002:80", "quiltdata/s3proxy"]
subprocess.Popen(command)
catalog_cmd_detailed_help = """
Run the Quilt catalog on your machine (requires Docker). Running
`quilt3 catalog` launches a webserver on your local machine using
Docker and a Python microservice that supplies temporary AWS
credentials to the catalog. Temporary credentials are derived from
your default AWS credentials (or active `AWS_PROFILE`) using
`boto3.sts.get_session_token`. For more details about configuring and
using AWS credentials in `boto3`, see the AWS documentation:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html
#### Previewing files in S3
The Quilt catalog allows users to preview files in S3 without
downloading. It relies on a API Gateway and AWS Lambda to generate
certain previews in the cloud. The catalog launched by `quilt3
catalog` sends preview requests to https://open.quiltdata.com. Preview
requests contain short-lived signed URLs generated using your AWS
credentials. Data is encrypted in transit and no data is retained by Quilt.
Nevertheless, it is recommended that you use `quilt3 catalog` only for public data.
We strongly encourage users with
sensitive data in S3 to run a private Quilt deployment. Visit
https://quiltdata.com for more information.
"""
def cmd_catalog(navigation_target=None, detailed_help=False):
"""
Run the Quilt catalog locally. If navigation_targets starts with 's3://', open file view. Otherwise assume it
refers to a package, following the pattern: BUCKET:USER/PKG
If detailed_help=True, display detailed information about the `quilt3 catalog` command and then exit
"""
from .registry import app # Delay importing it cause it's expensive.
if detailed_help:
print(catalog_cmd_detailed_help)
return
local_catalog_url = "http://localhost:3000"
# Build the catalog URL - we do this at the beginning so simple syntax errors return immediately
if navigation_target is None:
catalog_url = local_catalog_url
elif navigation_target.startswith("s3://"):
catalog_url = catalog_s3_url(local_catalog_url, navigation_target)
else:
num_colons = navigation_target.count(":")
assert num_colons == 1, f"To go to Package view, the input should follow the pattern BUCKET:USER/PKG. " \
f"However the input {navigation_target} has {num_colons} colons when it should have exactly one."
num_slashes = navigation_target.count("/")
assert num_slashes == 1, f"To go to Package view, the input should follow the pattern BUCKET:USER/PKG. " \
f"However the input {navigation_target} has {num_slashes} backslashes when it should have exactly one."
bucket, package_name = navigation_target.split(":")
catalog_url = catalog_package_url(local_catalog_url, bucket, package_name)
if not _test_url(local_catalog_url):
_launch_local_catalog()
# Make sure the containers are running and available before opening the browser window
print("Waiting for containers to launch...")
failure_timeout_secs = 15
poll_interval_secs = 0.5
start_time = time.time()
while True:
if time.time() - start_time > failure_timeout_secs:
catalog_failed = _test_url(local_catalog_url)
if not catalog_failed:
# Succeeded at the last second, let it proceed
break
raise QuiltException(f"The backend containers needed to run the catalog did not both successfully launch. "
f"Status:\n"
f"\tCATALOG: {'FAILED' if catalog_failed else 'SUCCEEDED'}")
if _test_url(local_catalog_url):
# Everything is working, proceed
break
else:
time.sleep(poll_interval_secs) # The containers can take a moment to launch
open_url(catalog_url)
app.run()
def cmd_disable_telemetry():
api._disable_telemetry()
print("Successfully disabled telemetry.")
def cmd_list_packages(registry):
registry_parsed = PhysicalKey.from_url(get_package_registry(fix_url(registry)))
for package_name in api._list_packages(registry=registry_parsed):
print(package_name)
def cmd_verify(name, registry, top_hash, dir, extra_files_ok):
pkg = api.Package._browse(name, registry, top_hash)
if pkg.verify(dir, extra_files_ok):
print("Verification succeeded")
return 0
else:
print("Verification failed")
return 1
def cmd_push(name, dir, registry, dest, message):
pkg = api.Package()
pkg.set_dir('.', dir)
pkg.push(name, registry=registry, dest=dest, message=message)
print("Successfully pushed the new package")
def create_parser():
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument(
"--version",
help="Show quilt3 version and exit",
action="version",
version=quilt3_version.strip()
)
subparsers = parser.add_subparsers(metavar="<command>")
subparsers.required = True
# login
shorthelp = "Log in to configured Quilt server"
login_p = subparsers.add_parser("login", description=shorthelp, help=shorthelp, allow_abbrev=False)
login_p.set_defaults(func=session.login)
# logout
shorthelp = "Log out of current Quilt server"
logout_p = subparsers.add_parser("logout", description=shorthelp, help=shorthelp, allow_abbrev=False)
logout_p.set_defaults(func=session.logout)
# config
shorthelp = "Configure Quilt"
config_p = subparsers.add_parser("config", description=shorthelp, help=shorthelp, allow_abbrev=False)
config_p.add_argument(
"catalog_url",
help="URL of catalog to config with, or empty string to reset the config",
type=str,
nargs="?"
)
config_p.set_defaults(func=cmd_config)
# config-default-registry
shorthelp = "Configure default remote registry for Quilt"
config_p = subparsers.add_parser("config-default-remote-registry", description=shorthelp, help=shorthelp, allow_abbrev=False)
config_p.add_argument(
"default_remote_registry",
help="The default remote registry to use, e.g. s3://quilt-ml",
type=str
)
config_p.set_defaults(func=cmd_config_default_registry)
# catalog
shorthelp = "Run Quilt catalog locally"
catalog_p = subparsers.add_parser("catalog", description=shorthelp, help=shorthelp, allow_abbrev=False)
catalog_p.add_argument(
"navigation_target",
help="Which page in the local catalog to open. Leave blank to go to the catalog landing page, pass in an "
"s3 url (e.g. 's3://bucket/myfile.txt') to go to file viewer, or pass in a package name in the form "
"'BUCKET:USER/PKG' to go to the package viewer.",
type=str,
nargs="?"
)
catalog_p.add_argument(
"--detailed_help",
help="Display detailed information about this command and then exit",
action="store_true",
)
catalog_p.set_defaults(func=cmd_catalog)
# disable-telemetry
shorthelp = "Disable anonymous usage metrics"
disable_telemetry_p = subparsers.add_parser("disable-telemetry", description=shorthelp, help=shorthelp, allow_abbrev=False)
disable_telemetry_p.set_defaults(func=cmd_disable_telemetry)
# install
shorthelp = "Install a package"
install_p = subparsers.add_parser("install", description=shorthelp, help=shorthelp, allow_abbrev=False)
install_p.add_argument(
"name",
help="Name of package, in the USER/PKG[/PATH] format",
type=str,
)
install_p.add_argument(
"--registry",
help="Registry where package is located, usually s3://MY-BUCKET. Defaults to the default remote registry.",
type=str,
required=False,
)
install_p.add_argument(
"--top-hash",
help="Hash of package to install. Defaults to latest.",
type=str,
required=False,
)
install_p.add_argument(
"--dest",
help="Local path to download files to.",
type=str,
required=False,
)
install_p.add_argument(
"--dest-registry",
help="Registry to install package to. Defaults to local registry.",
type=str,
required=False,
)
install_p.set_defaults(func=api.Package.install)
# list-packages
shorthelp = "List all packages in a registry"
list_packages_p = subparsers.add_parser("list-packages", description=shorthelp, help=shorthelp, allow_abbrev=False)
list_packages_p.add_argument(
"registry",
help="Registry for packages, e.g. s3://quilt-example",
type=str,
)
list_packages_p.set_defaults(func=cmd_list_packages)
# verify
shorthelp = "Verify that package contents matches a given directory"
verify_p = subparsers.add_parser("verify", description=shorthelp, help=shorthelp, allow_abbrev=False)
verify_p.add_argument(
"name",
help="Name of package, in the USER/PKG format",
type=str,
)
verify_p.add_argument(
"--registry",
help="Registry where package is located, usually s3://MY-BUCKET",
type=str,
required=True,
)
verify_p.add_argument(
"--top-hash",
help="Hash of package to verify",
type=str,
required=True,
)
verify_p.add_argument(
"--dir",
help="Directory to verify",
type=str,
required=True,
)
verify_p.add_argument(
"--extra-files-ok",
help="Whether extra files in the directory should cause a failure",
action="store_true"
)
verify_p.set_defaults(func=cmd_verify)
# push
shorthelp = "Pushes the new package to the remote registry"
push_p = subparsers.add_parser("push", description=shorthelp, help=shorthelp, allow_abbrev=False)
push_p.add_argument(
"name",
help="Name of package, in the USER/PKG format",
type=str,
)
push_p.add_argument(
"--dir",
help="Directory to add to the new package",
type=str,
required=True,
)
push_p.add_argument(
"--registry",
help="Registry where to create the new package. Defaults to the default remote registry.",
type=str,
)
push_p.add_argument(
"--dest",
help="Where to copy the objects in the package",
type=str,
)
push_p.add_argument(
"--message",
help="The commit message for the new package",
type=str,
)
push_p.set_defaults(func=cmd_push)
return parser
def main(args=None):
parser = create_parser()
args = parser.parse_args(args)
kwargs = vars(args)
func = kwargs.pop('func')
try:
return func(**kwargs)
except QuiltException as ex:
print(ex.message, file=sys.stderr)
return 1
| 35.314578
| 129
| 0.671567
|
7916ac373b55547f5f918640d120c14da1d1d5b0
| 7,612
|
py
|
Python
|
bw2io/strategies/generic.py
|
pjamesjoyce/brightway2-io
|
142fc26e2ffc47d8ec474386ee93ab2737a089ce
|
[
"BSD-3-Clause"
] | null | null | null |
bw2io/strategies/generic.py
|
pjamesjoyce/brightway2-io
|
142fc26e2ffc47d8ec474386ee93ab2737a089ce
|
[
"BSD-3-Clause"
] | null | null | null |
bw2io/strategies/generic.py
|
pjamesjoyce/brightway2-io
|
142fc26e2ffc47d8ec474386ee93ab2737a089ce
|
[
"BSD-3-Clause"
] | null | null | null |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *
from bw2data import mapping, Database, databases
from ..units import normalize_units as normalize_units_function
from ..errors import StrategyError
from ..utils import activity_hash, DEFAULT_FIELDS
from copy import deepcopy
import numbers
import numpy as np
import pprint
def format_nonunique_key_error(obj, fields, others):
template = """Object in source database can't be uniquely linked to target database.\nProblematic dataset is:\n{ds}\nPossible targets include (at least one not shown):\n{targets}"""
fields_to_print = list(fields or DEFAULT_FIELDS) + ['filename']
_ = lambda x: {field: x.get(field, "(missing)") for field in fields_to_print}
return template.format(
ds=pprint.pformat(_(obj)),
targets=pprint.pformat([_(x) for x in others])
)
def link_iterable_by_fields(unlinked, other=None, fields=None, kind=None,
internal=False, relink=False):
"""Generic function to link objects in ``unlinked`` to objects in ``other`` using fields ``fields``.
The database to be linked must have uniqueness for each object for the given ``fields``.
If ``kind``, limit objects in ``unlinked`` of type ``kind``.
If ``relink``, link to objects which already have an ``input``. Otherwise, skip already linked objects.
If ``internal``, linked ``unlinked`` to other objects in ``unlinked``. Each object must have the attributes ``database`` and ``code``."""
if kind:
kind = {kind} if isinstance(kind, str) else kind
if relink:
filter_func = lambda x: x.get('type') in kind
else:
filter_func = lambda x: x.get('type') in kind and not x.get('input')
else:
if relink:
filter_func = lambda x: True
else:
filter_func = lambda x: not x.get('input')
if internal:
other = unlinked
duplicates, candidates = {}, {}
try:
# Other can be a generator, so a bit convoluted
for ds in other:
key = activity_hash(ds, fields)
if key in candidates:
duplicates.setdefault(key, []).append(ds)
else:
candidates[key] = (ds['database'], ds['code'])
except KeyError:
raise StrategyError("Not all datasets in database to be linked have "
"``database`` or ``code`` attributes")
for container in unlinked:
for obj in filter(filter_func, container.get('exchanges', [])):
key = activity_hash(obj, fields)
if key in duplicates:
raise StrategyError(format_nonunique_key_error(obj, fields, duplicates[key]))
elif key in candidates:
obj['input'] = candidates[key]
return unlinked
def assign_only_product_as_production(db):
"""Assign only product as reference product.
Skips datasets that already have a reference product or no production exchanges. Production exchanges must have a ``name`` and an amount.
Will replace the following activity fields, if not already specified:
* 'name' - name of reference product
* 'unit' - unit of reference product
* 'production amount' - amount of reference product
"""
for ds in db:
if ds.get("reference product"):
continue
products = [x for x in ds.get('exchanges', []) if x.get('type') == 'production']
if len(products) == 1:
product = products[0]
assert product['name']
ds['reference product'] = product['name']
ds['production amount'] = product['amount']
ds['name'] = ds.get('name') or product['name']
ds['unit'] = ds.get('unit') or product.get('unit') or 'Unknown'
return db
def link_technosphere_by_activity_hash(db, external_db_name=None, fields=None):
"""Link technosphere exchanges using ``activity_hash`` function.
If ``external_db_name``, link against a different database; otherwise link internally.
If ``fields``, link using only certain fields."""
TECHNOSPHERE_TYPES = {"technosphere", "substitution", "production"}
if external_db_name is not None:
if external_db_name not in databases:
raise StrategyError("Can't find external database {}".format(
external_db_name))
other = (obj for obj in Database(external_db_name)
if obj.get('type', 'process') == 'process')
internal = False
else:
other = None
internal = True
return link_iterable_by_fields(db, other, internal=internal, kind=TECHNOSPHERE_TYPES, fields=fields)
def set_code_by_activity_hash(db, overwrite=False):
"""Use ``activity_hash`` to set dataset code.
By default, won't overwrite existing codes, but will if ``overwrite`` is ``True``."""
for ds in db:
if 'code' not in ds or overwrite:
ds['code'] = activity_hash(ds)
return db
def tupleize_categories(db):
for ds in db:
if ds.get('categories'):
ds['categories'] = tuple(ds['categories'])
for exc in ds.get('exchanges', []):
if exc.get('categories'):
exc['categories'] = tuple(exc['categories'])
return db
def drop_unlinked(db):
"""This is the nuclear option - use at your own risk!"""
for ds in db:
ds['exchanges'] = [obj for obj in ds['exchanges'] if obj.get('input')]
return db
def normalize_units(db):
"""Normalize units in datasets and their exchanges"""
for ds in db:
if 'unit' in ds:
ds['unit'] = normalize_units_function(ds['unit'])
for exc in ds.get('exchanges', []):
if 'unit' in exc:
exc['unit'] = normalize_units_function(exc['unit'])
for param in ds.get('parameters', {}).values():
if 'unit' in param:
param['unit'] = normalize_units_function(param['unit'])
return db
def add_database_name(db, name):
"""Add database name to datasets"""
for ds in db:
ds['database'] = name
return db
def convert_uncertainty_types_to_integers(db):
"""Generic number conversion function convert to floats. Return to integers."""
for ds in db:
for exc in ds['exchanges']:
try:
exc['uncertainty type'] = int(exc['uncertainty type'])
except:
pass
return db
def drop_falsey_uncertainty_fields_but_keep_zeros(db):
"""Drop fields like '' but keep zero and NaN.
Note that this doesn't strip `False`, which behaves *exactly* like 0.
"""
uncertainty_fields = [
'minimum',
'maximum',
'scale',
'shape',
'loc',
]
def drop_if_appropriate(exc):
for field in uncertainty_fields:
if field not in exc or exc[field] == 0:
continue
elif isinstance(exc[field], numbers.Number) and np.isnan(exc[field]):
continue
elif not exc[field]:
del exc[field]
for ds in db:
for exc in ds['exchanges']:
drop_if_appropriate(exc)
return db
def convert_activity_parameters_to_list(data):
"""Convert activity parameters from dictionary to list of dictionaries"""
def _(key, value):
dct = deepcopy(value)
dct['name'] = key
return dct
for ds in data:
if 'parameters' in ds:
ds['parameters'] = [_(x, y) for x, y in ds['parameters'].items()]
return data
| 34.757991
| 185
| 0.614687
|
9d1e09cd2dfade8ab8466b3f4a04883ccf450996
| 346
|
py
|
Python
|
strings.py
|
csamiselo/PythonScripsts
|
8ac0c086fca691d9c2dd0d8f758059c02f44e3e4
|
[
"MIT"
] | null | null | null |
strings.py
|
csamiselo/PythonScripsts
|
8ac0c086fca691d9c2dd0d8f758059c02f44e3e4
|
[
"MIT"
] | null | null | null |
strings.py
|
csamiselo/PythonScripsts
|
8ac0c086fca691d9c2dd0d8f758059c02f44e3e4
|
[
"MIT"
] | null | null | null |
def sum(number_one, number_two):
number_one_int = convert_integer(number_one)
number_two_int = convert_integer(number_two)
result = number_one_int + number_two_int
return result
def convert_integer(number_string):
converted_integer = int(number_string)
return converted_integer
answer = sum("1", "2")
print(answer)
| 19.222222
| 48
| 0.748555
|
015e0f8bb6fb38dfbf37824b9138a52711659836
| 52,309
|
py
|
Python
|
models/mhp.py
|
saadlabyad/aslsd
|
95a1cc660079972b45a77ec6dc587d9225489212
|
[
"BSD-3-Clause"
] | null | null | null |
models/mhp.py
|
saadlabyad/aslsd
|
95a1cc660079972b45a77ec6dc587d9225489212
|
[
"BSD-3-Clause"
] | null | null | null |
models/mhp.py
|
saadlabyad/aslsd
|
95a1cc660079972b45a77ec6dc587d9225489212
|
[
"BSD-3-Clause"
] | null | null | null |
# License: BSD 3 clause
import bisect
import copy
import itertools
import pickle
import numpy as np
from tqdm import tqdm
from aslsd.estimators.adaptive_stratified_estimator import AdaptiveStratified
from aslsd.estimators.estimator import Estimator
from aslsd.evaluation import goodness_of_fit as gof
from aslsd.events.process_path import ProcessPath
from aslsd.optim_logging.optim_logger import OptimLogger
from aslsd.plots import graphic_tools as gt
from aslsd.solvers.adam import ADAM
from aslsd.solvers.solver import Solver
from aslsd.utilities import useful_functions as uf
class MHP:
"""
Class for multivariate Hawkes processes (MHP) models.
Let :math:`\\mathbf{N}` be a d-dimensional counting process with
conditional intensity :math:`\\boldsymbol{\\lambda}`.
We say that :math:`\\mathbf{N}` is a (linear) MHP if, for all
:math:`i \\in[d]` and for all :math:`t \\geq 0`, we have
.. math::
\\lambda_{i}(t):=\\mu_{i}+\\sum_{j=1}^{d}
\\sum_{\\left\\{m: t_{m}^{j}<t\\right\\}} \\phi_{ij}\\left(t-t_{m}^{j}\\right),
where
* :math:`\\forall i,j \\in [d], \\phi_{ij}:[0,+\\infty) \\to [0,+\\infty)` is in :math:`L_{1}`. We write :math:`\\boldsymbol{\\phi}=(\\phi_{ij})_{i,j\\in [d]}`. The functions :math:`\\phi_{i j}` are called the kernels of the MHP;
* :math:`\\forall i \\in[d], \\mu_{i}>0`. The floats :math:`\\mu_{i}` are called baseline intensities.
For all :math:`i,j \\in [d]`, and for all :math:`t \\geq 0`, define
.. math::
\\psi_{ij}(t):=\\int_0^t \\phi_{ij}(u)\\mathrm{d}u.
We write :math:`\\boldsymbol{\\psi}=(\\psi_{ij})_{ij\\in [d]}`.
For all :math:`i,j,k \\in [d]`, and for all :math:`t,s \\geq 0`,
define
.. math::
\\Upsilon_{ijk}(t,s):=\\int_0^t \\phi_{ki}(u)\\phi_{kj}(u+s)\\mathrm{d}u.
We write :math:`\\boldsymbol{\\Upsilon}=(\\Upsilon_{ijk})_{ijk\\in [d]}`.
In our implementation, the class attribute
* `phi` denotes the matrix of kernel functions :math:`\\boldsymbol{\\phi}`, such that `phi[i][j]` is the kernel function :math:`\\phi_{ij}`;
* `psi` denotes the matrix of primitive functions :math:`\\boldsymbol{\\psi}`, such that `psi[i][j]` is the primitive function :math:`\\psi_{ij}`;
* `upsilon` denotes the tensor of correlation functions :math:`\\boldsymbol{\\Upsilon}`, such that `upsilon[i][j][k]` is the correlation function :math:`\\Upsilon_{ijk}`.
Attributes
----------
kernel_matrix : `list` of `list` of `KernelModel`
Matrix of kernel models.
d : `int`
Dimension of the MHP.
matrix_n_param : `list`
Matrix of numbers of parameters per kernel.
n_ker_param : `int`
Total number of kernel parameters.
ix_map : `list` of `list` of `dict`
DESCRIPTION. The default is None.
interval_map : `list` of `list` of `int`
Matrix of indices of first and last parameters of kernels in the flat
vector of parameters.
mu_names : `list` of `str`
List of names of baseline parameters.
ker_param_names : `list`
Tensor of names of kernel parameters.
param_bounds : TYPE, optional
Tensor of lower bounds of kernel parameters.
phi : `list` of `list` of `function`
Matrix of kernel functions.
diff_phi : `list` of `list` of `function`
Matrix of derivatives of kernel functions.
psi : `list` of `list` of `function`
Matrix of `psi` functions.
diff_psi : `list` of `list` of `function`
Matrix of derivatives of `psi` functions.
upsilon : `list` of `list` of `list` of `function`
Matrix of `upsilon` functions.
diff_sim_upsilon : `list` of `list` of `function`
Matrix of derivatives of auto-correlation `upsilon` functions.
diff_cross_upsilon : `list` of `list` of `list` of `function`
Matrix of derivatives of cross-correlation `upsilon` functions.
is_fitted : `bool`
True if the MHP has been fitted.
fitted_mu : `numpy.ndarray`
Fitted baseline.
fitted_ker_param : `numpy.ndarray`
Fitted kernel parameters.
fit_residuals : `numpy.ndarray`
Fit residuals.
fitted_adjacency : `numpy.ndarray`
Adjacency matrix for fitted kernel parameters.
fit_log : `aslsd.OptimLogger`
Fit log.
"""
def __init__(self, _kernel_matrix, d=None, matrix_n_param=None,
n_ker_param=None, ix_map=None, interval_map=None,
mu_names=None, ker_param_names=None,
param_bounds=None, phi=None, diff_phi=None, psi=None,
diff_psi=None, upsilon=None, diff_sim_upsilon=None,
diff_cross_upsilon=None, is_fitted=False,
fitted_mu=None, fitted_ker_param=None,
fit_residuals=None, fitted_adjacency=None, fit_log=None):
"""
Constructor of objects of class MHP.
Parameters
----------
_kernel_matrix : `list` of `list` of `KernelModel`
Matrix of kernel models.
"""
self.kernel_matrix = _kernel_matrix
# Kernel matrix
@property
def kernel_matrix(self):
"""
Kernel matrix of the MHP.
Setting the kernel matrix to a new value will automatically modify the
values of the other attributes that depend on it.
"""
return self._kernel_matrix
@kernel_matrix.setter
def kernel_matrix(self, M):
self._kernel_matrix = M
self.d = len(M)
self.matrix_n_param = self.get_n_param()
self.n_ker_param = sum([sum(self.matrix_n_param[i])
for i in range(self.d)])
ix_map, interval_map = self.make_maps()
self.ix_map = ix_map
self.interval_map = interval_map
param_names = self.get_param_names()
self.mu_names = param_names['mu']
self.ker_param_names = param_names['kernels']
self.param_bounds = self.get_param_bounds()
self.make_kernel_functionals()
@kernel_matrix.deleter
def kernel_matrix(self):
del self._kernel_matrix
# N params
def get_n_param(self):
"""
Get the matrix of number of parameters per kernel model.
If we denote by :math:`M` this matrix and by :math:`d` the
dimensionality of the MHP model, then :math:`M` is a :math:`d\\times d`
matrix which entry :math:`M_{ij}` is the number of parameters of kernel
:math:`\\phi_{ij}`.
Returns
-------
mat_n_param : `list` of `list` of `int`
Matrix of number of parameters per kernel model.
"""
d = self.d
mat_n_param = [[self._kernel_matrix[i][j].n_param for j in range(d)]
for i in range(d)]
return mat_n_param
# Parameters map
def make_maps(self):
"""
Compute the mapping between the MHP parameter indices and the flattened
vectors of parameters.
Denote by :math:`d` the dimensionality of the MHP model. For all
:math:`i, j \\in [d]`, denote the vector of parameters of the kernel
:math:`\\phi_{i j}` by :math:`\\vartheta_{i j}`, the dimension of
:math:`\\vartheta_{i j}` by :math:`\\rho_{i j}`, and the total number
of event type :math:`k` parameters of the model by
.. math::
n^{(k)}_{\\text {param }}:=1+\\sum_{i=1}^{d} \\rho_{k i},
where the additive term :math:`1` in the right hand side correspond to
the baseline parameter.
For all :math:`k \\in[d]`, concatenate the vectors of event type
:math:`k` kernel parameters as
.. math::
\\vartheta_{k}^{\\top}=\\left(\\vartheta_{k 1}^{\\top}, \\ldots, \\vartheta_{k d}^{\\top}\\right),
and define the vectors of event type :math:`k` MHP parameters
:math:`\\theta_{k}^{\\top}=\\left(\\mu_{k}, \\vartheta_{k}^{\\top}\\right)`.
Finally, define the vector of parameters :math:`\\theta` of the MHP by
.. math::
\\theta^{\\top}=\\left(\\theta_{1}^{\\top}, \\ldots, \\theta_{d}^{\\top}\\right) .
The vector of event type :math:`k` MHP parameters, :math:`\\theta_{k}`,
is the vector of dimension :math:`n^{(k)}_{\\text {param }}` containing
the baseline parameter :math:`\\mu_{k}` and the parameters of all
kernels :math:`(\\phi_{kj})_{j \\in [d]}`.
The list `ix_map` is such that for all :math:`k \\in [d]`, and for all
:math:`i \\in n_k`, `ix_map[k][i]` is a dictionary with keys `ker` and
`par`. The value `ix_map[k][i]['ker']` is an integer representing the
index `j` such that the `i`-th parameter of the flat vector of
parameters is a parameter of the kernel :math:`\\phi_{kj}`. By default,
since the `0`-th parameter of the flat vector corresponds to the
background rate :math:`\\mu_k`, we set `ix_map[k][0]['ker']` to `-1`.
Now let `j=ix_map[k][i]['ker']`. The value `ix_map[k][i]['par']` is an
integer representing the
index `p` such that the `i`-th parameter of the flat vector of
parameters is the `p`-th parameter of the kernel :math:`\\phi_{kj}`.
The list `interval_map` is such that for all :math:`k \\in [d]`, and for all
:math:`j \\in [d]`, `interval_map[k][j]` is a list of two integers
`[p,q]` such that `p` (resp. `q-1`) is the index of the first (resp.
last) parameter of kernel :math:`\\phi_{kj}` in the flat vector of
parameters.
Returns
-------
ix_map : `list` of `list` of `dict`
DESCRIPTION.
interval_map : `list` of `list` of `int`
Matrix of indices of first and last parameters of kernels in the
flat vector of parameters.
"""
d = self.d
ix_map = [[None for i in range(1+sum(self.matrix_n_param[k]))]
for k in range(d)]
interval_map = [[None for i in range(d)] for k in range(d)]
for k in range(d):
ix_map[k][0] = -1
ix_ker = 0
ix_param = 0
ix_left = 1
x = 1
n_param_k = 1+sum(self.matrix_n_param[k])
while x < n_param_k:
ix_map[k][x] = {'ker': ix_ker, 'par': ix_param}
if ix_param == self._kernel_matrix[k][ix_ker].n_param-1:
interval_map[k][ix_ker] = [ix_left, x+1]
ix_ker += 1
ix_param = 0
ix_left = x+1
x += 1
else:
ix_param += 1
x += 1
return ix_map, interval_map
def tensor2matrix_params(self, tensor_param):
"""
Convert the list of flat vectors of parameters to a vector of
background rates `mu` and a matrix of kernel parameters `kernel_param`.
Parameters
----------
tensor_param : TYPE
DESCRIPTION.
Returns
-------
mu : TYPE
Vector of background rates.
kernel_param : TYPE
Matrix of kernel parameters.
"""
d = self.d
mu = np.array([tensor_param[i][0] for i in range(d)])
kernel_param = np.array([[tensor_param[i][self.interval_map[i][j][0]:
self.interval_map[i][j][1]]
for j in range(d)] for i in range(d)],
dtype=object)
return mu, kernel_param
def matrix2tensor_params(self, mu, kernel_param):
"""
Convert the vector of background rates `mu` and the matrix of kernel
parameters `kernel_param` to the list of flat vectors of parameters.
Parameters
----------
mu : TYPE
Vector of baselines.
kernel_param : TYPE
Matrix of kernel parameters.
Returns
-------
TYPE
DESCRIPTION.
"""
d = self.d
x = [None]*d
for k in range(d):
x_k = []
# mu_k
x_k.append(mu[k])
# kernel parameters
for i in range(d):
x_k.extend(copy.deepcopy(kernel_param[k][i]))
x[k] = np.array(copy.deepcopy(x_k), dtype=object)
return np.array(x)
def tensor2matrix_solverpaths(self, tensor_paths):
# Convert the list of parameters
# tensor_paths is a tensor of paths of solvers per parameters
d = self.d
list_n = [len(tensor_paths[k]) for k in range(d)]
mu_paths = [[tensor_paths[k][n][0] for n in range(list_n[k])]
for k in range(d)]
kernel_param_paths = [[[tensor_paths[i][n][self.interval_map[i][j][0]:
self.interval_map[i][j][1]]
for n in range(list_n[i])] for j in range(d)]
for i in range(d)]
return mu_paths, kernel_param_paths
# Omega
def is_sbf(self):
d = self.d
for i, j in itertools.product(range(d), range(d)):
if not self._kernel_matrix[i][j].is_sbf():
return False
return True
# Bounds
def get_param_bounds(self):
d = self.d
bnds = [[self._kernel_matrix[i][j].get_param_bounds()
for j in range(d)] for i in range(d)]
return bnds
# Param names
def get_param_names(self, index_from_one=False):
"""
Get the matrix of parameter names per kernel model.
If we denote by :math:`M` this matrix and by :math:`d` the
dimensionality of the MHP model, then :math:`M` is a :math:`d\\times d`
matrix which entry :math:`M_{ij}` is the number of parameters of kernel
:math:`\\phi_{ij}`.
Returns
-------
mat_n_param : `list`
Matrix of number of parameters per kernel model.
"""
d = self.d
param_names = {}
if d == 1:
mu_names = ['$\u03BC$']
kernel = self._kernel_matrix[0][0]
vec_names = kernel.get_vec_param_names()
n_param = kernel.n_param
ker_param_names = [[None for j in range(d)] for i in range(d)]
ker_param_names[0][0] = [None]*n_param
for ix_param in range(n_param):
ix_ker = kernel.ix_map[ix_param]['ker']
ix_2 = kernel.ix_map[ix_param]['par']
if kernel.n_basis_ker == 1:
ker_param_names[0][0][ix_param] = vec_names[ix_ker][ix_2]
else:
ker_param_names[0][0][ix_param] = (vec_names[ix_ker][ix_2][:-1] + '_{'+str(ix_ker+int(index_from_one))+'}$')
else:
mu_names = ['$\u03BC_{'+str(i+int(index_from_one))+'}$'
for i in range(d)]
ker_param_names = [[None for j in range(d)] for i in range(d)]
for i, j in itertools.product(range(d), range(d)):
kernel = self._kernel_matrix[i][j]
vec_names = kernel.get_vec_param_names()
n_param = kernel.n_param
ker_param_names[i][j] = [None]*n_param
if kernel.n_basis_ker == 1:
for ix_param in range(n_param):
ix_ker = kernel.ix_map[ix_param]['ker']
ix_2 = kernel.ix_map[ix_param]['par']
ker_param_names[i][j][ix_param] = vec_names[ix_ker][ix_2][:-1]+ '_{'+str(i+int(index_from_one))+','+str(j+int(index_from_one))+'}$'
else:
for ix_param in range(n_param):
ix_ker = kernel.ix_map[ix_param]['ker']
ix_2 = kernel.ix_map[ix_param]['par']
ker_param_names[i][j][ix_param] = vec_names[ix_ker][ix_2][:-1]+ '_{'+str(i+int(index_from_one))+','+str(j+int(index_from_one))+','+str(ix_ker+int(index_from_one))+'}$'
param_names['mu'] = mu_names
param_names['kernels'] = ker_param_names
return param_names
# Kernel functionals
def make_kernel_functionals(self):
d = self.d
self.phi = [[None for j in range(d)] for i in range(d)]
self.diff_phi = [[None for j in range(d)] for i in range(d)]
self.psi = [[None for j in range(d)] for i in range(d)]
self.diff_psi = [[None for j in range(d)] for i in range(d)]
self.upsilon = [[[None for k in range(d)] for j in range(d)]
for i in range(d)]
self.diff_sim_upsilon = [[None for j in range(d)]
for i in range(d)]
self.diff_cross_upsilon = [[[None for k in range(d)]
for j in range(d)] for i in range(d)]
for i, j in itertools.product(range(d), range(d)):
kernel = self._kernel_matrix[i][j]
phi = kernel.make_phi()
self.phi[i][j] = phi
diff_phi = kernel.make_diff_phi()
self.diff_phi[i][j] = diff_phi
psi = kernel.make_psi()
self.psi[i][j] = psi
diff_psi = kernel.make_diff_psi()
self.diff_psi[i][j] = diff_psi
diff_sim_upsilon = kernel.make_diff_sim_upsilon()
self.diff_sim_upsilon[i][j] = diff_sim_upsilon
for i, j, k in itertools.product(range(d), range(d), range(d)):
kernel_ki = self._kernel_matrix[k][i]
kernel_kj = self._kernel_matrix[k][j]
if kernel_ki.is_compatible(kernel_kj):
func = kernel_ki.make_upsilon()
def upsilon(t, s, params_1, params_2):
return func(kernel_kj, t, s, params_1, params_2)
self.upsilon[i][j][k] = upsilon
diff_func = kernel_ki.make_diff_cross_upsilon()
def diff_cross_upsilon(t, s, ix_func, ix_diff, params_1,
params_2):
return diff_func(kernel_kj, t, s, ix_func, ix_diff,
params_1, params_2)
self.diff_cross_upsilon[i][j][k] = diff_cross_upsilon
else:
raise NotImplementedError("No available interaction"
" between kernel", k, ",", i,
" and kernel ", k, ",", j)
# Fit
def clear_fit(self):
"""
Delete all previously saved results and logs from the
corresponding attributes of the MHP object.
"""
self.is_fitted = False
self.fitted_mu = None
self.fitted_ker_param = None
self.fit_residuals = None
self.fitted_adjacency = None
self.fit_log = None
def fit(self, list_times, T_f, kappa=None, varpi=None, x_0=None,
n_iter=1000, solvers=None, estimators=None, logger=None, seed=1234,
verbose=False, clear=True, write=True, **kwargs):
"""
Fit the MHP model to some observations.
We suppose that we observe a path of a d-dimensional counting process
:math:`\\mathbf{N}` started at time :math:`0` up to some terminal time
:math:`T`.
The least squares error (LSE) of this model for these observations is
defined as
.. math::
\\mathcal{R}_{T}(\\boldsymbol{\\mu}):=\\frac{1}{T} \\sum_{k=1}^{d} \\int_{0}^{T} \\lambda_{k}(t)^{2} \\mathrm{~d} t-\\frac{2}{T} \\sum_{k=1}^{d} \\sum_{m=1}^{N_{T}^{k}} \\lambda_{k}\\left(t_{m}^{k}\\right).
For a homogeneous Poisson model, this simplifies to
.. math::
\\mathcal{R}_{T}(\\boldsymbol{\\mu}):=\\sum_{k=1}^{d} \\bigg( \\mu_{k}^{2} -2 \\frac{N_{T}^{k}}{T} \\bigg).
Parameters
----------
list_times : `list` of `numpy.ndarray`
List of jump times for each dimension.
T_f : `float`
Terminal time.
kappa : TYPE, optional
DESCRIPTION. The default is None.
varpi : TYPE, optional
DESCRIPTION. The default is None.
x_0 : `list` of `numpy.ndarray`, optional
x_0[k] is the initial guess for parameters of problem k. The
default is None.
n_iter : `list` or `int`, optional
n_iter[k] is the number of iterations of the the optimisation
algorithm for problem k. If n_iter is of type `int`, it will be
converted to a d-dimensional array where each entry is equal to
that integer. The default is 1000.
solvers : `list` of `aslsd.Solver`, optional
solvers[k] is the optimization solver for problem k. The default
is None.
estimators : `list` of `aslsd.Esimtator`, optional
estimators[k] is the gradient estimator for problem k. The default
is None.
logger : `aslsd.OptimLogger`, optional
DESCRIPTION. The default is None.
seed : `int`, optional
Seed for the random number generator. The default is 1234.
verbose : `bool`, optional
If True, print progression information. The default is False.
clear : `bool`, optional
If true, delete all previously saved results and logs from the
corresponding attributes of the MHP object. The default is True.
write : `bool`, optional
If true, save the estimation results and logs in the corresponding
attributes of the MHP object. The default is True.
**kwargs : `dict`
Additional keyword arguments.
Returns
-------
fitted_mu : `numpy.ndarray`
Fitted baselines.
fitted_ker_param : `numpy.ndarray`
Fitted kernel parameters.
"""
rng = np.random.default_rng(seed)
# Clear saved data in case already fitted
if clear:
self.clear_fit()
# Data
d = self.d
process_path = ProcessPath(list_times, T_f, kappa=kappa, varpi=varpi)
# Model
mu_bnds = [10**-10 for k in range(d)]
bnds = self.matrix2tensor_params(mu_bnds, self.param_bounds)
# Solver
if not isinstance(n_iter, (list, np.ndarray)):
n_iter = [n_iter for k in range(d)]
# Initialisation
if x_0 is None:
ref_mu = kwargs.get('ref_mu', None)
ref_ker_param = kwargs.get('ref_ker_param', None)
range_ref = kwargs.get('range_ref', 0.1)
target_bratio = kwargs.get('target_bratio', 0.6)
max_omega = kwargs.get('max_omega', 1.)
true_omega = kwargs.get('true_omega', None)
max_param = kwargs.get('max_param', 5.)
min_mu = kwargs.get('min_mu', 0.)
max_mu = kwargs.get('max_mu', None)
mu_0, ker_0 = self.get_random_param(ref_mu=ref_mu,
ref_ker_param=ref_ker_param,
range_ref=range_ref,
target_bratio=target_bratio,
max_omega=max_omega,
true_omega=true_omega,
max_param=max_param,
min_mu=min_mu, max_mu=max_mu,
flatten=False, rng=rng)
x_0 = self.matrix2tensor_params(mu_0, ker_0)
else:
mu_0, ker_0 = self.tensor2matrix_params(x_0)
# Initialize Estimators
if estimators is None:
estimators = [AdaptiveStratified(**kwargs) for k in range(d)]
else:
if issubclass(type(estimators), Estimator):
estimators = [copy.deepcopy(estimators) for k in range(d)]
for k in range(d):
estimators[k].k = k
estimators[k].n_iter = n_iter[k]
estimators[k].initialize(process_path, self)
estimators[k].intialize_logs()
estimators[k].set_stratification(**kwargs)
# Initialize Solvers
if solvers is None:
solvers = ADAM(**kwargs)
else:
if issubclass(type(solvers), Solver):
solvers = [copy.deepcopy(solvers) for k in range(d)]
# Initialize logger
logger = OptimLogger(d, n_iter, **kwargs)
# Scheme
x = [None]*d
for k in range(d):
x_k = x_0[k]
logger.log_param(k, 0, x_k)
bounds_k = bnds[k]
n_iter_k = n_iter[k]
for t in tqdm(range(n_iter_k), disable=not verbose):
# Compute LSE gradient estimate for parameters x_k
g_t = estimators[k].lse_k_grad_estimate(x_k, rng)
logger.log_grad(k, t, g_t)
# Apply solver iteration then project into space of parameters
x_k = solvers.iterate(t, x_k, g_t)
x_k = np.maximum(x_k, bounds_k)
logger.log_param(k, t+1, x_k)
esimator_k_log = estimators[k].get_log()
logger.estimator_logs[k] = esimator_k_log
x[k] = x_k
fitted_mu, fitted_ker_param = self.tensor2matrix_params(x)
if write:
self.is_fitted = True
self.fitted_mu = fitted_mu
self.fitted_ker_param = fitted_ker_param
logger.process_logs(self)
logger.mu_0 = mu_0
logger.ker_0 = ker_0
self.fit_log = logger
return fitted_mu, fitted_ker_param
def make_adjacency_matrix(self, kernel_param=None):
"""
Compute the adjacency matrix of the MHP.
The adjacency matrix :math:`A` of an MHP is the :math:`d\\times d`
matrix of :math:`L_{1}` norms of kernels; that is, for all
:math:`i,j \\in [d]` the corresponding entry of this matrix is given by
.. math::
A_{ij} := \\int_{[0,+\\infty]} |\\phi_{ij}(u)|du..
Parameters
----------
kernel_param : `numpy.ndarray`, optional
Matrix of kernel parameters at which to evaluate the adjacency
matrix. The default is None, in that case fitted kernel
parameters will be used if they are stored in the corresponding
attribute of the MHP object.
Raises
------
ValueError
Raise an error if the kernel parameters not specified and there
are no kernel parameters saved as an atrribute.
Returns
-------
adjacency : `numpy.ndarray`
Adjacency matrix of the MHP.
"""
log_fitted_adjacency = False
if kernel_param is None:
if self.is_fitted:
kernel_param = self.fitted_ker_param
log_fitted_adjacency = True
else:
raise ValueError("kernel_param must be specified.")
d = self.d
adjacency = [[self._kernel_matrix[i][j].l1_norm(kernel_param[i][j])
for j in range(d)] for i in range(d)]
if log_fitted_adjacency:
self.fitted_adjacency = adjacency
return adjacency
def get_branching_ratio(self, adjacency=None, kernel_param=None):
"""
Compute the branching ratio of the MHP.
The branching ratio of an MHP is equal to the spectral radius of
its adjacency matrix; that is, the maximum of the absolute values of
the eigenvalues of the adjacency matrix.
Parameters
----------
adjacency : `numpy.ndarray`, optional
Adjacency matrix of the MHP. The default is None, in that case it
will be computed.
kernel_param : `numpy.ndarray`, optional
Matrix of kernel parameters at which to evaluate the adjacency
matrix. The default is None, in that case fitted kernel
parameters will be used if they are stored in the corresponding
attribute of the MHP object.
Raises
------
ValueError
Raise an error if the adjacency matrix is not specified, the kernel
parameters not specified and there are no kernel parameters saved
as an atrribute.
Returns
-------
adjacency : `float`
Branching ratio of the MHP.
"""
if adjacency is None:
if kernel_param is None:
if self.is_fitted:
kernel_param = self.fitted_ker_param
else:
raise ValueError("kernel_param must be specified.")
adjacency = self.make_adjacency_matrix(kernel_param)
bratio = np.max(np.absolute(np.linalg.eigvals(adjacency)))
return bratio
def get_random_param(self, ref_mu=None, ref_ker_param=None, range_ref=0.1,
target_bratio=0.6, max_omega=1., true_omega=None,
max_param=5.,
min_mu=0., max_mu=None, flatten=False, seed=1234,
rng=None):
if rng is None:
rng = np.random.default_rng(seed)
d = self.d
# Mu
if ref_mu is None:
if not isinstance(min_mu, (list, np.ndarray)):
min_mu = np.ones(d)*min_mu
if max_mu is None:
max_mu = max(max(min_mu), 1.)
if not isinstance(max_mu, (list, np.ndarray)):
max_mu = np.ones(d)*max_mu
mu = np.zeros(d)
for i in range(d):
mu[i] = rng.uniform(low=min_mu[i], high=max_mu[i], size=1)[0]
else:
mu = np.zeros(d)
for i in range(d):
mu[i] = rng.uniform(low=max(0., (1.-range_ref)*ref_mu[i]),
high=(1+range_ref)*ref_mu[i], size=1)[0]
# Kernels
kernel_param = np.array([[None for j in range(d)]
for i in range(d)], dtype=object)
if ref_ker_param is None:
if not isinstance(max_param, (list, np.ndarray)):
float_max = max_param
max_param = [[[None for x
in range(self._kernel_matrix[i][j].n_param)]
for j in range(d)] for i in range(d)]
for i, j in itertools.product(range(d), range(d)):
n_param = self._kernel_matrix[i][j].n_param
vec_ix_omega = self._kernel_matrix[i][j].ix_omegas()
bnds = self.param_bounds[i][j]
for x in range(n_param):
if x in vec_ix_omega:
max_param[i][j][x] = max_omega
else:
max_param[i][j][x] = max(float_max, bnds[x])
for i, j in itertools.product(range(d), range(d)):
kernel_param[i][j] = []
n_param = self._kernel_matrix[i][j].n_param
vec_ix_omega = self._kernel_matrix[i][j].ix_omegas()
bnds = self.param_bounds[i][j]
for x in range(n_param):
val = rng.uniform(low=bnds[x], high=max_param[i][j][x],
size=1)[0]
kernel_param[i][j].append(val)
else:
for i, j in itertools.product(range(d), range(d)):
kernel_param[i][j] = []
n_param = self._kernel_matrix[i][j].n_param
bnds = self.param_bounds[i][j]
for x in range(n_param):
val = rng.uniform(low=max(bnds[x],
(1.-range_ref)
* ref_ker_param[i][j][x]),
high=(1.+range_ref)
* ref_ker_param[i][j][x],
size=1)[0]
kernel_param[i][j].append(val)
# Rescaling
branching_ratio = self.get_branching_ratio(kernel_param=kernel_param)
if branching_ratio > 0.:
scaling = target_bratio/branching_ratio
for i, j in itertools.product(range(d), range(d)):
kernel_param[i][j] = np.array(kernel_param[i][j])
if branching_ratio > 0.:
vec_ix_omega = self._kernel_matrix[i][j].ix_omegas()
kernel_param[i][j][vec_ix_omega] = (scaling*kernel_param[i][j][vec_ix_omega])
# Flatten
if flatten:
return self.matrix2tensor_params(mu, kernel_param)
else:
return mu, kernel_param
# Residuals
def get_residuals(self, process_path, mu=None, kernel_param=None,
sampling=False, sample_size=10**3, seed=1234, write=True,
verbose=False):
"""
Compute the residuals of the model.
We suppose that we observe a path of a d-dimensional counting process
:math:`\\mathbf{N}` started at time :math:`0` up to some terminal time
:math:`T`.
Let :math:`k \\in [d]`, define the compensator of :math:`N^k`
for all :math:`t \\geq 0` by
.. math::
\\Lambda_{k}(t):=\\int_{[0,t]}\\lambda_k(t)\\mathrm{~d} t.
For all :math:`m \\in \\mathbb{N}^{*}, k \\in [d]`, let
.. math::
s_{m}^{k}=\\Lambda_{k}\\left(t_{m}^{k}\\right).
For each :math:`k \\in[d]`, define the point process
.. math::
\\mathcal{S}^{k}:=\\left\\{s_{m}^{k}: m \\in \\mathbb{N}^{*}\\right\\};
then :math:`\\left(\mathcal{S}^{k}\\right)_{k \\in[d]}` are independent
standard Poisson processes. The inter-arrival times of
:math:`\\mathcal{S}^{k}` ('residuals'), for a model that fits the data
well must therefore be close to a standard exponential distribution.
Parameters
----------
process_path : `aslsd.ProcessPath`
DESCRIPTION.
mu : `numpy.ndarray`, optional
Vector of baseline parameters. The default is None, in that case
fitted baseline parameters will be used if they are stored in the
corresponding attribute of the MHP object.
kernel_param : `numpy.ndarray`, optional
Matrix of kernel parameters. The default is None, in that case
fitted kernel parameters will be used if they are stored in the
corresponding attribute of the MHP object.
sampling : `bool`, optional
If True, subsample the residuals. The default is False.
sample_size : `int`, optional
Size of the subsample of residuals. The default is 10**3. Only
used if sampling is True.
seed : `int`, optional
Seed of the random number generator. The default is 1234. Only
used if sampling is true.
write : `bool`, optional
If true, save computed residuals in the corresponding
attributes of the MHP object. The default is True.
verbose : `bool`, optional
If True, print progress bar. The default is False.
Raises
------
ValueError
Raise an error if the baseline is not specified and there is no
fitted baseline saved as an atrribute.
Returns
-------
residuals : `list` of `numpy.ndarray`
Residuals of the fitted model.
"""
if mu is None or kernel_param is None:
if self.is_fitted:
mu = self.fitted_mu
kernel_param = self.fitted_ker_param
else:
raise ValueError("Both mu and kernel_param must be specified.")
residuals = gof.get_residuals(process_path, self.psi, mu,
kernel_param, sampling=sampling,
sample_size=sample_size, seed=seed,
verbose=verbose)
if self.is_fitted and write:
self.fit_residuals = residuals
return residuals
def ks_test_residuals(self, residuals=None):
if residuals is None:
if self.fit_residuals is not None:
residuals = self.fit_residuals
else:
raise ValueError("residuals must be specified.")
return gof.ks_test_residuals(residuals)
def qq_plot(self, i, residuals=None, labels=None, style='exponential',
substract_yx=False, normalize=False, max_points=None,
display_line45=True, log_scale=False, ax=None, save=False,
filename='image.png', show=False, **kwargs):
if residuals is None:
if self.fit_residuals is not None:
residuals = self.fit_residuals
else:
raise ValueError("residuals must be specified.")
return gof.qq_plot(residuals[i], n_models=1, labels=labels,
style=style, substract_yx=substract_yx,
normalize=normalize, max_points=max_points,
display_line45=display_line45, log_scale=log_scale,
ax=ax, save=save, filename=filename, show=show,
**kwargs)
# Simulation
def simulate(self, T_f, mu=None, kernel_param=None, seed=1234,
verbose=False):
"""
Simulate a path of the MHP.
Parameters
----------
T_f : `float`
Terminal time.
mu : `numpy.ndarray`, optional
Vector of baseline parameters. The default is None, in that case
fitted baseline parameters will be used if they are stored in the
corresponding attribute of the MHP object.
kernel_param : `numpy.ndarray`, optional
Matrix of kernel parameters. The default is None, in that case
fitted kernel parameters will be used if they are stored in the
corresponding attribute of the MHP object.
seed : `int`, optional
Seed for the random number generator. The default is 1234.
verbose : `bool`, optional
If True, print progression information. The default is False.
Raises
------
ValueError
Raise an error if the baseline or the kernel parameters are not
specified and there is no fitted baseline or kernel parameters
saved as an atrribute.
Returns
-------
list_times : `list` of `numpy.ndarray`
List of simulated jump times for each dimension.
"""
if mu is None:
mu = self.fitted_mu
if mu is None:
raise ValueError("Missing value for Mu")
if kernel_param is None:
kernel_param = self.fitted_ker_param
if kernel_param is None:
raise ValueError("Missing value for Kernel parameters")
mu = np.array(mu)
d = self.d
offset_gens = [[None for j in range(d)] for i in range(d)]
for i, j in itertools.product(range(d), range(d)):
offset_gens[i][j] = self._kernel_matrix[i][j].make_offset_gen(
kernel_param[i][j])
adjacency = self.make_adjacency_matrix(kernel_param)
rng = np.random.default_rng(seed)
branching_ratio = self.get_branching_ratio(adjacency=adjacency)
if branching_ratio >= 1:
raise ValueError("Cannot simulate from unstable MHP: ",
"The branching ratio of this MHP is ",
branching_ratio, " > 1.")
if verbose:
print('Simulating events...')
# Step 1. Generate immigrants
# Number of immigrants
Nim = rng.poisson(mu*T_f)
# Location of immigrants
generations = [[rng.uniform(low=0.0, high=T_f, size=Nim[i])]
for i in range(d)]
def sum_generation(L, index):
return sum([len(L[i][index]) for i in range(d)])
ix_gen = 1
# Step 2. Fill via repeated generations
while sum_generation(generations, ix_gen-1):
for j in range(d):
if len(generations[j][ix_gen-1]) > 0:
for i in range(d):
# Set number of offspring
Noff = rng.poisson(adjacency[i][j],
size=len(generations[j][ix_gen-1]))
parenttimes = generations[j][ix_gen-1].repeat(Noff)
offsets = offset_gens[i][j](rng, N=Noff.sum())
offspringtime = parenttimes + offsets
generations[i] = generations[i]+[np.array([x for x in offspringtime if x < T_f])]
ix_gen += 1
list_times = [np.array(sorted([x for sublist in generations[i]
for x in sublist])) for i in range(d)]
if verbose:
n_tot = sum([len(L) for L in list_times])
print('Simulation Complete, ', n_tot, ' events simulated.')
return list_times
def simu_multipath(self, path_res, t_res, x_min, x_max, mu=None,
kernel_param=None, seed=1234, verbose=False,
disc_type='log', base_seed=1234):
d = self.d
rng = np.random.default_rng(base_seed)
vec_seeds = rng.choice(10**5, size=path_res, replace=False)
if disc_type == 'log':
T_f = 10**x_max
elif disc_type == 'linear':
T_f = x_max
list_Tf = uf.discretize_space(x_min, x_max, t_res, disc_type)
list_paths = [[[] for j in range(path_res)] for i in range(t_res)]
for j in range(path_res):
seed = vec_seeds[j]
list_times = self.simulate(T_f, mu=mu, kernel_param=kernel_param,
seed=seed, verbose=verbose)
for i in range(t_res):
local_Tf = list_Tf[i]
list_n_f = [bisect.bisect_left(list_times[index_dim],
local_Tf)-1
for index_dim in range(d)]
list_paths[i][j] = [list_times[0][:list_n_f[index_dim]+1]
for index_dim in range(d)]
return list_Tf, list_paths
# Metrics
# L2 projection
def get_l2_projection(self, mhp_2, param_2, n_iter=1000,
solver=None, log_error=False, rng=None,
seed=1234,
verbose=False, **kwargs):
d = self.d
if rng is None:
rng = np.random.default_rng(seed)
# Model
bnds = self.param_bounds
# Initialisation
ref_mu = kwargs.get('ref_mu', None)
ref_ker_param = kwargs.get('ref_ker_param', None)
range_ref = kwargs.get('range_ref', 0.1)
target_bratio = kwargs.get('target_bratio', 0.6)
max_omega = kwargs.get('max_omega', 1.)
true_omega = kwargs.get('true_omega', None)
max_param = kwargs.get('max_param', 5.)
min_mu = kwargs.get('min_mu', 0.)
max_mu = kwargs.get('max_mu', None)
mu_0, ker_0 = self.get_random_param(ref_mu=ref_mu,
ref_ker_param=ref_ker_param,
range_ref=range_ref,
target_bratio=target_bratio,
max_omega=max_omega,
true_omega=true_omega,
max_param=max_param,
min_mu=min_mu, max_mu=max_mu,
flatten=False, rng=rng)
param_1 = [[None for j in range(d)] for i in range(d)]
if solver is None:
solver = ADAM(**kwargs)
if log_error:
l2_err_log = [[np.zeros(n_iter) for j in range(d)]
for i in range(d)]
else:
l2_err_log = None
for i, j in itertools.product(range(d), range(d)):
kernel = self._kernel_matrix[i][j]
kernel_2 = mhp_2._kernel_matrix[i][j]
ker_param_2 = param_2[i][j]
res_ij = kernel.get_l2_projection(kernel_2, ker_param_2,
n_iter=n_iter,
params_0=ker_0[i][j],
solver=solver,
log_error=log_error,
rng=ker_0[i][j],
verbose=verbose, **kwargs)
param_1[i][j] = copy.deepcopy(res_ij['params'])
if log_error:
l2_err_log[i][j] = copy.deepcopy(res_ij['log'])
res = {'params': param_1, 'log': l2_err_log}
return res
# Plots
def plot_kernels(self, kernel_param=None, t_min=0., t_max=10.,
n_samples=1000, index_from_one=False, log_scale=False,
axs=None, save=False, filename='image.png',
show=False, **kwargs):
if kernel_param is None:
if self.is_fitted:
kernel_param = self.fitted_ker_param
else:
raise ValueError("kernel_param must be specified.")
return gt.plot_kernels(self.phi, kernel_param, t_min=t_min,
t_max=t_max, n_samples=n_samples,
index_from_one=index_from_one,
log_scale=log_scale, axs=axs,
save=save, filename=filename, show=show,
**kwargs)
def plot_adjacency_matrix(self, adjacency=None, kernel_param=None,
event_names=None,
index_from_one=False, annotate=False,
cmap="Blues", save=False,
filename='image.png', show=True, **kwargs):
if adjacency is None:
if self.is_fitted:
if self.fitted_adjacency is None:
if kernel_param is None:
kernel_param = self.fitted_ker_param
adjacency = self.make_adjacency_matrix()
self.fitted_adjacency = adjacency
else:
adjacency = self.fitted_adjacency
else:
if kernel_param is not None:
adjacency = self.make_adjacency_matrix(kernel_param)
else:
raise ValueError("adjacency must be specified.")
return gt.plot_adjacency_matrix(adjacency, event_names=event_names,
index_from_one=index_from_one,
annotate=annotate, cmap=cmap,
save=save, filename=filename,
show=show, **kwargs)
def plot_solver_path(self, true_mu=None, true_ker_param=None, min_mu=None,
min_ker_param=None, plot_derivatives=False,
derivatives_zero=False, axs=None, save=False,
filename='image.png', show=False, **kwargs):
if not self.is_fitted:
raise ValueError("MHP must be fitted before plotting solver path")
fit_log = self.fit_log
matrix_n_param = self.matrix_n_param
mu_names = self.mu_names
ker_param_names = self.ker_param_names
return gt.plot_solver_path(fit_log, matrix_n_param, mu_names,
ker_param_names, true_mu=true_mu,
true_ker_param=true_ker_param,
min_mu=min_mu, min_ker_param=min_ker_param,
plot_derivatives=plot_derivatives,
derivatives_zero=derivatives_zero,
axs=axs, save=save, filename=filename,
show=show, **kwargs)
# Serialization
def save(self, file, **kwargs):
if file.endswith('.pickle'):
file_mu = file+'_fitted_mu.pickle'
else:
file_mu = file+'_fitted_mu'
pickle_out = open(file_mu, "wb", **kwargs)
pickle.dump(self.fitted_mu, pickle_out)
pickle_out.close()
if file.endswith('.pickle'):
file_ker = file+'_fitted_ker.pickle'
else:
file_ker = file+'_fitted_ker'
pickle_out = open(file_ker, "wb", **kwargs)
pickle.dump(self.fitted_ker_param, pickle_out)
pickle_out.close()
if file.endswith('.pickle'):
file_residuals = file+'_fitted_residuals.pickle'
else:
file_residuals = file+'_fitted_residuals'
file_residuals = file+'_fitted_residuals'
pickle_out = open(file_residuals, "wb", **kwargs)
pickle.dump(self.fit_residuals, pickle_out)
pickle_out.close()
if file.endswith('.pickle'):
file_adjacency = file+'_fitted_adj.pickle'
else:
file_adjacency = file+'_fitted_adj'
file_adjacency = file+'_fitted_adj'
pickle_out = open(file_adjacency, "wb", **kwargs)
pickle.dump(self.fitted_adjacency, pickle_out)
pickle_out.close()
def load(self, file, **kwargs):
if file.endswith('.pickle'):
file_mu = file+'_fitted_mu.pickle'
else:
file_mu = file+'_fitted_mu'
pickle_in = open(file_mu, "rb")
fitted_mu = pickle.load(pickle_in)
if file.endswith('.pickle'):
file_ker = file+'_fitted_ker.pickle'
else:
file_ker = file+'_fitted_ker'
file_ker = file+'_fitted_ker'
pickle_in = open(file_ker, "rb")
fitted_ker = pickle.load(pickle_in)
if file.endswith('.pickle'):
file_residuals = file+'_fitted_residuals.pickle'
else:
file_residuals = file+'_fitted_residuals'
pickle_in = open(file_residuals, "rb")
fitted_residuals = pickle.load(pickle_in)
if file.endswith('.pickle'):
file_adjacency = file+'_fitted_adj.pickle'
else:
file_adjacency = file+'_fitted_adj'
pickle_in = open(file_adjacency, "rb")
fitted_adjacency = pickle.load(pickle_in)
self.clear_fit()
self.is_fitted = True
self.fitted_mu = fitted_mu
self.fitted_ker_param = fitted_ker
self.fit_residuals = fitted_residuals
self.fitted_adjacency = fitted_adjacency
| 41.680478
| 235
| 0.529966
|
81767e2b6ccaa42b3e2bda249db0d2191273c72c
| 7,012
|
py
|
Python
|
code-class-team/Team.py
|
kirmar/delaysay
|
9cba01d9840ddb1ba35430cc709608256134b798
|
[
"Apache-2.0"
] | null | null | null |
code-class-team/Team.py
|
kirmar/delaysay
|
9cba01d9840ddb1ba35430cc709608256134b798
|
[
"Apache-2.0"
] | 2
|
2022-01-19T11:20:06.000Z
|
2022-01-19T11:34:32.000Z
|
code-class-team/Team.py
|
kirmar/delaysay
|
9cba01d9840ddb1ba35430cc709608256134b798
|
[
"Apache-2.0"
] | null | null | null |
import boto3
import time
import os
from StripeSubscription import StripeSubscription
from datetime import datetime, timedelta
# This is the format used to log dates in the DynamoDB table.
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
class Team:
def __init__(self, id):
assert id and isinstance(id, str)
dynamodb = boto3.resource("dynamodb")
self.table = dynamodb.Table(os.environ['AUTH_TABLE_NAME'])
self.id = id
self.last_updated = 0
self._refresh()
def _get_payment_expiration_as_string(self):
if self.never_expires():
payment_expiration_as_string = self.payment_expiration
elif isinstance(self.payment_expiration, datetime):
payment_expiration_as_string = (
self.payment_expiration.strftime(DATETIME_FORMAT))
else:
# This shouldn't ever happen, but if it does, I at least
# want to know what happened.
payment_expiration_as_string = str(self.payment_expiration)
return payment_expiration_as_string
def _load_subscriptions(self):
subscriptions = []
for id in self.subscription_ids:
subscription = StripeSubscription(id)
subscriptions.append(subscription)
return subscriptions
def _update_payment_info_in_dynamodb(self):
payment_expiration_as_string = self._get_payment_expiration_as_string()
self.table.update_item(
Key={
'PK': "TEAM#" + self.id,
'SK': "team"
},
UpdateExpression=
"SET payment_expiration = :val,"
" payment_plan = :val2",
ExpressionAttributeValues={
":val": payment_expiration_as_string,
":val2": self.payment_plan
}
)
def _update_payment_info(self, require_current_subscription=True):
# Note as of 2020-05-02: The "best_subscription" is the one that
# expires latest or, if all others are expired/canceled, the only
# active subscription.
if self.never_expires():
return
subscriptions = self._load_subscriptions()
if subscriptions:
best_subscription = max(subscriptions)
else:
# The team is probably in the middle of a trial.
return
if not best_subscription.is_current() and require_current_subscription:
return
self.payment_expiration = best_subscription.get_expiration()
self.payment_plan = best_subscription.get_plan_nickname()
self.best_subscription = best_subscription
if self.best_subscription.is_current():
self._update_payment_info_in_dynamodb()
def _refresh(self, force=False, alert_if_not_in_dynamodb=False):
# Careful with this function!! Some of the functions
# that call it are called (directly or indirectly)
# by it, like get_time_payment_has_been_overdue()
# and also never_expires().
if not force and time.time() - self.last_updated < 2:
return
self.last_updated = time.time()
response = self.table.get_item(
Key={
'PK': "TEAM#" + self.id,
'SK': "team"
}
)
if 'Item' not in response:
self.is_in_dynamodb = False
if alert_if_not_in_dynamodb:
# 2020-05-04: For some reason, this wasn't called.
# Is 'Item' in response even when the item doesn't
# exist in the DynamoDB table?
raise TeamNotInDynamoDBError("Unauthorized team: " + self.id)
else:
return
self.is_in_dynamodb = True
date = response['Item']['payment_expiration']
try:
self.payment_expiration = datetime.strptime(date, DATETIME_FORMAT)
except:
# The expiration is probably "never".
self.payment_expiration = date
self.payment_plan = response['Item']['payment_plan']
self.subscription_ids = response['Item'].get(
'stripe_subscriptions', [])
if self.get_time_payment_has_been_overdue() > timedelta(0):
self._update_payment_info()
def is_trialing(self):
self._refresh(alert_if_not_in_dynamodb=True)
return self.payment_plan == "trial"
def never_expires(self):
self._refresh(alert_if_not_in_dynamodb=True)
if not isinstance(self.payment_expiration, datetime):
# The expiration is probably "never".
return True
return False
def get_time_till_payment_is_due(self):
self._refresh(alert_if_not_in_dynamodb=True)
if self.never_expires():
return timedelta(weeks=52*100)
now = datetime.utcnow()
return self.payment_expiration - now
def get_time_payment_has_been_overdue(self):
self._refresh(alert_if_not_in_dynamodb=True)
if self.never_expires():
return timedelta(0)
now = datetime.utcnow()
return now - self.payment_expiration
def add_to_dynamodb(self, team_name, enterprise_id, create_time,
trial_expiration):
self._refresh()
if self.is_in_dynamodb:
return
item = {
'PK': "TEAM#" + self.id,
'SK': "team",
'team_name': team_name,
'team_id': self.id,
'enterprise_id': enterprise_id,
'create_time': create_time.strftime(DATETIME_FORMAT),
'payment_expiration': trial_expiration.strftime(DATETIME_FORMAT),
'payment_plan': "trial",
'stripe_subscriptions': []
}
for key in list(item):
if key == 'stripe_subscriptions':
continue
if not item[key]:
del item[key]
self.table.put_item(Item=item)
self._refresh(force=True)
def add_subscription(self, subscription_id):
# Note as of 2020-05-02: There should only be one subscription
# for each team, but in the case that there are multiple,
# I want DynamoDB to keep track for debugging/support purposes.
self._refresh(alert_if_not_in_dynamodb=True)
self.subscription_ids.append(subscription_id)
self._update_payment_info()
self.table.update_item(
Key={
'PK': "TEAM#" + self.id,
'SK': "team"
},
UpdateExpression=
"SET stripe_subscriptions"
" = list_append(stripe_subscriptions, :val)",
ExpressionAttributeValues={
":val": [subscription_id]
}
)
def get_best_subscription(self):
self._refresh(alert_if_not_in_dynamodb=True)
self._update_payment_info(require_current_subscription=False)
return self.best_subscription
| 38.108696
| 79
| 0.604963
|
7a173ce1916ded6e23ac55792cc4f03b17531560
| 5,380
|
py
|
Python
|
x7/view/modes/common.py
|
gribbg/x7-view
|
53a07b651a08eae63f019b388584cfffceeb2ccb
|
[
"BSD-2-Clause",
"MIT"
] | null | null | null |
x7/view/modes/common.py
|
gribbg/x7-view
|
53a07b651a08eae63f019b388584cfffceeb2ccb
|
[
"BSD-2-Clause",
"MIT"
] | null | null | null |
x7/view/modes/common.py
|
gribbg/x7-view
|
53a07b651a08eae63f019b388584cfffceeb2ccb
|
[
"BSD-2-Clause",
"MIT"
] | null | null | null |
import tkinter as tk
from abc import ABC
from x7.geom.typing import *
from x7.geom.geom import Point
import x7.view.event
from ..digi import DigitizeController
from ..digibase import Mode
from ..shapes import DigitizeShape
__all__ = ['tag_area', 'canvas_find', 'canvas_find_multiple', 'ViewEvent', 'ModeCommon']
def tag_area(canvas, tag):
"""Compute the bbox area of a single item on the canvas"""
# TODO-different areas based on type of shape
xl, yl, xh, yh = canvas.bbox(tag)
return (xh-xl) * (yh-yl)
def canvas_find_multiple(view, cx, cy) -> List[Tuple]:
"""Find multiple objects near cursor, return sorted list of (area, tk_id)"""
debug = False
if debug:
shown = set()
for rad in [0, 1, 2, 4, 8]:
found = view.canvas.find_overlapping(cx - rad, cy - rad, cx + rad, cy + rad)
print('rad: %d found: %s' % (rad, found))
for f in found:
if f not in shown:
shown.add(f)
print(' %d: %s %s %s' % (f, tag_area(view.canvas, f), view.canvas.bbox(f), view.ui_map.obj(f)))
for rad in range(8):
found = view.canvas.find_overlapping(cx - rad, cy - rad, cx + rad, cy + rad)
found = sorted((tag_area(view.canvas, tag), tag) for tag in found if view.ui_map.obj(tag))
if found:
if debug:
print('-->', found)
return found
return []
def canvas_find(view, cx, cy) -> Tuple[Optional[object], Optional[str]]:
"""Find object near cursor, return object & tag"""
found = canvas_find_multiple(view, cx, cy)
if found:
obj, tag = view.ui_map.obj(found[0][1])
if obj not in view.shapes:
if isinstance(obj, DigitizeShape):
print('Internal error: shape on canvas, but not in view.shapes: %s' % obj)
return obj, tag
else:
return None, None
class ViewEvent(tk.Event):
"""tk.Event, with typing and some x7-view specific values"""
serial: int
num: Union[int, str] # str:?? implies not set
focus: bool
type_test: Union[int, str]
height: Union[int, str]
width: Union[int, str]
keycode: str
state: Union[int, str]
time: Union[int, str]
x: Union[int, str]
y: Union[int, str]
x_root: Union[int, str]
y_root: Union[int, str]
char: str
send_event: bool
keysym: str
keysym_num: str
type: tk.EventType
widget: tk.Misc
delta: int
cx: float # ev.x converted to canvas space
cy: float # ev.y converted to canvas space
mp: Point # (cx, cy) converted to modeling space
item: Union[DigitizeShape, Any] # Really anything that has mouse_button callbacks
tag: str # .tag from .item graphical element
shift: bool # Shift key pressed
control: bool # Control key pressed
def __init__(self, ev: tk.Event, cx=0.0, cy=0.0, mp=Point(0, 0), item=None, tag=''):
self.__dict__.update(ev.__dict__)
self.cx = cx
self.cy = cy
self.mp = mp
self.item = item
self.tag = tag
if isinstance(self.state, int):
self.shift = True if self.state & x7.view.event.SHIFT else False
self.control = True if self.state & x7.view.event.CONTROL else False
else:
# Visibility events have strings for .state, not modifier keys
self.shift = self.control = False
def __str__(self):
return super().__str__() + ' @ (%d, %d) -> %s' % (self.cx, self.cy, self.mp.round(2))
class ModeCommon(Mode, ABC):
"""A few more common behaviors for Modes"""
def __init__(self, controller: DigitizeController):
self.controller = controller
self.active_item: Union[DigitizeShape, Any] = None # Really anything that has mouse_button callbacks
self.active_tag: Optional[str] = None
self.verbose = False
def event_enrich(self, name, tk_event, verb=None, find=False) -> ViewEvent:
"""
Enrich an event by adding .cx, .cy, .mx, .my
Find matching item & tag if not self.active_item
Add .tag
"""
canvas = self.controller.view.canvas
assert tk_event.widget == canvas
cx, cy = canvas.canvasx(tk_event.x), canvas.canvasy(tk_event.y)
mp = Point(*self.controller.view.draw.matrix.untransform(cx, cy))
event = ViewEvent(tk_event, cx, cy, mp)
if self.verbose:
print('%s(%s) -> (%d, %d) -> %s .state=%s' % (name, tk_event, event.cx, event.cy, event.mp, event.state))
print('%s: %s' % (name, event))
if verb:
print(' active %s %s.%s' % (verb, self.active_item.__class__.__name__, self.active_tag))
if find or not self.active_item:
item, tag = canvas_find(self.controller.view, event.cx, event.cy)
event.item = item
event.tag = tag
if not self.active_item:
self.active_item = item
self.active_tag = tag
if self.verbose and item:
print('--> ', tag, '@', item)
else:
event.item = self.active_item
event.tag = self.active_tag
return event
| 36.849315
| 118
| 0.573234
|
f517b2dc51d59bba847f503456bab0d95ea35198
| 19,842
|
py
|
Python
|
nailgun/nailgun/test/integration/test_network_configuration.py
|
prmtl/fuel-web
|
3577169e209596a8e4a95d1c41d2dde099a3945f
|
[
"Apache-2.0"
] | null | null | null |
nailgun/nailgun/test/integration/test_network_configuration.py
|
prmtl/fuel-web
|
3577169e209596a8e4a95d1c41d2dde099a3945f
|
[
"Apache-2.0"
] | null | null | null |
nailgun/nailgun/test/integration/test_network_configuration.py
|
prmtl/fuel-web
|
3577169e209596a8e4a95d1c41d2dde099a3945f
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from mock import patch
from oslo.serialization import jsonutils
from sqlalchemy.sql import not_
from nailgun import consts
from nailgun.db.sqlalchemy.models import Cluster
from nailgun.db.sqlalchemy.models import NetworkGroup
from nailgun.network.manager import NetworkManager
from nailgun.test.base import BaseIntegrationTest
from nailgun.utils import reverse
class TestNovaNetworkConfigurationHandlerMultinode(BaseIntegrationTest):
def setUp(self):
super(TestNovaNetworkConfigurationHandlerMultinode, self).setUp()
cluster = self.env.create_cluster(api=True)
self.cluster = self.db.query(Cluster).get(cluster['id'])
def test_get_request_should_return_net_manager_and_networks(self):
resp = self.env.nova_networks_get(self.cluster.id)
data = resp.json_body
cluster = self.db.query(Cluster).get(self.cluster.id)
self.assertEqual(data['networking_parameters']['net_manager'],
self.cluster.network_config.net_manager)
for network_group in cluster.network_groups:
network = [i for i in data['networks']
if i['id'] == network_group.id][0]
keys = [
'name',
'group_id',
'vlan_start',
'cidr',
'id']
for key in keys:
self.assertEqual(network[key], getattr(network_group, key))
def test_not_found_cluster(self):
resp = self.env.nova_networks_get(self.cluster.id + 999,
expect_errors=True)
self.assertEqual(404, resp.status_code)
def test_change_net_manager(self):
self.assertEqual(self.cluster.network_config.net_manager,
'FlatDHCPManager')
new_net_manager = {
'networking_parameters': {'net_manager': 'VlanManager'}
}
self.env.nova_networks_put(self.cluster.id, new_net_manager)
self.db.refresh(self.cluster)
self.assertEqual(
self.cluster.network_config.net_manager,
new_net_manager['networking_parameters']['net_manager'])
def test_change_dns_nameservers(self):
new_dns_nameservers = {
'networking_parameters': {
'dns_nameservers': [
"208.67.222.222",
"208.67.220.220"
]
}
}
self.env.nova_networks_put(self.cluster.id, new_dns_nameservers)
self.db.refresh(self.cluster)
self.assertEqual(
self.cluster.network_config.dns_nameservers,
new_dns_nameservers['networking_parameters']['dns_nameservers']
)
def test_refresh_mask_on_cidr_change(self):
resp = self.env.nova_networks_get(self.cluster.id)
data = resp.json_body
mgmt = [n for n in data['networks']
if n['name'] == 'management'][0]
cidr = mgmt['cidr'].partition('/')[0] + '/25'
mgmt['cidr'] = cidr
resp = self.env.nova_networks_put(self.cluster.id, data)
self.assertEqual(resp.status_code, 200)
task = resp.json_body
self.assertEqual(task['status'], consts.TASK_STATUSES.ready)
self.db.refresh(self.cluster)
mgmt_ng = [ng for ng in self.cluster.network_groups
if ng.name == 'management'][0]
self.assertEqual(mgmt_ng.cidr, cidr)
def test_wrong_net_provider(self):
resp = self.app.put(
reverse(
'NeutronNetworkConfigurationHandler',
kwargs={'cluster_id': self.cluster.id}),
jsonutils.dumps({}),
headers=self.default_headers,
expect_errors=True
)
self.assertEqual(resp.status_code, 400)
self.assertEqual(
resp.json_body["message"],
u"Wrong net provider - environment uses 'nova_network'"
)
def test_do_not_update_net_manager_if_validation_is_failed(self):
new_net_manager = {
'networking_parameters': {'net_manager': 'VlanManager'},
'networks': [{'id': 500, 'vlan_start': 500}]
}
self.env.nova_networks_put(self.cluster.id, new_net_manager,
expect_errors=True)
self.db.refresh(self.cluster)
self.assertNotEqual(
self.cluster.network_config.net_manager,
new_net_manager['networking_parameters']['net_manager'])
def test_network_group_update_changes_network(self):
network = self.db.query(NetworkGroup).filter(
not_(NetworkGroup.name == consts.NETWORKS.fuelweb_admin)
).first()
self.assertIsNotNone(network)
new_vlan_id = 500 # non-used vlan id
new_nets = {'networks': [{'id': network.id,
'vlan_start': new_vlan_id}]}
resp = self.env.nova_networks_put(self.cluster.id, new_nets)
self.assertEqual(resp.status_code, 200)
self.db.refresh(network)
self.assertEqual(network.vlan_start, 500)
def test_update_networks_and_net_manager(self):
network = self.db.query(NetworkGroup).filter(
not_(NetworkGroup.name == consts.NETWORKS.fuelweb_admin)
).first()
new_vlan_id = 500 # non-used vlan id
new_net = {'networking_parameters': {'net_manager': 'VlanManager'},
'networks': [{'id': network.id, 'vlan_start': new_vlan_id}]}
self.env.nova_networks_put(self.cluster.id, new_net)
self.db.refresh(self.cluster)
self.db.refresh(network)
self.assertEqual(
self.cluster.network_config.net_manager,
new_net['networking_parameters']['net_manager'])
self.assertEqual(network.vlan_start, new_vlan_id)
def test_networks_update_fails_with_wrong_net_id(self):
new_nets = {'networks': [{'id': 500,
'vlan_start': 500}]}
resp = self.env.nova_networks_put(self.cluster.id, new_nets,
expect_errors=True)
self.assertEqual(200, resp.status_code)
task = resp.json_body
self.assertEqual(task['status'], consts.TASK_STATUSES.error)
self.assertEqual(
task['message'],
'Invalid network ID: 500'
)
def test_admin_public_floating_untagged_others_tagged(self):
resp = self.env.nova_networks_get(self.cluster.id)
data = resp.json_body
for net in data['networks']:
if net['name'] in (consts.NETWORKS.fuelweb_admin,
consts.NETWORKS.public,
consts.NETWORKS.fixed):
self.assertIsNone(net['vlan_start'])
else:
self.assertIsNotNone(net['vlan_start'])
def test_mgmt_storage_networks_have_no_gateway(self):
resp = self.env.nova_networks_get(self.cluster.id)
self.assertEqual(200, resp.status_code)
data = resp.json_body
for net in data['networks']:
if net['name'] in ['management', 'storage']:
self.assertIsNone(net['gateway'])
def test_management_network_has_gw(self):
net_meta = self.env.get_default_networks_metadata().copy()
mgmt = filter(lambda n: n['name'] == 'management',
net_meta['nova_network']['networks'])[0]
mgmt['use_gateway'] = True
mgmt['gateway'] = '192.168.0.1'
cluster = self.env.create(
cluster_kwargs={},
release_kwargs={'networks_metadata': net_meta, 'api': False},
nodes_kwargs=[{"pending_addition": True}]
)
resp = self.env.nova_networks_get(cluster['id'])
data = resp.json_body
mgmt = filter(lambda n: n['name'] == 'management',
data['networks'])[0]
self.assertEqual(mgmt['gateway'], '192.168.0.1')
strg = filter(lambda n: n['name'] == 'storage',
data['networks'])[0]
self.assertIsNone(strg['gateway'])
def test_management_network_gw_set_but_not_in_use(self):
net_meta = self.env.get_default_networks_metadata().copy()
mgmt = filter(lambda n: n['name'] == 'management',
net_meta['nova_network']['networks'])[0]
mgmt['gateway'] = '192.168.0.1'
self.assertEqual(mgmt['use_gateway'], False)
cluster = self.env.create(
cluster_kwargs={},
release_kwargs={'networks_metadata': net_meta, 'api': False},
nodes_kwargs=[{"pending_addition": True}]
)
resp = self.env.nova_networks_get(cluster['id'])
data = resp.json_body
for n in data['networks']:
if n['name'] in ('management', 'storage'):
self.assertIsNone(n['gateway'])
class TestNeutronNetworkConfigurationHandlerMultinode(BaseIntegrationTest):
def setUp(self):
super(TestNeutronNetworkConfigurationHandlerMultinode, self).setUp()
cluster = self.env.create_cluster(api=True,
net_provider='neutron',
net_segment_type='gre',
mode='ha_compact'
)
self.cluster = self.db.query(Cluster).get(cluster['id'])
def test_get_request_should_return_net_provider_segment_and_networks(self):
resp = self.env.neutron_networks_get(self.cluster.id)
data = resp.json_body
cluster = self.db.query(Cluster).get(self.cluster.id)
self.assertEqual(data['networking_parameters']['segmentation_type'],
self.cluster.network_config.segmentation_type)
for network_group in cluster.network_groups:
network = [i for i in data['networks']
if i['id'] == network_group.id][0]
keys = [
'name',
'group_id',
'vlan_start',
'cidr',
'id']
for key in keys:
self.assertEqual(network[key], getattr(network_group, key))
def test_get_request_should_return_vips(self):
resp = self.env.neutron_networks_get(self.cluster.id)
data = resp.json_body
self.assertIn('public_vip', data)
self.assertIn('management_vip', data)
def test_not_found_cluster(self):
resp = self.env.neutron_networks_get(self.cluster.id + 999,
expect_errors=True)
self.assertEqual(404, resp.status_code)
def test_refresh_mask_on_cidr_change(self):
resp = self.env.neutron_networks_get(self.cluster.id)
data = resp.json_body
mgmt = [n for n in data['networks']
if n['name'] == 'management'][0]
cidr = mgmt['cidr'].partition('/')[0] + '/25'
mgmt['cidr'] = cidr
resp = self.env.neutron_networks_put(self.cluster.id, data)
self.assertEqual(200, resp.status_code)
task = resp.json_body
self.assertEqual(task['status'], consts.TASK_STATUSES.ready)
self.db.refresh(self.cluster)
mgmt_ng = [ng for ng in self.cluster.network_groups
if ng.name == 'management'][0]
self.assertEqual(mgmt_ng.cidr, cidr)
def test_do_not_update_net_segmentation_type(self):
resp = self.env.neutron_networks_get(self.cluster.id)
data = resp.json_body
data['networking_parameters']['segmentation_type'] = 'vlan'
resp = self.env.neutron_networks_put(self.cluster.id, data,
expect_errors=True)
self.assertEqual(200, resp.status_code)
task = resp.json_body
self.assertEqual(task['status'], consts.TASK_STATUSES.error)
self.assertEqual(
task['message'],
"Change of 'segmentation_type' is prohibited"
)
def test_network_group_update_changes_network(self):
resp = self.env.neutron_networks_get(self.cluster.id)
data = resp.json_body
network = self.db.query(NetworkGroup).get(data['networks'][0]['id'])
self.assertIsNotNone(network)
data['networks'][0]['vlan_start'] = 500 # non-used vlan id
resp = self.env.neutron_networks_put(self.cluster.id, data)
self.assertEqual(resp.status_code, 200)
self.db.refresh(network)
self.assertEqual(network.vlan_start, 500)
def test_update_networks_fails_if_change_net_segmentation_type(self):
resp = self.env.neutron_networks_get(self.cluster.id)
data = resp.json_body
network = self.db.query(NetworkGroup).get(data['networks'][0]['id'])
self.assertIsNotNone(network)
data['networks'][0]['vlan_start'] = 500 # non-used vlan id
data['networking_parameters']['segmentation_type'] = 'vlan'
resp = self.env.neutron_networks_put(self.cluster.id, data,
expect_errors=True)
self.assertEqual(200, resp.status_code)
task = resp.json_body
self.assertEqual(task['status'], consts.TASK_STATUSES.error)
self.assertEqual(
task['message'],
"Change of 'segmentation_type' is prohibited"
)
def test_networks_update_fails_with_wrong_net_id(self):
new_nets = {'networks': [{'id': 500,
'name': 'new',
'vlan_start': 500}]}
resp = self.env.neutron_networks_put(self.cluster.id, new_nets,
expect_errors=True)
self.assertEqual(200, resp.status_code)
task = resp.json_body
self.assertEqual(task['status'], consts.TASK_STATUSES.error)
self.assertEqual(
task['message'],
'Invalid network ID: 500'
)
def test_refresh_public_cidr_on_its_change(self):
data = self.env.neutron_networks_get(self.cluster.id).json_body
publ = filter(lambda ng: ng['name'] == 'public', data['networks'])[0]
self.assertEqual(publ['cidr'], '172.16.0.0/24')
publ['cidr'] = '199.61.0.0/24'
publ['gateway'] = '199.61.0.1'
publ['ip_ranges'] = [['199.61.0.11', '199.61.0.33'],
['199.61.0.55', '199.61.0.99']]
data['networking_parameters']['floating_ranges'] = \
[['199.61.0.111', '199.61.0.122']]
resp = self.env.neutron_networks_put(self.cluster.id, data)
self.assertEqual(200, resp.status_code)
task = resp.json_body
self.assertEqual(task['status'], consts.TASK_STATUSES.ready)
self.db.refresh(self.cluster)
publ_ng = filter(lambda ng: ng.name == 'public',
self.cluster.network_groups)[0]
self.assertEqual(publ_ng.cidr, '199.61.0.0/24')
def test_admin_public_untagged_others_tagged(self):
resp = self.env.neutron_networks_get(self.cluster.id)
data = resp.json_body
for net in data['networks']:
if net['name'] in ('fuelweb_admin', 'public',):
self.assertIsNone(net['vlan_start'])
else:
self.assertIsNotNone(net['vlan_start'])
def test_mgmt_storage_networks_have_no_gateway(self):
resp = self.env.neutron_networks_get(self.cluster.id)
self.assertEqual(200, resp.status_code)
data = resp.json_body
for net in data['networks']:
if net['name'] in ['management', 'storage']:
self.assertIsNone(net['gateway'])
def test_management_network_has_gw(self):
net_meta = self.env.get_default_networks_metadata().copy()
mgmt = filter(lambda n: n['name'] == 'management',
net_meta['neutron']['networks'])[0]
mgmt['use_gateway'] = True
cluster = self.env.create(
cluster_kwargs={'net_provider': 'neutron',
'net_segment_type': 'gre'},
release_kwargs={'networks_metadata': net_meta, 'api': False},
nodes_kwargs=[{"pending_addition": True}]
)
resp = self.env.neutron_networks_get(cluster['id'])
data = resp.json_body
mgmt = filter(lambda n: n['name'] == 'management',
data['networks'])[0]
self.assertEqual(mgmt['gateway'], '192.168.0.1')
strg = filter(lambda n: n['name'] == 'storage',
data['networks'])[0]
self.assertIsNone(strg['gateway'])
class TestNovaNetworkConfigurationHandlerHA(BaseIntegrationTest):
def setUp(self):
super(TestNovaNetworkConfigurationHandlerHA, self).setUp()
cluster = self.env.create_cluster(api=True, mode='ha_compact')
self.cluster = self.db.query(Cluster).get(cluster['id'])
self.net_manager = NetworkManager
def test_returns_management_vip_and_public_vip(self):
resp = self.env.nova_networks_get(self.cluster.id).json_body
self.assertEqual(
resp['management_vip'],
self.net_manager.assign_vip(self.cluster, 'management'))
self.assertEqual(
resp['public_vip'],
self.net_manager.assign_vip(self.cluster, 'public'))
class TestAdminNetworkConfiguration(BaseIntegrationTest):
@patch.dict('nailgun.db.sqlalchemy.fixman.settings.ADMIN_NETWORK', {
"cidr": "192.168.0.0/24",
"size": "256",
"first": "192.168.0.129",
"last": "192.168.0.254"
})
def setUp(self):
super(TestAdminNetworkConfiguration, self).setUp()
self.cluster = self.env.create(
cluster_kwargs={
"api": True
},
nodes_kwargs=[
{"pending_addition": True, "api": True}
]
)
def test_netconfig_error_when_admin_cidr_match_other_network_cidr(self):
resp = self.env.nova_networks_get(self.cluster['id'])
nets = resp.json_body
resp = self.env.nova_networks_put(self.cluster['id'], nets,
expect_errors=True)
self.assertEqual(resp.status_code, 200)
task = resp.json_body
self.assertEqual(task['status'], consts.TASK_STATUSES.error)
self.assertEqual(task['progress'], 100)
self.assertEqual(task['name'], 'check_networks')
self.assertIn("Address space intersection between networks:\n"
"admin (PXE), management.",
task['message'])
def test_deploy_error_when_admin_cidr_match_other_network_cidr(self):
resp = self.env.cluster_changes_put(self.cluster['id'],
expect_errors=True)
self.assertEqual(resp.status_code, 200)
task = resp.json_body
self.assertEqual(task['status'], consts.TASK_STATUSES.error)
self.assertEqual(task['progress'], 100)
self.assertEqual(task['name'], 'deploy')
self.assertIn("Address space intersection between networks:\n"
"admin (PXE), management.",
task['message'])
| 40.084848
| 79
| 0.60004
|
89b21958a0272c3d79b8c74565d4170040a236c2
| 2,650
|
py
|
Python
|
dtcwt/tf/common.py
|
OneOneFour/dtcwt
|
c34711561ba00386a727e499bd2ae249640f9aba
|
[
"BSD-2-Clause"
] | null | null | null |
dtcwt/tf/common.py
|
OneOneFour/dtcwt
|
c34711561ba00386a727e499bd2ae249640f9aba
|
[
"BSD-2-Clause"
] | null | null | null |
dtcwt/tf/common.py
|
OneOneFour/dtcwt
|
c34711561ba00386a727e499bd2ae249640f9aba
|
[
"BSD-2-Clause"
] | null | null | null |
from __future__ import absolute_import
try:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
except ImportError:
# The lack of tensorflow will be caught by the low-level routines.
pass
class Pyramid(object):
"""A tensorflow representation of a transform domain signal.
An interface-compatible version of
:py:class:`dtcwt.Pyramid` where the initialiser
arguments are assumed to be :py:class:`tf.Variable` instances.
The attributes defined in :py:class:`dtcwt.Pyramid`
are implemented via properties. The original tf arrays may be accessed
via the ``..._op(s)`` attributes.
.. py:attribute:: lowpass_op
A tensorflow tensor that can be evaluated in a session to return
the coarsest scale lowpass signal for the input, X.
.. py:attribute:: highpasses_op
A tuple of tensorflow tensors, where each element is the complex
subband coefficients for corresponding scales finest to coarsest.
.. py:attribute:: scales_ops
*(optional)* A tuple where each element is a tensorflow tensor
containing the lowpass signal for corresponding scales finest to
coarsest. This is not required for the inverse and may be *None*.
"""
def __init__(self, lowpass, highpasses, scales=None, numpy=False):
self.lowpass_op = lowpass
self.highpasses_ops = highpasses
self.scales_ops = scales
self.numpy = numpy
@property
def lowpass(self):
if not hasattr(self, '_lowpass'):
if self.lowpass_op is None:
self._lowpass = None
else:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self._lowpass = sess.run(self.lowpass_op)
return self._lowpass
@property
def highpasses(self):
if not hasattr(self, '_highpasses'):
if self.highpasses_ops is None:
self._highpasses = None
else:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self._highpasses = \
tuple(sess.run(x) for x in self.highpasses_ops)
return self._highpasses
@property
def scales(self):
if not hasattr(self, '_scales'):
if self.scales_ops is None:
self._scales = None
else:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
self._scales = tuple(sess.run(x) for x in self.scales_ops)
return self._scales
| 34.415584
| 78
| 0.623019
|
97ee7ff977a8203a0fa561b22e5d3098e87adad4
| 6,881
|
py
|
Python
|
sdk/python/pulumi_azure_nextgen/web/v20180201/get_web_app_vnet_connection.py
|
test-wiz-sec/pulumi-azure-nextgen
|
20a695af0d020b34b0f1c336e1b69702755174cc
|
[
"Apache-2.0"
] | null | null | null |
sdk/python/pulumi_azure_nextgen/web/v20180201/get_web_app_vnet_connection.py
|
test-wiz-sec/pulumi-azure-nextgen
|
20a695af0d020b34b0f1c336e1b69702755174cc
|
[
"Apache-2.0"
] | null | null | null |
sdk/python/pulumi_azure_nextgen/web/v20180201/get_web_app_vnet_connection.py
|
test-wiz-sec/pulumi-azure-nextgen
|
20a695af0d020b34b0f1c336e1b69702755174cc
|
[
"Apache-2.0"
] | null | null | null |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetWebAppVnetConnectionResult',
'AwaitableGetWebAppVnetConnectionResult',
'get_web_app_vnet_connection',
]
@pulumi.output_type
class GetWebAppVnetConnectionResult:
"""
Virtual Network information contract.
"""
def __init__(__self__, cert_blob=None, cert_thumbprint=None, dns_servers=None, is_swift=None, kind=None, name=None, resync_required=None, routes=None, type=None, vnet_resource_id=None):
if cert_blob and not isinstance(cert_blob, str):
raise TypeError("Expected argument 'cert_blob' to be a str")
pulumi.set(__self__, "cert_blob", cert_blob)
if cert_thumbprint and not isinstance(cert_thumbprint, str):
raise TypeError("Expected argument 'cert_thumbprint' to be a str")
pulumi.set(__self__, "cert_thumbprint", cert_thumbprint)
if dns_servers and not isinstance(dns_servers, str):
raise TypeError("Expected argument 'dns_servers' to be a str")
pulumi.set(__self__, "dns_servers", dns_servers)
if is_swift and not isinstance(is_swift, bool):
raise TypeError("Expected argument 'is_swift' to be a bool")
pulumi.set(__self__, "is_swift", is_swift)
if kind and not isinstance(kind, str):
raise TypeError("Expected argument 'kind' to be a str")
pulumi.set(__self__, "kind", kind)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if resync_required and not isinstance(resync_required, bool):
raise TypeError("Expected argument 'resync_required' to be a bool")
pulumi.set(__self__, "resync_required", resync_required)
if routes and not isinstance(routes, list):
raise TypeError("Expected argument 'routes' to be a list")
pulumi.set(__self__, "routes", routes)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
if vnet_resource_id and not isinstance(vnet_resource_id, str):
raise TypeError("Expected argument 'vnet_resource_id' to be a str")
pulumi.set(__self__, "vnet_resource_id", vnet_resource_id)
@property
@pulumi.getter(name="certBlob")
def cert_blob(self) -> Optional[str]:
"""
A certificate file (.cer) blob containing the public key of the private key used to authenticate a
Point-To-Site VPN connection.
"""
return pulumi.get(self, "cert_blob")
@property
@pulumi.getter(name="certThumbprint")
def cert_thumbprint(self) -> str:
"""
The client certificate thumbprint.
"""
return pulumi.get(self, "cert_thumbprint")
@property
@pulumi.getter(name="dnsServers")
def dns_servers(self) -> Optional[str]:
"""
DNS servers to be used by this Virtual Network. This should be a comma-separated list of IP addresses.
"""
return pulumi.get(self, "dns_servers")
@property
@pulumi.getter(name="isSwift")
def is_swift(self) -> Optional[bool]:
"""
Flag that is used to denote if this is VNET injection
"""
return pulumi.get(self, "is_swift")
@property
@pulumi.getter
def kind(self) -> Optional[str]:
"""
Kind of resource.
"""
return pulumi.get(self, "kind")
@property
@pulumi.getter
def name(self) -> str:
"""
Resource Name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="resyncRequired")
def resync_required(self) -> bool:
"""
<code>true</code> if a resync is required; otherwise, <code>false</code>.
"""
return pulumi.get(self, "resync_required")
@property
@pulumi.getter
def routes(self) -> Sequence['outputs.VnetRouteResponse']:
"""
The routes that this Virtual Network connection uses.
"""
return pulumi.get(self, "routes")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="vnetResourceId")
def vnet_resource_id(self) -> Optional[str]:
"""
The Virtual Network's resource ID.
"""
return pulumi.get(self, "vnet_resource_id")
class AwaitableGetWebAppVnetConnectionResult(GetWebAppVnetConnectionResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetWebAppVnetConnectionResult(
cert_blob=self.cert_blob,
cert_thumbprint=self.cert_thumbprint,
dns_servers=self.dns_servers,
is_swift=self.is_swift,
kind=self.kind,
name=self.name,
resync_required=self.resync_required,
routes=self.routes,
type=self.type,
vnet_resource_id=self.vnet_resource_id)
def get_web_app_vnet_connection(name: Optional[str] = None,
resource_group_name: Optional[str] = None,
vnet_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetWebAppVnetConnectionResult:
"""
Use this data source to access information about an existing resource.
:param str name: Name of the app.
:param str resource_group_name: Name of the resource group to which the resource belongs.
:param str vnet_name: Name of the virtual network.
"""
__args__ = dict()
__args__['name'] = name
__args__['resourceGroupName'] = resource_group_name
__args__['vnetName'] = vnet_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:web/v20180201:getWebAppVnetConnection', __args__, opts=opts, typ=GetWebAppVnetConnectionResult).value
return AwaitableGetWebAppVnetConnectionResult(
cert_blob=__ret__.cert_blob,
cert_thumbprint=__ret__.cert_thumbprint,
dns_servers=__ret__.dns_servers,
is_swift=__ret__.is_swift,
kind=__ret__.kind,
name=__ret__.name,
resync_required=__ret__.resync_required,
routes=__ret__.routes,
type=__ret__.type,
vnet_resource_id=__ret__.vnet_resource_id)
| 36.796791
| 189
| 0.646418
|
a5228ef1ec58881f3e0cd3632e63ac9e499be36c
| 12,310
|
py
|
Python
|
ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenodeinterestedvlanrange_02e7ef1c95a71c8d764fab0f1f227d4f.py
|
rfrye-github/ixnetwork_restpy
|
23eeb24b21568a23d3f31bbd72814ff55eb1af44
|
[
"MIT"
] | null | null | null |
ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenodeinterestedvlanrange_02e7ef1c95a71c8d764fab0f1f227d4f.py
|
rfrye-github/ixnetwork_restpy
|
23eeb24b21568a23d3f31bbd72814ff55eb1af44
|
[
"MIT"
] | null | null | null |
ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/dcenodeinterestedvlanrange_02e7ef1c95a71c8d764fab0f1f227d4f.py
|
rfrye-github/ixnetwork_restpy
|
23eeb24b21568a23d3f31bbd72814ff55eb1af44
|
[
"MIT"
] | null | null | null |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class DceNodeInterestedVlanRange(Base):
"""This object holds a list of DCE Node Interested Vlan Ranges.
The DceNodeInterestedVlanRange class encapsulates a list of dceNodeInterestedVlanRange resources that are managed by the user.
A list of resources can be retrieved from the server using the DceNodeInterestedVlanRange.find() method.
The list can be managed by using the DceNodeInterestedVlanRange.add() and DceNodeInterestedVlanRange.remove() methods.
"""
__slots__ = ()
_SDM_NAME = 'dceNodeInterestedVlanRange'
_SDM_ATT_MAP = {
'IncludeInLsp': 'includeInLsp',
'IncludeInMgroupPdu': 'includeInMgroupPdu',
'IncludeInterestedVlan': 'includeInterestedVlan',
'InternodeVlanStep': 'internodeVlanStep',
'M4BitEnabled': 'm4BitEnabled',
'M6BitEnabled': 'm6BitEnabled',
'NoOfSpanningTreeRoot': 'noOfSpanningTreeRoot',
'StartSpanningTreeRootBridgeId': 'startSpanningTreeRootBridgeId',
'StartVlanId': 'startVlanId',
'VlanIdCount': 'vlanIdCount',
}
def __init__(self, parent):
super(DceNodeInterestedVlanRange, self).__init__(parent)
@property
def IncludeInLsp(self):
"""
Returns
-------
- bool: If true, a custom VLAN is included in the LSP.
"""
return self._get_attribute(self._SDM_ATT_MAP['IncludeInLsp'])
@IncludeInLsp.setter
def IncludeInLsp(self, value):
self._set_attribute(self._SDM_ATT_MAP['IncludeInLsp'], value)
@property
def IncludeInMgroupPdu(self):
"""
Returns
-------
- bool: If true, a custom VLAN is included in the MGROUP PDU.
"""
return self._get_attribute(self._SDM_ATT_MAP['IncludeInMgroupPdu'])
@IncludeInMgroupPdu.setter
def IncludeInMgroupPdu(self, value):
self._set_attribute(self._SDM_ATT_MAP['IncludeInMgroupPdu'], value)
@property
def IncludeInterestedVlan(self):
"""
Returns
-------
- bool: If true, the interested VLAN is included.
"""
return self._get_attribute(self._SDM_ATT_MAP['IncludeInterestedVlan'])
@IncludeInterestedVlan.setter
def IncludeInterestedVlan(self, value):
self._set_attribute(self._SDM_ATT_MAP['IncludeInterestedVlan'], value)
@property
def InternodeVlanStep(self):
"""
Returns
-------
- number: It shows the Increment Step of internode Vlan ID. Default is 1.
"""
return self._get_attribute(self._SDM_ATT_MAP['InternodeVlanStep'])
@InternodeVlanStep.setter
def InternodeVlanStep(self, value):
self._set_attribute(self._SDM_ATT_MAP['InternodeVlanStep'], value)
@property
def M4BitEnabled(self):
"""
Returns
-------
- bool: If true, the M4 bit is enabled.
"""
return self._get_attribute(self._SDM_ATT_MAP['M4BitEnabled'])
@M4BitEnabled.setter
def M4BitEnabled(self, value):
self._set_attribute(self._SDM_ATT_MAP['M4BitEnabled'], value)
@property
def M6BitEnabled(self):
"""
Returns
-------
- bool: If true, the M6 bit is enabled.
"""
return self._get_attribute(self._SDM_ATT_MAP['M6BitEnabled'])
@M6BitEnabled.setter
def M6BitEnabled(self, value):
self._set_attribute(self._SDM_ATT_MAP['M6BitEnabled'], value)
@property
def NoOfSpanningTreeRoot(self):
"""
Returns
-------
- number: The number of spanning tree roots for the VLAN.
"""
return self._get_attribute(self._SDM_ATT_MAP['NoOfSpanningTreeRoot'])
@NoOfSpanningTreeRoot.setter
def NoOfSpanningTreeRoot(self, value):
self._set_attribute(self._SDM_ATT_MAP['NoOfSpanningTreeRoot'], value)
@property
def StartSpanningTreeRootBridgeId(self):
"""
Returns
-------
- str: If true, starts the spanning tree root Bridge Id.
"""
return self._get_attribute(self._SDM_ATT_MAP['StartSpanningTreeRootBridgeId'])
@StartSpanningTreeRootBridgeId.setter
def StartSpanningTreeRootBridgeId(self, value):
self._set_attribute(self._SDM_ATT_MAP['StartSpanningTreeRootBridgeId'], value)
@property
def StartVlanId(self):
"""
Returns
-------
- number: The VLAN Id of first VLAN. Default is 1.
"""
return self._get_attribute(self._SDM_ATT_MAP['StartVlanId'])
@StartVlanId.setter
def StartVlanId(self, value):
self._set_attribute(self._SDM_ATT_MAP['StartVlanId'], value)
@property
def VlanIdCount(self):
"""
Returns
-------
- number: The count of the VLAN Id.
"""
return self._get_attribute(self._SDM_ATT_MAP['VlanIdCount'])
@VlanIdCount.setter
def VlanIdCount(self, value):
self._set_attribute(self._SDM_ATT_MAP['VlanIdCount'], value)
def update(self, IncludeInLsp=None, IncludeInMgroupPdu=None, IncludeInterestedVlan=None, InternodeVlanStep=None, M4BitEnabled=None, M6BitEnabled=None, NoOfSpanningTreeRoot=None, StartSpanningTreeRootBridgeId=None, StartVlanId=None, VlanIdCount=None):
"""Updates dceNodeInterestedVlanRange resource on the server.
Args
----
- IncludeInLsp (bool): If true, a custom VLAN is included in the LSP.
- IncludeInMgroupPdu (bool): If true, a custom VLAN is included in the MGROUP PDU.
- IncludeInterestedVlan (bool): If true, the interested VLAN is included.
- InternodeVlanStep (number): It shows the Increment Step of internode Vlan ID. Default is 1.
- M4BitEnabled (bool): If true, the M4 bit is enabled.
- M6BitEnabled (bool): If true, the M6 bit is enabled.
- NoOfSpanningTreeRoot (number): The number of spanning tree roots for the VLAN.
- StartSpanningTreeRootBridgeId (str): If true, starts the spanning tree root Bridge Id.
- StartVlanId (number): The VLAN Id of first VLAN. Default is 1.
- VlanIdCount (number): The count of the VLAN Id.
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
def add(self, IncludeInLsp=None, IncludeInMgroupPdu=None, IncludeInterestedVlan=None, InternodeVlanStep=None, M4BitEnabled=None, M6BitEnabled=None, NoOfSpanningTreeRoot=None, StartSpanningTreeRootBridgeId=None, StartVlanId=None, VlanIdCount=None):
"""Adds a new dceNodeInterestedVlanRange resource on the server and adds it to the container.
Args
----
- IncludeInLsp (bool): If true, a custom VLAN is included in the LSP.
- IncludeInMgroupPdu (bool): If true, a custom VLAN is included in the MGROUP PDU.
- IncludeInterestedVlan (bool): If true, the interested VLAN is included.
- InternodeVlanStep (number): It shows the Increment Step of internode Vlan ID. Default is 1.
- M4BitEnabled (bool): If true, the M4 bit is enabled.
- M6BitEnabled (bool): If true, the M6 bit is enabled.
- NoOfSpanningTreeRoot (number): The number of spanning tree roots for the VLAN.
- StartSpanningTreeRootBridgeId (str): If true, starts the spanning tree root Bridge Id.
- StartVlanId (number): The VLAN Id of first VLAN. Default is 1.
- VlanIdCount (number): The count of the VLAN Id.
Returns
-------
- self: This instance with all currently retrieved dceNodeInterestedVlanRange resources using find and the newly added dceNodeInterestedVlanRange resources available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._create(self._map_locals(self._SDM_ATT_MAP, locals()))
def remove(self):
"""Deletes all the contained dceNodeInterestedVlanRange resources in this instance from the server.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
self._delete()
def find(self, IncludeInLsp=None, IncludeInMgroupPdu=None, IncludeInterestedVlan=None, InternodeVlanStep=None, M4BitEnabled=None, M6BitEnabled=None, NoOfSpanningTreeRoot=None, StartSpanningTreeRootBridgeId=None, StartVlanId=None, VlanIdCount=None):
"""Finds and retrieves dceNodeInterestedVlanRange resources from the server.
All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve dceNodeInterestedVlanRange resources from the server.
To retrieve an exact match ensure the parameter value starts with ^ and ends with $
By default the find method takes no parameters and will retrieve all dceNodeInterestedVlanRange resources from the server.
Args
----
- IncludeInLsp (bool): If true, a custom VLAN is included in the LSP.
- IncludeInMgroupPdu (bool): If true, a custom VLAN is included in the MGROUP PDU.
- IncludeInterestedVlan (bool): If true, the interested VLAN is included.
- InternodeVlanStep (number): It shows the Increment Step of internode Vlan ID. Default is 1.
- M4BitEnabled (bool): If true, the M4 bit is enabled.
- M6BitEnabled (bool): If true, the M6 bit is enabled.
- NoOfSpanningTreeRoot (number): The number of spanning tree roots for the VLAN.
- StartSpanningTreeRootBridgeId (str): If true, starts the spanning tree root Bridge Id.
- StartVlanId (number): The VLAN Id of first VLAN. Default is 1.
- VlanIdCount (number): The count of the VLAN Id.
Returns
-------
- self: This instance with matching dceNodeInterestedVlanRange resources retrieved from the server available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))
def read(self, href):
"""Retrieves a single instance of dceNodeInterestedVlanRange data from the server.
Args
----
- href (str): An href to the instance to be retrieved
Returns
-------
- self: This instance with the dceNodeInterestedVlanRange resources from the server available through an iterator or index
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
return self._read(href)
| 44.601449
| 255
| 0.6684
|
50018a8e60a806a7cc4e9102f9981c323b6252c3
| 6,414
|
py
|
Python
|
samples/cookbook/regression/custom_regression.py
|
vincentcheny/models
|
afb1a59fc1bc792ac72d1a3e22e2469020529788
|
[
"Apache-2.0"
] | 1
|
2019-09-11T09:41:11.000Z
|
2019-09-11T09:41:11.000Z
|
samples/cookbook/regression/custom_regression.py
|
vincentcheny/models
|
afb1a59fc1bc792ac72d1a3e22e2469020529788
|
[
"Apache-2.0"
] | null | null | null |
samples/cookbook/regression/custom_regression.py
|
vincentcheny/models
|
afb1a59fc1bc792ac72d1a3e22e2469020529788
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Regression using the DNNRegressor Estimator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import tensorflow as tf
import automobile_data
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
parser.add_argument('--train_steps', default=1000, type=int,
help='number of training steps')
parser.add_argument('--price_norm_factor', default=1000., type=float,
help='price normalization factor')
def my_dnn_regression_fn(features, labels, mode, params):
"""A model function implementing DNN regression for a custom Estimator."""
# Extract the input into a dense layer, according to the feature_columns.
top = tf.feature_column.input_layer(features, params["feature_columns"])
# Iterate over the "hidden_units" list of layer sizes, default is [20].
for units in params.get("hidden_units", [20]):
# Add a hidden layer, densely connected on top of the previous layer.
top = tf.layers.dense(inputs=top, units=units, activation=tf.nn.relu)
# Connect a linear output layer on top.
output_layer = tf.layers.dense(inputs=top, units=1)
# Reshape the output layer to a 1-dim Tensor to return predictions
predictions = tf.squeeze(output_layer, 1)
if mode == tf.estimator.ModeKeys.PREDICT:
# In `PREDICT` mode we only need to return predictions.
return tf.estimator.EstimatorSpec(
mode=mode, predictions={"price": predictions})
# Calculate loss using mean squared error
average_loss = tf.losses.mean_squared_error(labels, predictions)
# Pre-made estimators use the total_loss instead of the average,
# so report total_loss for compatibility.
batch_size = tf.shape(labels)[0]
total_loss = tf.to_float(batch_size) * average_loss
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = params.get("optimizer", tf.train.AdamOptimizer)
optimizer = optimizer(params.get("learning_rate", None))
train_op = optimizer.minimize(
loss=average_loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(
mode=mode, loss=total_loss, train_op=train_op)
# In evaluation mode we will calculate evaluation metrics.
assert mode == tf.estimator.ModeKeys.EVAL
# Calculate root mean squared error
print(labels)
print(predictions)
# Fixed for #4083
predictions = tf.cast(predictions, tf.float64)
rmse = tf.metrics.root_mean_squared_error(labels, predictions)
# Add the rmse to the collection of evaluation metrics.
eval_metrics = {"rmse": rmse}
return tf.estimator.EstimatorSpec(
mode=mode,
# Report sum of error for compatibility with pre-made estimators
loss=total_loss,
eval_metric_ops=eval_metrics)
def main(argv):
"""Builds, trains, and evaluates the model."""
args = parser.parse_args(argv[1:])
(train_x,train_y), (test_x, test_y) = automobile_data.load_data()
train_y /= args.price_norm_factor
test_y /= args.price_norm_factor
# Provide the training input dataset.
train_input_fn = automobile_data.make_dataset(args.batch_size, train_x, train_y, True, 1000)
# Build the validation dataset.
test_input_fn = automobile_data.make_dataset(args.batch_size, test_x, test_y)
# The first way assigns a unique weight to each category. To do this you must
# specify the category's vocabulary (values outside this specification will
# receive a weight of zero). Here we specify the vocabulary using a list of
# options. The vocabulary can also be specified with a vocabulary file (using
# `categorical_column_with_vocabulary_file`). For features covering a
# range of positive integers use `categorical_column_with_identity`.
body_style_vocab = ["hardtop", "wagon", "sedan", "hatchback", "convertible"]
body_style = tf.feature_column.categorical_column_with_vocabulary_list(
key="body-style", vocabulary_list=body_style_vocab)
make = tf.feature_column.categorical_column_with_hash_bucket(
key="make", hash_bucket_size=50)
feature_columns = [
tf.feature_column.numeric_column(key="curb-weight"),
tf.feature_column.numeric_column(key="highway-mpg"),
# Since this is a DNN model, convert categorical columns from sparse
# to dense.
# Wrap them in an `indicator_column` to create a
# one-hot vector from the input.
tf.feature_column.indicator_column(body_style),
# Or use an `embedding_column` to create a trainable vector for each
# index.
tf.feature_column.embedding_column(make, dimension=3),
]
# Build a custom Estimator, using the model_fn.
# `params` is passed through to the `model_fn`.
model = tf.estimator.Estimator(
model_fn=my_dnn_regression_fn,
params={
"feature_columns": feature_columns,
"learning_rate": 0.001,
"optimizer": tf.train.AdamOptimizer,
"hidden_units": [20, 20]
})
# Train the model.
model.train(input_fn=train_input_fn, steps=args.train_steps)
# Evaluate how the model performs on data it has not yet seen.
eval_result = model.evaluate(input_fn=test_input_fn)
# Print the Root Mean Square Error (RMSE).
print("\n" + 80 * "*")
print("\nRMS error for the test set: ${:.0f}"
.format(args.price_norm_factor * eval_result["rmse"]))
print()
if __name__ == "__main__":
# The Estimator periodically generates "INFO" logs; make these logs visible.
tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run(main=main)
| 39.109756
| 95
| 0.704085
|
03dde642babfb6267b5a0e3381e4627249da49e9
| 1,623
|
py
|
Python
|
checkov/terraform/checks/resource/aws/SecurityGroupUnrestrictedIngress22.py
|
acdha/checkov
|
3b78cd6297f5b708f63aebd8c07acecf252ffa05
|
[
"Apache-2.0"
] | null | null | null |
checkov/terraform/checks/resource/aws/SecurityGroupUnrestrictedIngress22.py
|
acdha/checkov
|
3b78cd6297f5b708f63aebd8c07acecf252ffa05
|
[
"Apache-2.0"
] | 1
|
2021-06-02T02:53:31.000Z
|
2021-06-02T02:53:31.000Z
|
checkov/terraform/checks/resource/aws/SecurityGroupUnrestrictedIngress22.py
|
acdha/checkov
|
3b78cd6297f5b708f63aebd8c07acecf252ffa05
|
[
"Apache-2.0"
] | null | null | null |
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
from checkov.common.util.type_forcers import force_list
PORT = 22
class SecurityGroupUnrestrictedIngress22(BaseResourceCheck):
def __init__(self):
name = "Ensure no security groups allow ingress from 0.0.0.0:0 to port %d" % PORT
id = "CKV_AWS_24"
supported_resources = ['aws_security_group']
categories = [CheckCategories.NETWORKING]
super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources)
def scan_resource_conf(self, conf):
"""
Looks for configuration at security group ingress rules :
https://www.terraform.io/docs/providers/aws/r/security_group.html
:param conf: aws_security_group configuration
:return: <CheckResult>
"""
if 'ingress' in conf.keys():
ingress_conf = conf['ingress']
for rule in ingress_conf:
if isinstance(rule, dict):
if isinstance(force_list(rule['from_port'])[0],int) and isinstance(force_list(rule['to_port'])[0],int):
if rule['from_port'] == [PORT] and rule['to_port'] == [PORT]:
if 'cidr_blocks' in rule.keys():
if rule['cidr_blocks'] == [["0.0.0.0/0"]] and 'security_groups' not in rule.keys():
return CheckResult.FAILED
return CheckResult.PASSED
check = SecurityGroupUnrestrictedIngress22()
| 43.864865
| 123
| 0.636476
|
bb6c4c1a03ec8f9274fb4ce1638c9e19c69892a2
| 1,713
|
py
|
Python
|
tests/actors/accessibility/test_simulator.py
|
reapler/geckordp
|
29dab2e6e691954a473e054fa95ba40a3ad10e53
|
[
"MIT"
] | 1
|
2021-12-24T04:37:02.000Z
|
2021-12-24T04:37:02.000Z
|
tests/actors/accessibility/test_simulator.py
|
jpramosi/geckordp
|
29dab2e6e691954a473e054fa95ba40a3ad10e53
|
[
"MIT"
] | 1
|
2021-07-23T13:38:36.000Z
|
2021-08-07T14:17:54.000Z
|
tests/actors/accessibility/test_simulator.py
|
reapler/geckordp
|
29dab2e6e691954a473e054fa95ba40a3ad10e53
|
[
"MIT"
] | 1
|
2021-10-31T17:31:35.000Z
|
2021-10-31T17:31:35.000Z
|
# pylint: disable=unused-import
import pytest
import tests.helpers.constants as constants
from tests.helpers.utils import *
from geckordp.rdp_client import RDPClient
from geckordp.actors.root import RootActor
from geckordp.actors.descriptors.tab import TabActor
from geckordp.actors.accessibility.accessibility import AccessibilityActor
from geckordp.actors.accessibility.simulator import SimulatorActor
from geckordp.actors.accessibility.parent_accessibility import ParentAccessibilityActor
from geckordp.logger import log, logdict
def init():
cl = RDPClient(3)
cl.connect(constants.REMOTE_HOST, constants.REMOTE_PORT)
root = RootActor(cl)
current_tab = root.current_tab()
tab = TabActor(cl, current_tab["actor"])
actor_ids = tab.get_target()
root_ids = root.get_root()
accessibility = AccessibilityActor(cl, actor_ids["accessibilityActor"])
simulator_id = accessibility.get_simulator().get("actor", None)
if (simulator_id is None):
log("No simulator actor found, firefox is probably running in headless mode")
return cl, None
simulator = SimulatorActor(cl, simulator_id)
accessibility.bootstrap()
parent = ParentAccessibilityActor(
cl, root_ids["parentAccessibilityActor"])
parent.bootstrap()
parent.enable()
return cl, simulator
def test_simulate():
cl = None
try:
cl, simulator = init()
if (simulator is None):
return
val = simulator.simulate(SimulatorActor.Types.PROTANOPIA)
assert val.get("value", None) is not None
val = simulator.simulate(SimulatorActor.Types.NONE)
assert val.get("value", None) is not None
finally:
cl.disconnect()
| 35.6875
| 87
| 0.729714
|
751616e1c546cb4c31557124c668c546a7135240
| 4,999
|
py
|
Python
|
predicting_abx_resistance/PerMutation-GA.py
|
broadinstitute/PerMutation
|
84ff524e53a701c1deb7f253b4caf219e2eb9016
|
[
"BSD-3-Clause"
] | null | null | null |
predicting_abx_resistance/PerMutation-GA.py
|
broadinstitute/PerMutation
|
84ff524e53a701c1deb7f253b4caf219e2eb9016
|
[
"BSD-3-Clause"
] | null | null | null |
predicting_abx_resistance/PerMutation-GA.py
|
broadinstitute/PerMutation
|
84ff524e53a701c1deb7f253b4caf219e2eb9016
|
[
"BSD-3-Clause"
] | 1
|
2021-09-29T16:48:52.000Z
|
2021-09-29T16:48:52.000Z
|
import os
import sys
import argparse
from collections import defaultdict
import numpy
import math
def p_adjust_bh(p):
"""
Using implementation from https://stackoverflow.com/questions/7450957/how-to-implement-rs-p-adjust-in-python/33532498#33532498
Benjamini-Hochberg p-value correction for multiple hypothesis testing.
"""
p = numpy.asfarray(p)
by_descend = p.argsort()[::-1]
by_orig = by_descend.argsort()
steps = float(len(p)) / numpy.arange(len(p), 0, -1)
q = numpy.minimum(1, numpy.minimum.accumulate(steps * p[by_descend]))
return q[by_orig]
def read_in_wig_data(all_wigs):
wigdata = []
position = []
for i, wf in enumerate(all_wigs):
sample_counts = []
with open(wf) as owf:
for line in owf:
line = line.strip()
ls = line.split('\t')
if line.startswith("variableStep"): continue
if i == 0: position.append(int(ls[0]))
sample_counts.append(float(ls[1]))
wigdata.append(sample_counts)
wigdata_tr = []
for ls in zip(*wigdata):
wigdata_tr.append(list(ls))
return ([position, wigdata_tr])
def resampling(control_data, treatment_data, S=100000):
count_greater = 0
n_control = len(list(control_data.values())[0])
control_mean = numpy.average([sum(x[1]) for x in control_data.items()])
treatment_mean = numpy.average([sum(x[1]) for x in treatment_data.items()])
log2FC = (control_mean + 0.1)/(treatment_mean+0.1)
stat_obs = 0
test_data = []
for ind in control_data:
control_sum = sum(control_data[ind])
treat_sum = sum(treatment_data[ind])
test_data.append(control_data[ind] + treatment_data[ind])
stat_obs += treat_sum - control_sum
for j, s in enumerate(range(S)):
stat = 0
for pos_vals in test_data:
perm_vals = numpy.random.permutation(pos_vals)
stat += sum(perm_vals[n_control:]) - sum(perm_vals[:n_control])
if stat >= stat_obs: count_greater += 1
pval_greater = float(count_greater) / float(S)
return (stat_obs, log2FC, pval_greater)
def create_parser():
# Parse arguments.
parser = argparse.ArgumentParser(description=""" This program runs a position aware variant of the permutation test developed by DeJesus et al 2015.""")
parser.add_argument('-c', '--control_wigs', help='control wig files separated by comma.', required=True)
parser.add_argument('-e', '--experiment_wigs', help='experimental wig files separated by comma.', required=True)
parser.add_argument('-b', '--bed_file', help='BED file with four columns: scaffold id, start position, end position, gene id', required=True)
parser.add_argument('-s', '--scaffold', help='scaffold id', required=True)
parser.add_argument('-o', '--output', help='output file', required=True)
args = parser.parse_args()
return args
# parse arguments
myargs = create_parser()
control_wigs = myargs.control_wigs.split(',')
experiment_wigs = myargs.experiment_wigs.split(',')
bed_file = myargs.bed_file
output_file = myargs.output
scaffold = myargs.scaffold
replicate_labels = ['control']*len(control_wigs) + ['experiment']*len(experiment_wigs)
all_wigs = control_wigs + experiment_wigs
position, wigdata = read_in_wig_data(all_wigs)
pos_to_index = {}
for i, p in enumerate(position):
nz_flag = False
for r in wigdata:
if r[i] > 0.0:
nz_flag = True
if nz_flag:
pos_to_index[p] = i
all_info = []
pvalues = []
with open(bed_file) as obf:
for line in obf:
line = line.rstrip('\n')
feature_scaffold, start, stop, description = line.split('\t')
relevant_indices = []
start = min(int(start), int(stop))
stop = max(int(start), int(stop))
glen = abs(start - stop) + 1
start = int(math.floor(start + (glen * 0.10)))
stop = int(math.ceil(stop - (glen * 0.10)))
for p in range(start, stop+1):
if p in pos_to_index:
relevant_indices.append(pos_to_index[p])
if not relevant_indices: continue
control_samples = defaultdict(list)
experiment_samples = defaultdict(list)
for ind in relevant_indices:
for r in range(0,len(control_wigs)):
control_samples[ind].append(wigdata[r][ind])
for r in range(len(control_wigs), (len(control_wigs)+len(experiment_wigs))):
experiment_samples[ind].append(wigdata[r][ind])
stat, log2FC, pval = resampling(control_samples, experiment_samples)
all_info.append([feature_scaffold, start, stop, description, log2FC, stat, pval])
pvalues.append(pval)
outf = open(output_file, 'w')
qvalues = p_adjust_bh(pvalues)
for i, q in enumerate(qvalues):
outf.write('\t'.join([ str(x) for x in (all_info[i] + [q])])+ '\n')
outf.close()
| 36.489051
| 156
| 0.638328
|
a9a0dae567cc7d99c3270f100c14fe73db91c48b
| 2,394
|
py
|
Python
|
host-software/keyplus/keycodes/lang_map/Russian0.py
|
ai03-2725/keyplus
|
6fb857dff7aa88284d6f6f08532f8da3aae981e1
|
[
"MIT"
] | 226
|
2017-08-14T16:11:36.000Z
|
2022-03-13T00:58:13.000Z
|
host-software/keyplus/keycodes/lang_map/Russian0.py
|
ai03-2725/keyplus
|
6fb857dff7aa88284d6f6f08532f8da3aae981e1
|
[
"MIT"
] | 90
|
2017-09-12T02:07:39.000Z
|
2022-01-27T20:58:19.000Z
|
host-software/keyplus/keycodes/lang_map/Russian0.py
|
ai03-2725/keyplus
|
6fb857dff7aa88284d6f6f08532f8da3aae981e1
|
[
"MIT"
] | 44
|
2017-09-17T17:31:25.000Z
|
2022-02-27T08:19:46.000Z
|
# Copyright 2018 jem@seethis.link
# Licensed under the MIT license (http://opensource.org/licenses/MIT)
from hid_keycodes import *
lang = 'Russian'
country = 'Russia'
scancode_map = {
KC_0: ('0', ')', '', '%', '0', ''),
KC_1: ('1', '!', '', '№', '1', ''),
KC_2: ('2', '@', '', '-', '2', ''),
KC_3: ('3', '#', '', '/', '3', ''),
KC_4: ('4', '$', '', '"', '4', ''),
KC_5: ('5', '%', '', ':', '5', ''),
KC_6: ('6', '^', '', ',', '6', ''),
KC_7: ('7', '&', '', '.', '7', ''),
KC_8: ('8', '*', '', '_', '8', ''),
KC_9: ('9', '(', '', '?', '9', ''),
KC_A: ('a', 'A', '', 'ф', 'Ф', ''),
KC_B: ('b', 'B', '', 'и', 'И', ''),
KC_C: ('c', 'C', '', 'с', 'С', ''),
KC_D: ('d', 'D', '', 'в', 'В', ''),
KC_E: ('e', 'E', '€', 'у', 'У', ''),
KC_F: ('f', 'F', '', 'а', 'А', ''),
KC_G: ('g', 'G', '', 'п', 'П', ''),
KC_H: ('h', 'H', '', 'р', 'Р', ''),
KC_I: ('i', 'I', '', 'ш', 'Ш', ''),
KC_J: ('j', 'J', '', 'о', 'О', ''),
KC_K: ('k', 'K', '', 'л', 'Л', ''),
KC_L: ('l', 'L', '', 'д', 'Д', ''),
KC_M: ('m', 'M', '', 'ь', 'Ь', ''),
KC_N: ('n', 'N', '', 'т', 'Т', ''),
KC_O: ('o', 'O', '', 'щ', 'Щ', ''),
KC_P: ('p', 'P', '', 'з', 'З', ''),
KC_Q: ('q', 'Q', '', 'й', 'Й', ''),
KC_R: ('r', 'R', '', 'к', 'К', ''),
KC_S: ('s', 'S', '', 'ы', 'Ы', ''),
KC_T: ('t', 'T', '', 'е', 'Е', ''),
KC_U: ('u', 'U', '', 'г', 'Г', ''),
KC_V: ('v', 'V', '', 'м', 'М', ''),
KC_W: ('w', 'W', '', 'ц', 'Ц', ''),
KC_X: ('x', 'X', '', 'ч', 'Ч', ''),
KC_Y: ('y', 'Y', '', 'н', 'Н', ''),
KC_Z: ('z', 'Z', '', 'я', 'Я', ''),
KC_APOSTROPHE: ("'", '"', '', 'э', 'Э', ''),
KC_BACKSPACE: ('\x08', '\x08', '', '\x08', '\x08', ''),
KC_BACK_SLASH: ('\\', '|', '', ')', '(', ''),
KC_COMMA: (',', '<', '', 'б', 'Б', ''),
KC_ENTER: ('\r', '', '', '', '', ''),
KC_EQUAL: ('=', '+', '', ';', '\\', ''),
KC_FORWARD_SLASH: ('-', '_', '-', '-', '_', ''),
KC_FORWARD_SLASH: ('/', '?', '', 'ё', 'Ё', ''),
KC_GRAVE: ('`', '~', '', '|', '+', ''),
KC_LEFT_BRACKET: ('[', '{', '', 'х', 'Х', ''),
KC_MINUS: ('-', '_', '', '!', '=', ''),
KC_PERIOD: ('.', '>', '', 'ю', 'Ю', ''),
KC_RIGHT_BRACKET: (']', '}', '', 'ъ', 'Ъ', ''),
KC_SEMICOLON: (';', ':', '', 'ж', 'Ж', ''),
KC_SPACEBAR: (' ', ' ', '', ' ', ' ', ''),
KC_TAB: ('\t', '', '', '\t', '', ''),
}
| 40.576271
| 69
| 0.258563
|
25d3ac79100655319309995ddd07e3e669de0d74
| 368,315
|
py
|
Python
|
oscar/lib/python2.7/site-packages/phonenumbers/geodata/data1.py
|
sainjusajan/django-oscar
|
466e8edc807be689b0a28c9e525c8323cc48b8e1
|
[
"BSD-3-Clause"
] | null | null | null |
oscar/lib/python2.7/site-packages/phonenumbers/geodata/data1.py
|
sainjusajan/django-oscar
|
466e8edc807be689b0a28c9e525c8323cc48b8e1
|
[
"BSD-3-Clause"
] | null | null | null |
oscar/lib/python2.7/site-packages/phonenumbers/geodata/data1.py
|
sainjusajan/django-oscar
|
466e8edc807be689b0a28c9e525c8323cc48b8e1
|
[
"BSD-3-Clause"
] | null | null | null |
"""Per-prefix data, mapping each prefix to a dict of locale:name.
Auto-generated file, do not edit by hand.
"""
from ..util import u
# Copyright (C) 2011-2017 The Libphonenumber Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
data = {
'1514303':{'en': 'Montreal, QC'},
'1570601':{'en': 'Williamsport, PA'},
'1570602':{'en': 'Pittston, PA'},
'1513844':{'en': 'Hamilton, OH'},
'1513841':{'en': 'Cincinnati, OH'},
'1518435':{'en': 'Albany, NY'},
'1450532':{'en': 'Valcourt, QC'},
'1518437':{'en': 'Albany, NY'},
'1450530':{'en': u('Saint-J\u00e9r\u00f4me, QC')},
'1575234':{'en': 'Carlsbad, NM'},
'1450534':{'en': 'Bromont, QC'},
'1450539':{'en': 'Waterloo, QC'},
'1450538':{'en': 'Sutton, QC'},
'1518439':{'en': 'Delmar, NY'},
'1518438':{'en': 'Albany, NY'},
'1510790':{'en': 'Fremont, CA'},
'1510791':{'en': 'Fremont, CA'},
'1510792':{'en': 'Fremont, CA'},
'1510793':{'en': 'Fremont, CA'},
'1510794':{'en': 'Fremont, CA'},
'1510795':{'en': 'Fremont, CA'},
'1510796':{'en': 'Fremont, CA'},
'1510797':{'en': 'Fremont, CA'},
'1530532':{'en': 'Oroville, CA'},
'1530533':{'en': 'Oroville, CA'},
'1501624':{'en': 'Hot Springs, AR'},
'1501625':{'en': 'Hot Springs, AR'},
'1501622':{'en': 'Hot Springs, AR'},
'1501623':{'en': 'Hot Springs, AR'},
'1501620':{'en': 'Hot Springs, AR'},
'1480968':{'en': 'Tempe, AZ'},
'1530538':{'en': 'Oroville, CA'},
'1605665':{'en': 'Yankton, SD'},
'1615340':{'en': 'Nashville, TN'},
'1573898':{'en': 'Elsberry, MO'},
'1520977':{'en': 'Tucson, AZ'},
'1607692':{'en': 'Whitney Point, NY'},
'1607693':{'en': 'Harpursville, NY'},
'1615352':{'en': 'Nashville, TN'},
'1615353':{'en': 'Nashville, TN'},
'1615350':{'en': 'Nashville, TN'},
'1607698':{'en': 'Canisteo, NY'},
'1607699':{'en': 'Nichols, NY'},
'1610796':{'en': 'Reading, PA'},
'1615355':{'en': 'Smyrna, TN'},
'1519744':{'en': 'Kitchener, ON'},
'1519745':{'en': 'Kitchener, ON'},
'1519746':{'en': 'Waterloo, ON'},
'1519747':{'en': 'Waterloo, ON'},
'1519740':{'en': 'Cambridge, ON'},
'1519741':{'en': 'Kitchener, ON'},
'1519742':{'en': 'Kitchener, ON'},
'1519743':{'en': 'Kitchener, ON'},
'1604255':{'en': 'Vancouver, BC'},
'1604254':{'en': 'Vancouver, BC'},
'1604257':{'en': 'Vancouver, BC'},
'1585922':{'en': 'Rochester, NY'},
'1519748':{'en': 'Kitchener, ON'},
'1519749':{'en': 'Kitchener, ON'},
'1604253':{'en': 'Vancouver, BC'},
'1505385':{'en': 'Albuquerque, NM'},
'1605698':{'en': 'Sisseton, SD'},
'1518434':{'en': 'Albany, NY'},
'1573803':{'en': 'Cape Girardeau, MO'},
'1605697':{'en': 'Brookings, SD'},
'1605692':{'en': 'Brookings, SD'},
'1605693':{'en': 'Brookings, SD'},
'1518436':{'en': 'Albany, NY'},
'1608429':{'en': 'Pardeeville, WI'},
'1608427':{'en': 'Camp Douglas, WI'},
'1608424':{'en': 'Belleville, WI'},
'1608423':{'en': 'Cambridge, WI'},
'1518432':{'en': 'Albany, NY'},
'1508251':{'en': 'Marlborough, MA'},
'1508252':{'en': 'Rehoboth, MA'},
'1508255':{'en': 'Orleans, MA'},
'1519925':{'en': 'Shelburne, ON'},
'1604986':{'en': 'North Vancouver, BC'},
'1605348':{'en': 'Rapid City, SD'},
'1610449':{'en': 'Havertown, PA'},
'1440926':{'en': 'Grafton, OH'},
'1519436':{'en': 'Chatham, ON'},
'1605342':{'en': 'Rapid City, SD'},
'1605343':{'en': 'Rapid City, SD'},
'1605345':{'en': 'Webster, SD'},
'1505632':{'en': 'Bloomfield, NM'},
'1480983':{'en': 'Apache Junction, AZ'},
'1480982':{'en': 'Apache Junction, AZ'},
'1480981':{'en': 'Mesa, AZ'},
'1480987':{'en': 'Queen Creek, AZ'},
'1480986':{'en': 'Mesa, AZ'},
'1480985':{'en': 'Mesa, AZ'},
'1480984':{'en': 'Mesa, AZ'},
'1503494':{'en': 'Portland, OR'},
'1503493':{'en': 'Portland, OR'},
'1503492':{'en': 'Gresham, OR'},
'1614409':{'en': 'Columbus, OH'},
'1610388':{'en': 'Chadds Ford, PA'},
'1609597':{'en': 'Manahawkin, NJ'},
'1609599':{'en': 'Trenton, NJ'},
'1610383':{'en': 'Coatesville, PA'},
'1610380':{'en': 'Coatesville, PA'},
'1610384':{'en': 'Coatesville, PA'},
'1504831':{'en': 'Metairie, LA'},
'1541868':{'en': 'Eugene, OR'},
'1541863':{'en': 'Myrtle Creek, OR'},
'1410334':{'en': 'Salisbury, MD'},
'1410337':{'en': 'Towson, MD'},
'1410841':{'en': 'Annapolis, MD'},
'1410332':{'en': 'Baltimore, MD'},
'1410338':{'en': 'Baltimore, MD'},
'1410849':{'en': 'Annapolis, MD'},
'1410848':{'en': 'Westminster, MD'},
'1612673':{'en': 'Minneapolis, MN'},
'1604983':{'en': 'North Vancouver, BC'},
'1610447':{'en': 'Chester, PA'},
'1562912':{'en': 'Long Beach, CA'},
'1508875':{'en': 'Framingham, MA'},
'1508877':{'en': 'Framingham, MA'},
'1508870':{'en': 'Westborough, MA'},
'1574372':{'en': 'Warsaw, IN'},
'1508872':{'en': 'Framingham, MA'},
'1503595':{'en': 'Portland, OR'},
'1423365':{'en': 'Spring City, TN'},
'1601847':{'en': 'Mendenhall, MS'},
'1601845':{'en': 'Florence, MS'},
'1601336':{'en': 'Hattiesburg, MS'},
'1561939':{'en': 'Boca Raton, FL'},
'1610690':{'en': 'Springfield, PA'},
'1601849':{'en': 'Magee, MS'},
'1480325':{'en': 'Mesa, AZ'},
'1516791':{'en': 'Valley Stream, NY'},
'1480323':{'en': 'Scottsdale, AZ'},
'1516825':{'en': 'Valley Stream, NY'},
'1516794':{'en': 'East Meadow, NY'},
'1516795':{'en': 'Massapequa, NY'},
'1516829':{'en': 'Great Neck, NY'},
'1516798':{'en': 'Massapequa, NY'},
'1516799':{'en': 'Massapequa, NY'},
'1609921':{'en': 'Princeton, NJ'},
'1418548':{'en': u('Jonqui\u00e8re, QC')},
'1418549':{'en': 'Chicoutimi, QC'},
'1504948':{'en': 'New Orleans, LA'},
'1504949':{'en': 'New Orleans, LA'},
'1610969':{'en': 'Allentown, PA'},
'1418542':{'en': u('Jonqui\u00e8re, QC')},
'1415863':{'en': 'San Francisco, CA'},
'1610964':{'en': 'Wayne, PA'},
'1415861':{'en': 'San Francisco, CA'},
'1435635':{'en': 'Hurricane, UT'},
'1418547':{'en': u('Jonqui\u00e8re, QC')},
'1415864':{'en': 'San Francisco, CA'},
'1415865':{'en': 'San Francisco, CA'},
'1603679':{'en': 'Epping, NH'},
'1573547':{'en': 'Perryville, MO'},
'1502722':{'en': 'Simpsonville, KY'},
'1502721':{'en': 'Louisville, KY'},
'1540731':{'en': 'Radford, VA'},
'1606932':{'en': 'South Shore, KY'},
'1440582':{'en': 'Cleveland, OH'},
'1509434':{'en': 'Spokane, WA'},
'1513672':{'en': 'Cincinnati, OH'},
'1518347':{'en': 'Schenectady, NY'},
'1612522':{'en': 'Minneapolis, MN'},
'1513671':{'en': 'Cincinnati, OH'},
'1513674':{'en': 'Cincinnati, OH'},
'1417646':{'en': 'Osceola, MO'},
'1502625':{'en': 'Louisville, KY'},
'1502624':{'en': 'Fort Knox, KY'},
'1502629':{'en': 'Louisville, KY'},
'1607217':{'en': 'Binghamton, NY'},
'1417649':{'en': 'Carl Junction, MO'},
'1507424':{'en': 'Rochester, MN'},
'1412856':{'en': 'Monroeville, PA'},
'1541488':{'en': 'Ashland, OR'},
'1541482':{'en': 'Ashland, OR'},
'1541481':{'en': 'Boardman, OR'},
'1541484':{'en': 'Eugene, OR'},
'1541485':{'en': 'Eugene, OR'},
'1530534':{'en': 'Oroville, CA'},
'1561750':{'en': 'Boca Raton, FL'},
'1561752':{'en': 'Boynton Beach, FL'},
'1561756':{'en': 'Boca Raton, FL'},
'1613924':{'en': 'Athens, ON'},
'1540955':{'en': 'Berryville, VA'},
'1415875':{'en': 'San Francisco, CA'},
'1510639':{'en': 'Oakland, CA'},
'1510638':{'en': 'Oakland, CA'},
'1510633':{'en': 'Oakland, CA'},
'1510632':{'en': 'Oakland, CA'},
'1510324':{'en': 'Union City, CA'},
'1510635':{'en': 'Oakland, CA'},
'1602542':{'en': 'Phoenix, AZ'},
'1602546':{'en': 'Phoenix, AZ'},
'1602548':{'en': 'Phoenix, AZ'},
'1519915':{'en': 'Windsor, ON'},
'1614292':{'en': 'Columbus, OH'},
'1518358':{'en': 'Hogansburg, NY'},
'1518359':{'en': 'Tupper Lake, NY'},
'1509939':{'en': 'Spokane, WA'},
'1509396':{'en': 'Kennewick, WA'},
'1509397':{'en': 'Colfax, WA'},
'1509427':{'en': 'Stevenson, WA'},
'1518355':{'en': 'Schenectady, NY'},
'1509422':{'en': 'Okanogan, WA'},
'1509935':{'en': 'Chewelah, WA'},
'1614293':{'en': 'Columbus, OH'},
'1413547':{'en': 'Ludlow, MA'},
'1413545':{'en': 'Amherst, MA'},
'1413549':{'en': 'Amherst, MA'},
'1408885':{'en': 'San Jose, CA'},
'1412765':{'en': 'Pittsburgh, PA'},
'1412766':{'en': 'Pittsburgh, PA'},
'1412761':{'en': 'Pittsburgh, PA'},
'1415268':{'en': 'San Francisco, CA'},
'1509647':{'en': 'Wilbur, WA'},
'1573234':{'en': 'Columbia, MO'},
'1603766':{'en': 'Portsmouth, NH'},
'1573237':{'en': 'New Haven, MO'},
'1603763':{'en': 'Sunapee, NH'},
'1504373':{'en': 'New Orleans, LA'},
'1573231':{'en': 'Hannibal, MO'},
'1415273':{'en': 'San Francisco, CA'},
'1609452':{'en': 'Princeton, NJ'},
'1512243':{'en': 'Austin, TX'},
'1512244':{'en': 'Round Rock, TX'},
'1512246':{'en': 'Round Rock, TX'},
'1512247':{'en': 'Del Valle, TX'},
'1573545':{'en': 'Benton, MO'},
'1416686':{'en': 'Toronto, ON'},
'1574232':{'en': 'South Bend, IN'},
'1605598':{'en': 'Faulkton, SD'},
'1605594':{'en': 'Garretson, SD'},
'1614298':{'en': 'Columbus, OH'},
'1520568':{'en': 'Maricopa, AZ'},
'1501470':{'en': 'Mayflower, AR'},
'1520562':{'en': 'Sacaton, AZ'},
'1418748':{'en': 'Chibougamau, QC'},
'1506847':{'en': 'Rothesay, NB'},
'1419433':{'en': 'Huron, OH'},
'1419435':{'en': 'Fostoria, OH'},
'1512358':{'en': 'Austin, TX'},
'1419436':{'en': 'Fostoria, OH'},
'1570251':{'en': 'Honesdale, PA'},
'1574855':{'en': 'South Bend, IN'},
'1418745':{'en': 'Chapais, QC'},
'1419557':{'en': 'Sandusky, OH'},
'1414359':{'en': 'Milwaukee, WI'},
'1414358':{'en': 'Milwaukee, WI'},
'1573499':{'en': 'Columbia, MO'},
'1414353':{'en': 'Milwaukee, WI'},
'1414352':{'en': 'Milwaukee, WI'},
'1414351':{'en': 'Milwaukee, WI'},
'1508998':{'en': 'New Bedford, MA'},
'1414357':{'en': 'Milwaukee, WI'},
'1414355':{'en': 'Milwaukee, WI'},
'1414354':{'en': 'Milwaukee, WI'},
'1615356':{'en': 'Nashville, TN'},
'1562633':{'en': 'Paramount, CA'},
'1480668':{'en': 'Mesa, AZ'},
'1610770':{'en': 'Allentown, PA'},
'1610776':{'en': 'Allentown, PA'},
'1610775':{'en': 'Reading, PA'},
'1480844':{'en': 'Mesa, AZ'},
'1480661':{'en': 'Scottsdale, AZ'},
'1617277':{'en': 'Brookline, MA'},
'1419882':{'en': 'Sylvania, OH'},
'1505401':{'en': 'Albuquerque, NM'},
'1419884':{'en': 'Lexington, OH'},
'1419885':{'en': 'Sylvania, OH'},
'1419886':{'en': 'Bellville, OH'},
'1419887':{'en': 'Maumee, OH'},
'1601450':{'en': 'Hattiesburg, MS'},
'1530695':{'en': 'Live Oak, CA'},
'1516367':{'en': 'Woodbury, NY'},
'1516365':{'en': 'Manhasset, NY'},
'1516364':{'en': 'Syosset, NY'},
'1614898':{'en': 'Westerville, OH'},
'1614899':{'en': 'Westerville, OH'},
'1610599':{'en': 'Bangor, PA'},
'1614890':{'en': 'Westerville, OH'},
'1610594':{'en': 'Exton, PA'},
'1614895':{'en': 'Westerville, OH'},
'1602229':{'en': 'Phoenix, AZ'},
'1514525':{'en': 'Montreal, QC'},
'1602222':{'en': 'Phoenix, AZ'},
'1602224':{'en': 'Phoenix, AZ'},
'1602225':{'en': 'Phoenix, AZ'},
'1503728':{'en': 'Clatskanie, OR'},
'1418687':{'en': 'Quebec City, QC'},
'1418686':{'en': 'Quebec City, QC'},
'1418681':{'en': 'Quebec City, QC'},
'1418683':{'en': 'Quebec City, QC'},
'1418682':{'en': 'Quebec City, QC'},
'1418689':{'en': 'Chandler, QC'},
'1410455':{'en': 'Catonsville, MD'},
'1548':{'en': 'Ontario'},
'1410457':{'en': 'Darlington, MD'},
'1575434':{'en': 'Alamogordo, NM'},
'1541298':{'en': 'The Dalles, OR'},
'1541296':{'en': 'The Dalles, OR'},
'1410342':{'en': 'Baltimore, MD'},
'1440563':{'en': 'Rock Creek, OH'},
'1440564':{'en': 'Newbury, OH'},
'1413229':{'en': 'Sheffield, MA'},
'1501332':{'en': 'Malvern, AR'},
'1440449':{'en': 'Cleveland, OH'},
'1501279':{'en': 'Searcy, AR'},
'1501278':{'en': 'Searcy, AR'},
'1418266':{'en': 'Quebec City, QC'},
'1518638':{'en': 'Argyle, NY'},
'1440442':{'en': 'Cleveland, OH'},
'1585924':{'en': 'Victor, NY'},
'1604876':{'en': 'Vancouver, BC'},
'1517364':{'en': 'Lansing, MI'},
'1604521':{'en': 'New Westminster, BC'},
'1616374':{'en': 'Lake Odessa, MI'},
'1517367':{'en': 'Lansing, MI'},
'1517369':{'en': 'Bronson, MI'},
'1603778':{'en': 'Exeter, NH'},
'1479451':{'en': 'Pea Ridge, AR'},
'1479452':{'en': 'Fort Smith, AR'},
'1432837':{'en': 'Alpine, TX'},
'1514982':{'en': 'Montreal, QC'},
'1514985':{'en': 'Montreal, QC'},
'1478329':{'en': 'Warner Robins, GA'},
'1514987':{'en': 'Montreal, QC'},
'1514989':{'en': 'Montreal, QC'},
'1602955':{'en': 'Phoenix, AZ'},
'1602484':{'en': 'Phoenix, AZ'},
'1602485':{'en': 'Phoenix, AZ'},
'1570622':{'en': 'Pottsville, PA'},
'1609441':{'en': 'Atlantic City, NJ'},
'1602952':{'en': 'Phoenix, AZ'},
'1570621':{'en': 'Pottsville, PA'},
'1513531':{'en': 'Cincinnati, OH'},
'1513530':{'en': 'Cincinnati, OH'},
'1513533':{'en': 'Cincinnati, OH'},
'1513539':{'en': 'Monroe, OH'},
'1616632':{'en': 'Grand Rapids, MI'},
'1616636':{'en': 'Sand Lake, MI'},
'1603578':{'en': 'Nashua, NH'},
'1450510':{'en': 'Vaudreuil-Dorion, QC'},
'1603577':{'en': 'Nashua, NH'},
'1616974':{'en': 'Grand Rapids, MI'},
'1418603':{'en': 'Levis, QC'},
'1562590':{'en': 'Long Beach, CA'},
'1438380':{'en': 'Montreal, QC'},
'1519582':{'en': 'Delhi, ON'},
'1412578':{'en': 'Pittsburgh, PA'},
'1519586':{'en': 'Port Rowan, ON'},
'1519587':{'en': 'Jarvis, ON'},
'1414908':{'en': 'Milwaukee, WI'},
'1519585':{'en': 'Kitchener, ON'},
'1412571':{'en': 'Pittsburgh, PA'},
'1416218':{'en': 'North York, ON'},
'1509891':{'en': 'Spokane Valley, WA'},
'1509892':{'en': 'Spokane Valley, WA'},
'1608625':{'en': 'La Farge, WI'},
'1416213':{'en': 'Etobicoke, ON'},
'1416214':{'en': 'Toronto, ON'},
'1416216':{'en': 'Toronto, ON'},
'1412683':{'en': 'Pittsburgh, PA'},
'1412682':{'en': 'Pittsburgh, PA'},
'1412681':{'en': 'Pittsburgh, PA'},
'1412687':{'en': 'Pittsburgh, PA'},
'1412688':{'en': 'Pittsburgh, PA'},
'1613248':{'en': 'Ottawa, ON'},
'1613249':{'en': 'Ottawa, ON'},
'1519766':{'en': 'Guelph, ON'},
'1519767':{'en': 'Guelph, ON'},
'1519765':{'en': 'Aylmer West, ON'},
'1519762':{'en': 'Dutton, ON'},
'1519763':{'en': 'Guelph, ON'},
'1604507':{'en': 'Surrey, BC'},
'1504585':{'en': 'New Orleans, LA'},
'1504586':{'en': 'New Orleans, LA'},
'1504581':{'en': 'New Orleans, LA'},
'1504582':{'en': 'New Orleans, LA'},
'1504588':{'en': 'New Orleans, LA'},
'1504589':{'en': 'New Orleans, LA'},
'1515279':{'en': 'Des Moines, IA'},
'1515271':{'en': 'Des Moines, IA'},
'1608442':{'en': 'Madison, WI'},
'1608443':{'en': 'Madison, WI'},
'1515274':{'en': 'Des Moines, IA'},
'1515275':{'en': 'Ogden, IA'},
'1515277':{'en': 'Des Moines, IA'},
'1507725':{'en': 'Caledonia, MN'},
'1507726':{'en': 'Lake Crystal, MN'},
'1507723':{'en': 'Springfield, MN'},
'1613531':{'en': 'Kingston, ON'},
'1508278':{'en': 'Uxbridge, MA'},
'1508279':{'en': 'Bridgewater, MA'},
'1505989':{'en': 'Santa Fe, NM'},
'1505988':{'en': 'Santa Fe, NM'},
'1505986':{'en': 'Santa Fe, NM'},
'1505984':{'en': 'Santa Fe, NM'},
'1505983':{'en': 'Santa Fe, NM'},
'1505982':{'en': 'Santa Fe, NM'},
'1505980':{'en': 'Albuquerque, NM'},
'1440949':{'en': 'Sheffield Lake, OH'},
'1440942':{'en': 'Willoughby, OH'},
'1440946':{'en': 'Willoughby, OH'},
'1608798':{'en': 'Cross Plains, WI'},
'1614461':{'en': 'Columbus, OH'},
'1415742':{'en': 'San Francisco, CA'},
'1585360':{'en': 'Rochester, NY'},
'1409924':{'en': 'Beaumont, TX'},
'1510986':{'en': 'Oakland, CA'},
'1510981':{'en': 'Berkeley, CA'},
'1415749':{'en': 'San Francisco, CA'},
'1585368':{'en': 'Rochester, NY'},
'1423698':{'en': 'Chattanooga, TN'},
'1541844':{'en': 'Eugene, OR'},
'1570893':{'en': 'Lock Haven, PA'},
'1507583':{'en': 'Blooming Prairie, MN'},
'1423697':{'en': 'Chattanooga, TN'},
'1573392':{'en': 'Eldon, MO'},
'1410861':{'en': 'Finksburg, MD'},
'1410860':{'en': 'Salisbury, MD'},
'1410863':{'en': 'Glen Burnie, MD'},
'1606487':{'en': 'Hazard, KY'},
'1410685':{'en': 'Baltimore, MD'},
'1423434':{'en': 'Johnson City, TN'},
'1423343':{'en': 'Kingsport, TN'},
'1609714':{'en': 'Medford, NJ'},
'1423346':{'en': 'Wartburg, TN'},
'1423431':{'en': 'Johnson City, TN'},
'1423344':{'en': 'Harrison, TN'},
'1423345':{'en': 'Surgoinsville, TN'},
'1562933':{'en': 'Long Beach, CA'},
'1423349':{'en': 'Kingsport, TN'},
'1423439':{'en': 'Johnson City, TN'},
'1541349':{'en': 'Eugene, OR'},
'1561912':{'en': 'Boca Raton, FL'},
'1561910':{'en': 'Boca Raton, FL'},
'1508856':{'en': 'Worcester, MA'},
'1502297':{'en': 'Louisville, KY'},
'1508854':{'en': 'Worcester, MA'},
'1508852':{'en': 'Worcester, MA'},
'1508853':{'en': 'Worcester, MA'},
'1502290':{'en': 'Louisville, KY'},
'1605362':{'en': 'Sioux Falls, SD'},
'1605360':{'en': 'Sioux Falls, SD'},
'1605361':{'en': 'Sioux Falls, SD'},
'1506458':{'en': 'Fredericton, NB'},
'1506459':{'en': 'Fredericton, NB'},
'1603435':{'en': 'Pittsfield, NH'},
'1506454':{'en': 'Fredericton, NB'},
'1506455':{'en': 'Fredericton, NB'},
'1605368':{'en': 'Tea, SD'},
'1506457':{'en': 'Fredericton, NB'},
'1506450':{'en': 'Fredericton, NB'},
'1506451':{'en': 'Fredericton, NB'},
'1506452':{'en': 'Fredericton, NB'},
'1506453':{'en': 'Fredericton, NB'},
'1480301':{'en': 'Scottsdale, AZ'},
'1435652':{'en': 'St. George, UT'},
'1435657':{'en': 'Heber City, UT'},
'1435656':{'en': 'St. George, UT'},
'1435655':{'en': 'Park City, UT'},
'1435654':{'en': 'Heber City, UT'},
'1606666':{'en': 'Jackson, KY'},
'1435658':{'en': 'Park City, UT'},
'1606663':{'en': 'Stanton, KY'},
'1516773':{'en': 'Great Neck, NY'},
'1609909':{'en': 'Mays Landing, NJ'},
'1417485':{'en': 'Ozark, MO'},
'1541343':{'en': 'Eugene, OR'},
'1502749':{'en': 'Louisville, KY'},
'1541342':{'en': 'Eugene, OR'},
'1502742':{'en': 'Louisville, KY'},
'1540710':{'en': 'Fredericksburg, VA'},
'1605341':{'en': 'Rapid City, SD'},
'1506672':{'en': 'Saint John, NB'},
'1417667':{'en': 'Nevada, MO'},
'1605347':{'en': 'Sturgis, SD'},
'1479846':{'en': 'Prairie Grove, AR'},
'1580286':{'en': 'Idabel, OK'},
'1505217':{'en': 'Albuquerque, NM'},
'1505216':{'en': 'Santa Fe, NM'},
'1517647':{'en': 'Portland, MI'},
'1510614':{'en': 'San Leandro, CA'},
'1517645':{'en': 'Potterville, MI'},
'1510346':{'en': 'San Leandro, CA'},
'1517641':{'en': 'Bath Township, MI'},
'1586939':{'en': 'Sterling Heights, MI'},
'1519973':{'en': 'Windsor, ON'},
'1519972':{'en': 'Windsor, ON'},
'1519971':{'en': 'Windsor, ON'},
'1519977':{'en': 'Windsor, ON'},
'1425347':{'en': 'Everett, WA'},
'1425348':{'en': 'Everett, WA'},
'1434295':{'en': 'Charlottesville, VA'},
'1434296':{'en': 'Charlottesville, VA'},
'1519978':{'en': 'Windsor, ON'},
'1434292':{'en': 'Blackstone, VA'},
'1434293':{'en': 'Charlottesville, VA'},
'1541746':{'en': 'Springfield, OR'},
'1602569':{'en': 'Phoenix, AZ'},
'1505379':{'en': 'Albuquerque, NM'},
'1541741':{'en': 'Springfield, OR'},
'1541743':{'en': 'Eugene, OR'},
'1503916':{'en': 'Portland, OR'},
'1616285':{'en': 'Grand Rapids, MI'},
'1571292':{'en': 'Manassas, VA'},
'1575377':{'en': 'Angel Fire, NM'},
'1575374':{'en': 'Clayton, NM'},
'1575373':{'en': 'Las Cruces, NM'},
'1610385':{'en': 'Douglassville, PA'},
'1575378':{'en': 'Ruidoso Downs, NM'},
'1540834':{'en': 'Fredericksburg, VA'},
'1413569':{'en': 'Southwick, MA'},
'1413568':{'en': 'Westfield, MA'},
'1413565':{'en': 'Longmeadow, MA'},
'1413567':{'en': 'Longmeadow, MA'},
'1413566':{'en': 'Hampden, MA'},
'1410566':{'en': 'Baltimore, MD'},
'1413562':{'en': 'Westfield, MA'},
'1519396':{'en': 'Kincardine, ON'},
'1519395':{'en': 'Ripley, ON'},
'1540837':{'en': 'Boyce, VA'},
'1519393':{'en': 'Sebringville, ON'},
'1519392':{'en': 'Teeswater, ON'},
'1412749':{'en': 'Sewickley, PA'},
'1415242':{'en': 'San Francisco, CA'},
'1415243':{'en': 'San Francisco, CA'},
'1415241':{'en': 'San Francisco, CA'},
'1412967':{'en': 'Pittsburgh, PA'},
'1412741':{'en': 'Sewickley, PA'},
'1514510':{'en': 'Montreal, QC'},
'1530477':{'en': 'Grass Valley, CA'},
'1530476':{'en': 'Arbuckle, CA'},
'1530474':{'en': 'Shingletown, CA'},
'1530473':{'en': 'Williams, CA'},
'1530470':{'en': 'Nevada City, CA'},
'1530478':{'en': 'Nevada City, CA'},
'1518372':{'en': 'Schenectady, NY'},
'1518373':{'en': 'Clifton Park, NY'},
'1518370':{'en': 'Schenectady, NY'},
'1518371':{'en': 'Clifton Park, NY'},
'1518377':{'en': 'Schenectady, NY'},
'1518374':{'en': 'Schenectady, NY'},
'1603749':{'en': 'Dover, NH'},
'1603747':{'en': 'Woodsville, NH'},
'1603744':{'en': 'Bristol, NH'},
'1603745':{'en': 'Lincoln, NH'},
'1603742':{'en': 'Dover, NH'},
'1603743':{'en': 'Dover, NH'},
'1603740':{'en': 'Dover, NH'},
'1603965':{'en': 'Derry, NH'},
'1604299':{'en': 'Burnaby, BC'},
'1512268':{'en': 'Kyle, TX'},
'1512918':{'en': 'Austin, TX'},
'1512916':{'en': 'Austin, TX'},
'1512261':{'en': 'Lakeway, TX'},
'1512266':{'en': 'Austin, TX'},
'1512264':{'en': 'Spicewood, TX'},
'1432520':{'en': 'Midland, TX'},
'1432522':{'en': 'Midland, TX'},
'1432523':{'en': 'Andrews, TX'},
'1432524':{'en': 'Andrews, TX'},
'1604298':{'en': 'Burnaby, BC'},
'1501455':{'en': 'Little Rock, AR'},
'1520547':{'en': 'Tucson, AZ'},
'1520544':{'en': 'Tucson, AZ'},
'1520545':{'en': 'Tucson, AZ'},
'1501450':{'en': 'Conway, AR'},
'1615259':{'en': 'Nashville, TN'},
'1615256':{'en': 'Nashville, TN'},
'1615255':{'en': 'Nashville, TN'},
'1410840':{'en': 'Westminster, MD'},
'1615252':{'en': 'Nashville, TN'},
'1615251':{'en': 'Nashville, TN'},
'1615250':{'en': 'Nashville, TN'},
'1509662':{'en': 'Wenatchee, WA'},
'1509663':{'en': 'Wenatchee, WA'},
'1509667':{'en': 'Wenatchee, WA'},
'1509664':{'en': 'Wenatchee, WA'},
'1509665':{'en': 'Wenatchee, WA'},
'1506866':{'en': 'Moncton, NB'},
'1573701':{'en': 'Farmington, MO'},
'1520722':{'en': 'Tucson, AZ'},
'1520723':{'en': 'Coolidge, AZ'},
'1515643':{'en': 'Des Moines, IA'},
'1412341':{'en': 'Pittsburgh, PA'},
'1608877':{'en': 'Stoughton, WI'},
'1419453':{'en': 'Ottoville, OH'},
'1412344':{'en': 'Pittsburgh, PA'},
'1414374':{'en': 'Milwaukee, WI'},
'1414371':{'en': 'Milwaukee, WI'},
'1561218':{'en': 'Boca Raton, FL'},
'1414372':{'en': 'Milwaukee, WI'},
'1512444':{'en': 'Austin, TX'},
'1419531':{'en': 'Toledo, OH'},
'1419532':{'en': 'Kalida, OH'},
'1415353':{'en': 'San Francisco, CA'},
'1419534':{'en': 'Toledo, OH'},
'1419535':{'en': 'Toledo, OH'},
'1419536':{'en': 'Toledo, OH'},
'1419537':{'en': 'Toledo, OH'},
'1512442':{'en': 'Austin, TX'},
'1415355':{'en': 'San Francisco, CA'},
'1503355':{'en': 'Rockaway Beach, OR'},
'1503357':{'en': 'Forest Grove, OR'},
'1606877':{'en': 'London, KY'},
'1512441':{'en': 'Austin, TX'},
'1503359':{'en': 'Forest Grove, OR'},
'1580889':{'en': 'Atoka, OK'},
'1507444':{'en': 'Owatonna, MN'},
'1480829':{'en': 'Tempe, AZ'},
'1507446':{'en': 'Owatonna, MN'},
'1580767':{'en': 'Ponca City, OK'},
'1610759':{'en': 'Nazareth, PA'},
'1610758':{'en': 'Bethlehem, PA'},
'1507442':{'en': 'Edgerton, MN'},
'1480821':{'en': 'Chandler, AZ'},
'1610756':{'en': 'Kempton, PA'},
'1610750':{'en': 'Reading, PA'},
'1480827':{'en': 'Mesa, AZ'},
'1434848':{'en': 'Lawrenceville, VA'},
'1580762':{'en': 'Ponca City, OK'},
'1613599':{'en': 'Kanata, ON'},
'1613226':{'en': 'Nepean, ON'},
'1434842':{'en': 'Fork Union, VA'},
'1434845':{'en': 'Lynchburg, VA'},
'1434847':{'en': 'Lynchburg, VA'},
'1434846':{'en': 'Lynchburg, VA'},
'1609882':{'en': 'Ewing Township, NJ'},
'1516349':{'en': 'Plainview, NY'},
'1417877':{'en': 'Springfield, MO'},
'1417876':{'en': 'El Dorado Spgs, MO'},
'1417875':{'en': 'Springfield, MO'},
'1609884':{'en': 'Cape May, NJ'},
'1541729':{'en': 'Eugene, OR'},
'1541728':{'en': 'Bend, OR'},
'1541726':{'en': 'Springfield, OR'},
'1508879':{'en': 'Framingham, MA'},
'1410476':{'en': 'Trappe, MD'},
'1503749':{'en': 'Aumsville, OR'},
'1410479':{'en': 'Denton, MD'},
'1606298':{'en': 'Inez, KY'},
'1418669':{'en': 'Alma, QC'},
'1418668':{'en': 'Alma, QC'},
'1418667':{'en': 'Quebec City, QC'},
'1418914':{'en': 'Quebec City, QC'},
'1418665':{'en': 'La Malbaie, QC'},
'1418662':{'en': 'Alma, QC'},
'1418661':{'en': 'Quebec City, QC'},
'1418660':{'en': 'Quebec City, QC'},
'1602889':{'en': 'Phoenix, AZ'},
'1570429':{'en': 'Saint Clair, PA'},
'1570398':{'en': 'Jersey Shore, PA'},
'1570424':{'en': 'Stroudsburg, PA'},
'1570427':{'en': 'Weatherly, PA'},
'1570420':{'en': 'Stroudsburg, PA'},
'1513737':{'en': 'Hamilton, OH'},
'1513735':{'en': 'Batavia, OH'},
'1513734':{'en': 'Bethel, OH'},
'1513733':{'en': 'Cincinnati, OH'},
'1513732':{'en': 'Batavia, OH'},
'1513731':{'en': 'Cincinnati, OH'},
'1440428':{'en': 'Madison, OH'},
'1501219':{'en': 'Little Rock, AR'},
'1518966':{'en': 'Greenville, NY'},
'1435462':{'en': 'Mount Pleasant, UT'},
'1501217':{'en': 'Little Rock, AR'},
'1518962':{'en': 'Westport, NY'},
'1510428':{'en': 'Oakland, CA'},
'1517349':{'en': 'Okemos, MI'},
'1517439':{'en': 'Hillsdale, MI'},
'1517437':{'en': 'Hillsdale, MI'},
'1517346':{'en': 'Lansing, MI'},
'1517347':{'en': 'Okemos, MI'},
'1570648':{'en': 'Shamokin, PA'},
'1513933':{'en': 'Lebanon, OH'},
'1570644':{'en': 'Shamokin, PA'},
'1513559':{'en': 'Cincinnati, OH'},
'1513558':{'en': 'Cincinnati, OH'},
'1603516':{'en': 'Dover, NH'},
'1540898':{'en': 'Fredericksburg, VA'},
'1540899':{'en': 'Fredericksburg, VA'},
'1513553':{'en': 'New Richmond, OH'},
'1480451':{'en': 'Scottsdale, AZ'},
'1540894':{'en': 'Mineral, VA'},
'1603518':{'en': 'Manchester, NH'},
'1513557':{'en': 'Cincinnati, OH'},
'1513887':{'en': 'Hamilton, OH'},
'1513554':{'en': 'Cincinnati, OH'},
'1602404':{'en': 'Phoenix, AZ'},
'1450793':{'en': 'Saint-Liboire, QC'},
'1450796':{'en': 'Saint-Hyacinthe, QC'},
'1501663':{'en': 'Little Rock, AR'},
'1450799':{'en': 'Saint-Hyacinthe, QC'},
'1501661':{'en': 'Little Rock, AR'},
'1501666':{'en': 'Little Rock, AR'},
'1501664':{'en': 'Little Rock, AR'},
'1434336':{'en': 'Emporia, VA'},
'1434332':{'en': 'Rustburg, VA'},
'1585637':{'en': 'Brockport, NY'},
'1415868':{'en': 'Bolinas, CA'},
'1603659':{'en': 'Newmarket, NH'},
'1519568':{'en': 'Kitchener, ON'},
'1519569':{'en': 'Kitchener, ON'},
'1602971':{'en': 'Phoenix, AZ'},
'1414961':{'en': 'Milwaukee, WI'},
'1414962':{'en': 'Milwaukee, WI'},
'1414963':{'en': 'Milwaukee, WI'},
'1414964':{'en': 'Milwaukee, WI'},
'1602978':{'en': 'Glendale, AZ'},
'1414967':{'en': 'Milwaukee, WI'},
'1416232':{'en': 'Etobicoke, ON'},
'1416233':{'en': 'Etobicoke, ON'},
'1416231':{'en': 'Etobicoke, ON'},
'1416236':{'en': 'Etobicoke, ON'},
'1416237':{'en': 'Etobicoke, ON'},
'1416234':{'en': 'Etobicoke, ON'},
'1616447':{'en': 'Grand Rapids, MI'},
'1416239':{'en': 'Etobicoke, ON'},
'1605539':{'en': 'Wessington Spgs, SD'},
'1504944':{'en': 'New Orleans, LA'},
'1418543':{'en': 'Chicoutimi, QC'},
'1509877':{'en': 'Wapato, WA'},
'1435632':{'en': 'St. George, UT'},
'1585968':{'en': 'Cuba, NY'},
'1612374':{'en': 'Minneapolis, MN'},
'1504940':{'en': 'New Orleans, LA'},
'1604569':{'en': 'Vancouver, BC'},
'1604568':{'en': 'Vancouver, BC'},
'1435634':{'en': 'St. George, UT'},
'1602604':{'en': 'Phoenix, AZ'},
'1602606':{'en': 'Phoenix, AZ'},
'1418544':{'en': 'La Baie, QC'},
'1616850':{'en': 'Grand Haven, MI'},
'1418545':{'en': 'Chicoutimi, QC'},
'1612370':{'en': 'Minneapolis, MN'},
'1608462':{'en': 'Elroy, WI'},
'1515256':{'en': 'Des Moines, IA'},
'1608467':{'en': 'Madison, WI'},
'1515255':{'en': 'Des Moines, IA'},
'1615871':{'en': 'Nashville, TN'},
'1517639':{'en': 'Quincy, MI'},
'1612706':{'en': 'Minneapolis, MN'},
'1612379':{'en': 'Minneapolis, MN'},
'1612378':{'en': 'Minneapolis, MN'},
'1416385':{'en': 'North York, ON'},
'1504658':{'en': 'New Orleans, LA'},
'1504656':{'en': 'Belle Chasse, LA'},
'1409948':{'en': 'Texas City, TX'},
'1585340':{'en': 'Rochester, NY'},
'1585343':{'en': 'Batavia, NY'},
'1585342':{'en': 'Rochester, NY'},
'1415765':{'en': 'San Francisco, CA'},
'1585344':{'en': 'Batavia, NY'},
'1585349':{'en': 'Spencerport, NY'},
'1614444':{'en': 'Columbus, OH'},
'1614447':{'en': 'Columbus, OH'},
'1409945':{'en': 'Texas City, TX'},
'1614443':{'en': 'Columbus, OH'},
'1614442':{'en': 'Columbus, OH'},
'1563532':{'en': 'Ossian, IA'},
'1518272':{'en': 'Troy, NY'},
'1614889':{'en': 'Dublin, OH'},
'1518271':{'en': 'Troy, NY'},
'1563538':{'en': 'Lansing, IA'},
'1563539':{'en': 'Monona, IA'},
'1562777':{'en': 'Santa Fe Springs, CA'},
'1540382':{'en': 'Christiansburg, VA'},
'1562951':{'en': 'Long Beach, CA'},
'1509764':{'en': 'Moses Lake, WA'},
'1615472':{'en': 'Franklin, TN'},
'1410803':{'en': 'Bel Air, MD'},
'1416955':{'en': 'Toronto, ON'},
'1609730':{'en': 'Pennington, NJ'},
'1540381':{'en': 'Christiansburg, VA'},
'1512707':{'en': 'Austin, TX'},
'1512708':{'en': 'Austin, TX'},
'1518274':{'en': 'Troy, NY'},
'1559798':{'en': 'Ivanhoe, CA'},
'1616458':{'en': 'Grand Rapids, MI'},
'1561972':{'en': 'Jupiter, FL'},
'1506472':{'en': 'Fredericton, NB'},
'1506473':{'en': 'Grand Falls, NB'},
'1616459':{'en': 'Grand Rapids, MI'},
'1508830':{'en': 'Plymouth, MA'},
'1508831':{'en': 'Worcester, MA'},
'1508832':{'en': 'Auburn, MA'},
'1508835':{'en': 'West Boylston, MA'},
'1508836':{'en': 'Westborough, MA'},
'1440964':{'en': 'Ashtabula, OH'},
'1440967':{'en': 'Vermilion, OH'},
'1605388':{'en': 'Rapid City, SD'},
'1440960':{'en': 'Lorain, OH'},
'1605384':{'en': 'Wagner, SD'},
'1530406':{'en': 'Woodland, CA'},
'1605387':{'en': 'Menno, SD'},
'1610255':{'en': 'Landenberg, PA'},
'1480368':{'en': 'Scottsdale, AZ'},
'1440639':{'en': 'Painesville, OH'},
'1435678':{'en': 'Blanding, UT'},
'1610252':{'en': 'Easton, PA'},
'1501397':{'en': 'Redfield, AR'},
'1435674':{'en': 'St. George, UT'},
'1435676':{'en': 'Panguitch, UT'},
'1480367':{'en': 'Scottsdale, AZ'},
'1435673':{'en': 'St. George, UT'},
'1440632':{'en': 'Middlefield, OH'},
'1419529':{'en': 'Mansfield, OH'},
'1417468':{'en': 'Marshfield, MO'},
'1417469':{'en': 'Willow Springs, MO'},
'1580444':{'en': 'Velma, OK'},
'1417466':{'en': 'Mount Vernon, MO'},
'1616452':{'en': 'Grand Rapids, MI'},
'1506652':{'en': 'Saint John, NB'},
'1506657':{'en': 'Saint John, NB'},
'1613695':{'en': 'Ottawa, ON'},
'1506658':{'en': 'Saint John, NB'},
'1613692':{'en': 'Manotick, ON'},
'1540778':{'en': 'Stanley, VA'},
'1612521':{'en': 'Minneapolis, MN'},
'1540772':{'en': 'Roanoke, VA'},
'1540777':{'en': 'Roanoke, VA'},
'1540776':{'en': 'Roanoke, VA'},
'1540775':{'en': 'King George, VA'},
'1540774':{'en': 'Roanoke, VA'},
'1425712':{'en': 'Lynnwood, WA'},
'1605835':{'en': 'Gregory, SD'},
'1516752':{'en': 'Farmingdale, NY'},
'1605964':{'en': 'Eagle Butte, SD'},
'1479824':{'en': 'Lincoln, AR'},
'1479795':{'en': 'Centerton, AR'},
'1515986':{'en': 'Grimes, IA'},
'1450370':{'en': 'Salaberry-de-Valleyfield, QC'},
'1515984':{'en': 'Polk City, IA'},
'1505232':{'en': 'Albuquerque, NM'},
'1505235':{'en': 'Albuquerque, NM'},
'1505237':{'en': 'Albuquerque, NM'},
'1505239':{'en': 'Albuquerque, NM'},
'1505238':{'en': 'Albuquerque, NM'},
'1503682':{'en': 'Wilsonville, OR'},
'1503681':{'en': 'Hillsboro, OR'},
'1517663':{'en': 'Eaton Rapids, MI'},
'1604261':{'en': 'Vancouver, BC'},
'1517669':{'en': 'DeWitt, MI'},
'1517668':{'en': 'DeWitt, MI'},
'1517887':{'en': 'Lansing, MI'},
'1517886':{'en': 'Lansing, MI'},
'1517882':{'en': 'Lansing, MI'},
'1570894':{'en': 'Tobyhanna, PA'},
'1570897':{'en': 'Mount Bethel, PA'},
'1425369':{'en': 'Issaquah, WA'},
'1505352':{'en': 'Albuquerque, NM'},
'1505350':{'en': 'Albuquerque, NM'},
'1541553':{'en': 'Warm Springs, OR'},
'1519954':{'en': 'Kitchener, ON'},
'1519951':{'en': 'London, ON'},
'1540872':{'en': 'Bumpass, VA'},
'1415974':{'en': 'San Francisco, CA'},
'1409379':{'en': 'Newton, TX'},
'1415970':{'en': 'San Francisco, CA'},
'1503972':{'en': 'Portland, OR'},
'1415979':{'en': 'San Francisco, CA'},
'1503977':{'en': 'Portland, OR'},
'1514282':{'en': 'Montreal, QC'},
'1514280':{'en': 'Montreal, QC'},
'1514281':{'en': 'Montreal, QC'},
'1514286':{'en': 'Montreal, QC'},
'1514287':{'en': 'Montreal, QC'},
'1514284':{'en': 'Montreal, QC'},
'1514285':{'en': 'Montreal, QC'},
'1575359':{'en': 'Portales, NM'},
'1514288':{'en': 'Montreal, QC'},
'1514289':{'en': 'Montreal, QC'},
'1513947':{'en': 'Cincinnati, OH'},
'1513941':{'en': 'Cincinnati, OH'},
'1513943':{'en': 'Cincinnati, OH'},
'1513948':{'en': 'Cincinnati, OH'},
'1432640':{'en': 'Odessa, TX'},
'1507831':{'en': 'Windom, MN'},
'1440392':{'en': 'Painesville, OH'},
'1603237':{'en': 'Colebrook, NH'},
'1603232':{'en': 'Manchester, NH'},
'1530459':{'en': 'Montague, CA'},
'1530458':{'en': 'Colusa, CA'},
'1541962':{'en': 'La Grande, OR'},
'1603239':{'en': 'Winchester, NH'},
'1509464':{'en': 'Spokane, WA'},
'1509465':{'en': 'Spokane, WA'},
'1509466':{'en': 'Spokane, WA'},
'1509467':{'en': 'Spokane, WA'},
'1509468':{'en': 'Spokane, WA'},
'1509469':{'en': 'Yakima, WA'},
'1518392':{'en': 'Chatham, NY'},
'1518393':{'en': 'Schenectady, NY'},
'1508481':{'en': 'Marlborough, MA'},
'1508480':{'en': 'Marlborough, MA'},
'1505827':{'en': 'Santa Fe, NM'},
'1505820':{'en': 'Santa Fe, NM'},
'1505821':{'en': 'Albuquerque, NM'},
'1508339':{'en': 'Mansfield, MA'},
'1505823':{'en': 'Albuquerque, NM'},
'1508337':{'en': 'Mansfield, MA'},
'1508336':{'en': 'Seekonk, MA'},
'1508334':{'en': 'Worcester, MA'},
'1505828':{'en': 'Albuquerque, NM'},
'1408954':{'en': 'San Jose, CA'},
'1408956':{'en': 'Milpitas, CA'},
'1615223':{'en': 'Smyrna, TN'},
'1615279':{'en': 'Nashville, TN'},
'1504488':{'en': 'New Orleans, LA'},
'1520529':{'en': 'Tucson, AZ'},
'1504486':{'en': 'New Orleans, LA'},
'1615274':{'en': 'Eagleville, TN'},
'1504483':{'en': 'New Orleans, LA'},
'1504482':{'en': 'New Orleans, LA'},
'1412235':{'en': 'Pittsburgh, PA'},
'1412232':{'en': 'Pittsburgh, PA'},
'1412233':{'en': 'Clairton, PA'},
'1412231':{'en': 'Pittsburgh, PA'},
'1509684':{'en': 'Colville, WA'},
'1509685':{'en': 'Colville, WA'},
'1509687':{'en': 'Manson, WA'},
'1509682':{'en': 'Chelan, WA'},
'1573293':{'en': 'Bernie, MO'},
'1573727':{'en': 'Poplar Bluff, MO'},
'1573722':{'en': 'Advance, MO'},
'1540368':{'en': 'Fredericksburg, VA'},
'1559307':{'en': 'Fresno, CA'},
'1419475':{'en': 'Toledo, OH'},
'1419474':{'en': 'Toledo, OH'},
'1540542':{'en': 'Winchester, VA'},
'1419476':{'en': 'Toledo, OH'},
'1419471':{'en': 'Toledo, OH'},
'1540545':{'en': 'Winchester, VA'},
'1419473':{'en': 'Toledo, OH'},
'1419472':{'en': 'Toledo, OH'},
'1540548':{'en': 'Fredericksburg, VA'},
'1419479':{'en': 'Toledo, OH'},
'1419478':{'en': 'Toledo, OH'},
'1520298':{'en': 'Tucson, AZ'},
'1520299':{'en': 'Tucson, AZ'},
'1520292':{'en': 'Tucson, AZ'},
'1520293':{'en': 'Tucson, AZ'},
'1520290':{'en': 'Tucson, AZ'},
'1520296':{'en': 'Tucson, AZ'},
'1520297':{'en': 'Tucson, AZ'},
'1520294':{'en': 'Tucson, AZ'},
'1520295':{'en': 'Tucson, AZ'},
'1585753':{'en': 'Rochester, NY'},
'1512930':{'en': 'Georgetown, TX'},
'1512931':{'en': 'Georgetown, TX'},
'1540428':{'en': 'Warrenton, VA'},
'1519267':{'en': 'Cambridge, ON'},
'1414393':{'en': 'Milwaukee, WI'},
'1605448':{'en': 'Britton, SD'},
'1419517':{'en': 'Sylvania, OH'},
'1480802':{'en': 'Chandler, AZ'},
'1413662':{'en': 'North Adams, MA'},
'1480807':{'en': 'Mesa, AZ'},
'1503378':{'en': 'Salem, OR'},
'1416291':{'en': 'Scarborough, ON'},
'1503375':{'en': 'Salem, OR'},
'1503370':{'en': 'Salem, OR'},
'1503371':{'en': 'Salem, OR'},
'1507467':{'en': 'Lanesboro, MN'},
'1540364':{'en': 'Marshall, VA'},
'1614586':{'en': 'Columbus, OH'},
'1413665':{'en': 'South Deerfield, MA'},
'1518644':{'en': 'Bolton Landing, NY'},
'1443849':{'en': 'Towson, MD'},
'1601355':{'en': 'Jackson, MS'},
'1418704':{'en': 'Quebec City, QC'},
'1610791':{'en': 'Allentown, PA'},
'1519264':{'en': 'Mount Brydges, ON'},
'1610793':{'en': 'West Chester, PA'},
'1610792':{'en': 'Royersford, PA'},
'1417859':{'en': 'Marshfield, MO'},
'1417858':{'en': 'Shell Knob, MO'},
'1607639':{'en': 'Afton, NY'},
'1541708':{'en': 'Ashland, OR'},
'1610797':{'en': 'Allentown, PA'},
'1530938':{'en': 'Weed, CA'},
'1604676':{'en': 'Vancouver, BC'},
'1530934':{'en': 'Willows, CA'},
'1423262':{'en': 'Johnson City, TN'},
'1541706':{'en': 'Bend, OR'},
'1601656':{'en': 'Philadelphia, MS'},
'1616988':{'en': 'Grand Rapids, MI'},
'1604850':{'en': 'Abbotsford, BC'},
'1503769':{'en': 'Stayton, OR'},
'1613925':{'en': 'Prescott, ON'},
'1601657':{'en': 'Liberty, MS'},
'1503764':{'en': 'Portland, OR'},
'1410496':{'en': 'Randallstown, MD'},
'1503761':{'en': 'Portland, OR'},
'1503760':{'en': 'Portland, OR'},
'1503763':{'en': 'Salem, OR'},
'1503762':{'en': 'Portland, OR'},
'1418649':{'en': 'Quebec City, QC'},
'1418648':{'en': 'Quebec City, QC'},
'1604855':{'en': 'Abbotsford, BC'},
'1510412':{'en': 'Richmond, CA'},
'1418641':{'en': 'Quebec City, QC'},
'1580':{'en': 'Oklahoma'},
'1581':{'en': 'Quebec'},
'1586':{'en': 'Michigan'},
'1587':{'en': 'Alberta'},
'1418647':{'en': 'Quebec City, QC'},
'1585':{'en': 'New York'},
'1434823':{'en': 'Crozet, VA'},
'1434822':{'en': 'Danville, VA'},
'1434821':{'en': 'Rustburg, VA'},
'1617236':{'en': 'Boston, MA'},
'1580581':{'en': 'Lawton, OK'},
'1419609':{'en': 'Sandusky, OH'},
'1580584':{'en': 'Broken Bow, OK'},
'1604859':{'en': 'Abbotsford, BC'},
'1435336':{'en': 'Coalville, UT'},
'1501941':{'en': 'Cabot, AR'},
'1479361':{'en': 'Springdale, AR'},
'1518943':{'en': 'Catskill, NY'},
'1518946':{'en': 'Wilmington, NY'},
'1513575':{'en': 'Milford, OH'},
'1513574':{'en': 'Cincinnati, OH'},
'1612333':{'en': 'Minneapolis, MN'},
'1513576':{'en': 'Milford, OH'},
'1530662':{'en': 'Woodland, CA'},
'1612337':{'en': 'Minneapolis, MN'},
'1530661':{'en': 'Woodland, CA'},
'1612339':{'en': 'Minneapolis, MN'},
'1612338':{'en': 'Minneapolis, MN'},
'1616364':{'en': 'Grand Rapids, MI'},
'1616365':{'en': 'Grand Rapids, MI'},
'1513579':{'en': 'Cincinnati, OH'},
'1616363':{'en': 'Grand Rapids, MI'},
'1530668':{'en': 'Woodland, CA'},
'1530669':{'en': 'Woodland, CA'},
'1518497':{'en': 'Chateaugay, NY'},
'1518494':{'en': 'Chestertown, NY'},
'1518499':{'en': 'Whitehall, NY'},
'1603536':{'en': 'Plymouth, NH'},
'1608374':{'en': 'Tomah, WI'},
'1602494':{'en': 'Phoenix, AZ'},
'1561637':{'en': 'Delray Beach, FL'},
'1502410':{'en': 'Louisville, KY'},
'1502412':{'en': 'Louisville, KY'},
'1561638':{'en': 'Delray Beach, FL'},
'1570409':{'en': 'Milford, PA'},
'1416431':{'en': 'Scarborough, ON'},
'1416438':{'en': 'Scarborough, ON'},
'1416439':{'en': 'Scarborough, ON'},
'1479587':{'en': 'Fayetteville, AR'},
'1540213':{'en': 'Staunton, VA'},
'1479582':{'en': 'Fayetteville, AR'},
'1434315':{'en': 'Farmville, VA'},
'1434316':{'en': 'Lynchburg, VA'},
'1412531':{'en': 'Pittsburgh, PA'},
'1615904':{'en': 'Murfreesboro, TN'},
'1570662':{'en': 'Mansfield, PA'},
'1602916':{'en': 'Phoenix, AZ'},
'1570668':{'en': 'Tamaqua, PA'},
'1518237':{'en': 'Cohoes, NY'},
'1518236':{'en': 'Mooers, NY'},
'1608662':{'en': 'Madison, WI'},
'1518234':{'en': 'Cobleskill, NY'},
'1607363':{'en': 'Downsville, NY'},
'1413625':{'en': 'Shelburne Falls, MA'},
'1413623':{'en': 'Becket, MA'},
'1419285':{'en': 'Put-in-Bay, OH'},
'1615837':{'en': 'Nashville, TN'},
'1519720':{'en': 'Brantford, ON'},
'1519727':{'en': 'Emeryville, ON'},
'1519725':{'en': 'Waterloo, ON'},
'1604544':{'en': 'New Westminster, BC'},
'1519728':{'en': 'Belle River, ON'},
'1604541':{'en': 'Surrey, BC'},
'1604543':{'en': 'Surrey, BC'},
'1510636':{'en': 'Oakland, CA'},
'1508363':{'en': 'Worcester, MA'},
'1602626':{'en': 'Phoenix, AZ'},
'1603883':{'en': 'Nashua, NH'},
'1608489':{'en': 'Hillsboro, WI'},
'1617342':{'en': 'Boston, MA'},
'1412391':{'en': 'Pittsburgh, PA'},
'1412394':{'en': 'Pittsburgh, PA'},
'1603224':{'en': 'Concord, NH'},
'1575835':{'en': 'Socorro, NM'},
'1478986':{'en': 'Gray, GA'},
'1478987':{'en': 'Perry, GA'},
'1478982':{'en': 'Millen, GA'},
'1478988':{'en': 'Perry, GA'},
'1514499':{'en': 'Montreal, QC'},
'1514498':{'en': 'Pointe-aux-Trembles, QC'},
'1409962':{'en': 'Groves, TX'},
'1409963':{'en': 'Groves, TX'},
'1615354':{'en': 'Nashville, TN'},
'1512891':{'en': 'Austin, TX'},
'1610863':{'en': 'Wind Gap, PA'},
'1541884':{'en': 'Klamath Falls, OR'},
'1512892':{'en': 'Austin, TX'},
'1423658':{'en': 'Whitwell, TN'},
'1512894':{'en': 'Dripping Springs, TX'},
'1541881':{'en': 'Ontario, OR'},
'1512899':{'en': 'Austin, TX'},
'1415701':{'en': 'San Francisco, CA'},
'1604814':{'en': 'Mission, BC'},
'1512542':{'en': 'Austin, TX'},
'1423652':{'en': 'Bristol, TN'},
'1541889':{'en': 'Ontario, OR'},
'1514721':{'en': 'Montreal, QC'},
'1514723':{'en': 'Montreal, QC'},
'1514722':{'en': 'Montreal, QC'},
'1514725':{'en': 'Montreal, QC'},
'1514727':{'en': 'Montreal, QC'},
'1514729':{'en': 'Montreal, QC'},
'1514728':{'en': 'Montreal, QC'},
'1610865':{'en': 'Bethlehem, PA'},
'1563556':{'en': 'Dubuque, IA'},
'1563557':{'en': 'Dubuque, IA'},
'1423478':{'en': 'Cleveland, TN'},
'1423479':{'en': 'Cleveland, TN'},
'1512763':{'en': 'Georgetown, TX'},
'1423472':{'en': 'Cleveland, TN'},
'1423473':{'en': 'Cleveland, TN'},
'1423475':{'en': 'Chattanooga, TN'},
'1423476':{'en': 'Cleveland, TN'},
'1423477':{'en': 'Gray, TN'},
'1601825':{'en': 'Brandon, MS'},
'1601824':{'en': 'Brandon, MS'},
'1601823':{'en': 'Brookhaven, MS'},
'1601394':{'en': 'Leakesville, MS'},
'1601829':{'en': 'Brandon, MS'},
'1561955':{'en': 'Boca Raton, FL'},
'1520887':{'en': 'Tucson, AZ'},
'1520886':{'en': 'Tucson, AZ'},
'1520885':{'en': 'Tucson, AZ'},
'1520884':{'en': 'Tucson, AZ'},
'1520883':{'en': 'Tucson, AZ'},
'1520882':{'en': 'Tucson, AZ'},
'1440989':{'en': 'Lorain, OH'},
'1440988':{'en': 'Amherst, OH'},
'1615514':{'en': 'Nashville, TN'},
'1615515':{'en': 'Nashville, TN'},
'1440985':{'en': 'Amherst, OH'},
'1440984':{'en': 'Amherst, OH'},
'1540286':{'en': 'Fredericksburg, VA'},
'1520889':{'en': 'Tucson, AZ'},
'1520888':{'en': 'Tucson, AZ'},
'1602943':{'en': 'Phoenix, AZ'},
'1417443':{'en': 'Highlandville, MO'},
'1610278':{'en': 'Norristown, PA'},
'1610279':{'en': 'Norristown, PA'},
'1435833':{'en': 'Tooele, UT'},
'1507328':{'en': 'Rochester, MN'},
'1614933':{'en': 'New Albany, OH'},
'1610275':{'en': 'Norristown, PA'},
'1610272':{'en': 'Norristown, PA'},
'1610273':{'en': 'Honey Brook, PA'},
'1417448':{'en': 'Nevada, MO'},
'1559449':{'en': 'Fresno, CA'},
'1559448':{'en': 'Fresno, CA'},
'1559443':{'en': 'Fresno, CA'},
'1559442':{'en': 'Fresno, CA'},
'1559441':{'en': 'Fresno, CA'},
'1559440':{'en': 'Fresno, CA'},
'1559447':{'en': 'Fresno, CA'},
'1559446':{'en': 'Fresno, CA'},
'1559445':{'en': 'Fresno, CA'},
'1540751':{'en': 'Purcellville, VA'},
'1540752':{'en': 'Fredericksburg, VA'},
'1410392':{'en': 'Elkton, MD'},
'1410827':{'en': 'Queenstown, MD'},
'1410820':{'en': 'Easton, MD'},
'1410823':{'en': 'Towson, MD'},
'1410822':{'en': 'Easton, MD'},
'1410398':{'en': 'Elkton, MD'},
'1417623':{'en': 'Joplin, MO'},
'1417626':{'en': 'Joplin, MO'},
'1417627':{'en': 'Joplin, MO'},
'1417624':{'en': 'Joplin, MO'},
'1417625':{'en': 'Joplin, MO'},
'1518356':{'en': 'Schenectady, NY'},
'1561404':{'en': 'Delray Beach, FL'},
'1518357':{'en': 'Schenectady, NY'},
'1425739':{'en': 'Kirkland, WA'},
'1605859':{'en': 'Philip, SD'},
'1505782':{'en': 'Zuni, NM'},
'1540249':{'en': 'Grottoes, VA'},
'1505786':{'en': 'Crownpoint, NM'},
'1605852':{'en': 'Highmore, SD'},
'1540248':{'en': 'Verona, VA'},
'1605854':{'en': 'De Smet, SD'},
'1605856':{'en': 'Mission, SD'},
'1480345':{'en': 'Tempe, AZ'},
'1480346':{'en': 'Scottsdale, AZ'},
'1516734':{'en': 'New Hyde Park, NY'},
'1480348':{'en': 'Scottsdale, AZ'},
'1617267':{'en': 'Boston, MA'},
'1580938':{'en': 'Shattuck, OK'},
'1580931':{'en': 'Durant, OK'},
'1580933':{'en': 'Valliant, OK'},
'1479770':{'en': 'Lowell, AR'},
'1541393':{'en': 'Eugene, OR'},
'1541390':{'en': 'Bend, OR'},
'1541396':{'en': 'Coquille, OR'},
'1413498':{'en': 'Northfield, MA'},
'1410536':{'en': 'Halethorpe, MD'},
'1410535':{'en': 'Prince Frederick, MD'},
'1410534':{'en': 'Baltimore, MD'},
'1410532':{'en': 'Baltimore, MD'},
'1505250':{'en': 'Albuquerque, NM'},
'1505256':{'en': 'Albuquerque, NM'},
'1410539':{'en': 'Baltimore, MD'},
'1505254':{'en': 'Albuquerque, NM'},
'1513389':{'en': 'Cincinnati, OH'},
'1443':{'en': 'Maryland'},
'1442':{'en': 'California'},
'1440':{'en': 'Ohio'},
'1513381':{'en': 'Cincinnati, OH'},
'1617261':{'en': 'Boston, MA'},
'1513385':{'en': 'Cincinnati, OH'},
'1505332':{'en': 'Albuquerque, NM'},
'1505334':{'en': 'Aztec, NM'},
'1570879':{'en': 'Hallstead, PA'},
'1505338':{'en': 'Albuquerque, NM'},
'1541574':{'en': 'Newport, OR'},
'1541575':{'en': 'John Day, OR'},
'1541572':{'en': 'Myrtle Point, OR'},
'1541573':{'en': 'Burns, OR'},
'1503954':{'en': 'Portland, OR'},
'1585393':{'en': 'Canandaigua, NY'},
'1418343':{'en': 'Saint-Bruno, QC'},
'1415956':{'en': 'San Francisco, CA'},
'1415957':{'en': 'San Francisco, CA'},
'1415954':{'en': 'San Francisco, CA'},
'1575628':{'en': 'Carlsbad, NM'},
'1410750':{'en': 'Ellicott City, MD'},
'1616791':{'en': 'Grand Rapids, MI'},
'1604806':{'en': 'Vancouver, BC'},
'1575623':{'en': 'Roswell, NM'},
'1575622':{'en': 'Roswell, NM'},
'1575625':{'en': 'Roswell, NM'},
'1575336':{'en': 'Alto, NM'},
'1575627':{'en': 'Roswell, NM'},
'1574223':{'en': 'Rochester, IN'},
'1610847':{'en': 'Ottsville, PA'},
'1513965':{'en': 'Milford, OH'},
'1513961':{'en': 'Cincinnati, OH'},
'1604488':{'en': 'Vancouver, BC'},
'1604483':{'en': 'Powell River, BC'},
'1604484':{'en': 'Vancouver, BC'},
'1604485':{'en': 'Powell River, BC'},
'1603253':{'en': 'Moultonborough, NH'},
'1530432':{'en': 'Penn Valley, CA'},
'1504310':{'en': 'New Orleans, LA'},
'1509448':{'en': 'Spokane, WA'},
'1509334':{'en': 'Pullman, WA'},
'1509443':{'en': 'Spokane, WA'},
'1509447':{'en': 'Newport, WA'},
'1509332':{'en': 'Pullman, WA'},
'1509649':{'en': 'Roslyn, WA'},
'1505804':{'en': 'Albuquerque, NM'},
'1412942':{'en': 'Pittsburgh, PA'},
'1580925':{'en': 'Konawa, OK'},
'1615217':{'en': 'Murfreesboro, TN'},
'1408978':{'en': 'San Jose, CA'},
'1408979':{'en': 'San Jose, CA'},
'1408977':{'en': 'San Jose, CA'},
'1415442':{'en': 'San Francisco, CA'},
'1408975':{'en': 'San Jose, CA'},
'1408972':{'en': 'San Jose, CA'},
'1408973':{'en': 'Cupertino, CA'},
'1408970':{'en': 'Santa Clara, CA'},
'1408971':{'en': 'San Jose, CA'},
'1501490':{'en': 'Little Rock, AR'},
'1435636':{'en': 'Price, UT'},
'1412255':{'en': 'Pittsburgh, PA'},
'1412257':{'en': 'Bridgeville, PA'},
'1573964':{'en': 'Lake Ozark, MO'},
'1573747':{'en': 'Farmington, MO'},
'1573748':{'en': 'New Madrid, MO'},
'1608835':{'en': 'Oregon, WI'},
'1603875':{'en': 'Alton, NH'},
'1540568':{'en': 'Harrisonburg, VA'},
'1508987':{'en': 'Oxford, MA'},
'1603870':{'en': 'Salem, NH'},
'1515352':{'en': 'Gowrie, IA'},
'1419499':{'en': 'Milan, OH'},
'1540562':{'en': 'Roanoke, VA'},
'1540563':{'en': 'Roanoke, VA'},
'1617394':{'en': 'Everett, MA'},
'1585265':{'en': 'Webster, NY'},
'1603878':{'en': 'New Ipswich, NH'},
'1608838':{'en': 'McFarland, WI'},
'1540564':{'en': 'Harrisonburg, VA'},
'1608348':{'en': 'Platteville, WI'},
'1540380':{'en': 'Salem, VA'},
'1604732':{'en': 'Vancouver, BC'},
'1604733':{'en': 'Vancouver, BC'},
'1604730':{'en': 'Vancouver, BC'},
'1604731':{'en': 'Vancouver, BC'},
'1604736':{'en': 'Vancouver, BC'},
'1604737':{'en': 'Vancouver, BC'},
'1604734':{'en': 'Vancouver, BC'},
'1507665':{'en': 'Le Sueur, MN'},
'1604738':{'en': 'Vancouver, BC'},
'1604739':{'en': 'Vancouver, BC'},
'1507662':{'en': 'Lakefield, MN'},
'1507663':{'en': 'Northfield, MN'},
'1601703':{'en': 'Meridian, MS'},
'1512360':{'en': 'Smithville, TX'},
'1608635':{'en': 'Poynette, WI'},
'1562690':{'en': 'La Habra, CA'},
'1415395':{'en': 'San Francisco, CA'},
'1562692':{'en': 'Whittier, CA'},
'1415397':{'en': 'San Francisco, CA'},
'1562694':{'en': 'La Habra, CA'},
'1415391':{'en': 'San Francisco, CA'},
'1415392':{'en': 'San Francisco, CA'},
'1415393':{'en': 'San Francisco, CA'},
'1562698':{'en': 'Whittier, CA'},
'1415398':{'en': 'San Francisco, CA'},
'1415399':{'en': 'San Francisco, CA'},
'1503316':{'en': 'Salem, OR'},
'1559322':{'en': 'Clovis, CA'},
'1559323':{'en': 'Clovis, CA'},
'1559320':{'en': 'Fresno, CA'},
'1559326':{'en': 'Clovis, CA'},
'1559324':{'en': 'Clovis, CA'},
'1559325':{'en': 'Clovis, CA'},
'1608630':{'en': 'Madison, WI'},
'1586790':{'en': 'Clinton Twp, MI'},
'1614457':{'en': 'Columbus, OH'},
'1443869':{'en': 'Baltimore, MD'},
'1574217':{'en': 'South Bend, IN'},
'1410706':{'en': 'Baltimore, MD'},
'1512374':{'en': 'Austin, TX'},
'1512376':{'en': 'Lockhart, TX'},
'1512377':{'en': 'Austin, TX'},
'1512370':{'en': 'Austin, TX'},
'1512371':{'en': 'Austin, TX'},
'1512372':{'en': 'Austin, TX'},
'1512373':{'en': 'Austin, TX'},
'1418724':{'en': 'Rimouski, QC'},
'1418725':{'en': 'Rimouski, QC'},
'1418722':{'en': 'Rimouski, QC'},
'1418723':{'en': 'Rimouski, QC'},
'1418721':{'en': 'Rimouski, QC'},
'1418623':{'en': 'Quebec City, QC'},
'1418622':{'en': 'Quebec City, QC'},
'1418621':{'en': 'Quebec City, QC'},
'1418627':{'en': 'Quebec City, QC'},
'1418626':{'en': 'Quebec City, QC'},
'1418625':{'en': 'Lac-Etchemin, QC'},
'1418624':{'en': 'Quebec City, QC'},
'1418629':{'en': 'Amqui, QC'},
'1418628':{'en': 'Quebec City, QC'},
'1580832':{'en': 'New Cordell, OK'},
'1610688':{'en': 'Wayne, PA'},
'1610391':{'en': 'Allentown, PA'},
'1518828':{'en': 'Hudson, NY'},
'1518827':{'en': 'Middleburgh, NY'},
'1518822':{'en': 'Hudson, NY'},
'1603942':{'en': 'Northwood, NH'},
'1613260':{'en': 'Ottawa, ON'},
'1506204':{'en': 'Moncton, NB'},
'1506755':{'en': 'Saint George, NB'},
'1603943':{'en': 'Nashua, NH'},
'1506753':{'en': 'Campbellton, NB'},
'1613267':{'en': 'Perth, ON'},
'1613269':{'en': 'Merrickville, ON'},
'1517381':{'en': 'Okemos, MI'},
'1506759':{'en': 'Campbellton, NB'},
'1513772':{'en': 'Cincinnati, OH'},
'1513771':{'en': 'Cincinnati, OH'},
'1513770':{'en': 'Mason, OH'},
'1513777':{'en': 'West Chester, OH'},
'1513779':{'en': 'West Chester, OH'},
'1561994':{'en': 'Boca Raton, FL'},
'1501961':{'en': 'Scott, AR'},
'1518926':{'en': 'Glens Falls, NY'},
'1615371':{'en': 'Brentwood, TN'},
'1604531':{'en': 'Surrey, BC'},
'1408741':{'en': 'Saratoga, CA'},
'1408745':{'en': 'Sunnyvale, CA'},
'1541766':{'en': 'Corvallis, OR'},
'1541765':{'en': 'Depoe Bay, OR'},
'1408746':{'en': 'Sunnyvale, CA'},
'1408749':{'en': 'Sunnyvale, CA'},
'1408748':{'en': 'Santa Clara, CA'},
'1541768':{'en': 'Corvallis, OR'},
'1530605':{'en': 'Redding, CA'},
'1512241':{'en': 'Austin, TX'},
'1612353':{'en': 'Minneapolis, MN'},
'1616301':{'en': 'Grand Rapids, MI'},
'1612354':{'en': 'Minneapolis, MN'},
'1609454':{'en': 'Princeton, NJ'},
'1602288':{'en': 'Phoenix, AZ'},
'1561615':{'en': 'West Palm Beach, FL'},
'1540967':{'en': 'Louisa, VA'},
'1561616':{'en': 'West Palm Beach, FL'},
'1604566':{'en': 'Vancouver, BC'},
'1419935':{'en': 'Willard, OH'},
'1570462':{'en': 'Shenandoah, PA'},
'1419931':{'en': 'Perrysburg, OH'},
'1419933':{'en': 'Willard, OH'},
'1510574':{'en': 'Fremont, CA'},
'1615374':{'en': 'Hartsville, TN'},
'1416412':{'en': 'Scarborough, ON'},
'1416413':{'en': 'Toronto, ON'},
'1413420':{'en': 'Holyoke, MA'},
'1616748':{'en': 'Zeeland, MI'},
'1602281':{'en': 'Phoenix, AZ'},
'1602283':{'en': 'Phoenix, AZ'},
'1519524':{'en': 'Goderich, ON'},
'1519527':{'en': 'Seaforth, ON'},
'1434372':{'en': 'Chase City, VA'},
'1434376':{'en': 'Brookneal, VA'},
'1434374':{'en': 'Clarksville, VA'},
'1602424':{'en': 'Phoenix, AZ'},
'1602426':{'en': 'Phoenix, AZ'},
'1514876':{'en': 'Montreal, QC'},
'1602393':{'en': 'Phoenix, AZ'},
'1509784':{'en': 'Entiat, WA'},
'1509787':{'en': 'Quincy, WA'},
'1509786':{'en': 'Prosser, WA'},
'1509837':{'en': 'Sunnyside, WA'},
'1509783':{'en': 'Kennewick, WA'},
'1509782':{'en': 'Cashmere, WA'},
'1518218':{'en': 'Albany, NY'},
'1509839':{'en': 'Sunnyside, WA'},
'1509838':{'en': 'Spokane, WA'},
'1413644':{'en': 'Great Barrington, MA'},
'1608647':{'en': 'Richland Center, WI'},
'1608452':{'en': 'Coon Valley, WI'},
'1615377':{'en': 'Brentwood, TN'},
'1519291':{'en': 'Listowel, ON'},
'1519294':{'en': 'Parkhill, ON'},
'1515597':{'en': 'Huxley, IA'},
'1610237':{'en': 'Darby, PA'},
'1610987':{'en': 'Oley, PA'},
'1415499':{'en': 'San Rafael, CA'},
'1604436':{'en': 'Burnaby, BC'},
'1415492':{'en': 'San Rafael, CA'},
'1415491':{'en': 'San Rafael, CA'},
'1415495':{'en': 'San Francisco, CA'},
'1615726':{'en': 'Nashville, TN'},
'1508788':{'en': 'Framingham, MA'},
'1508785':{'en': 'Dover, MA'},
'1519833':{'en': 'Erin, ON'},
'1585657':{'en': 'Bloomfield, NY'},
'1585654':{'en': 'Rochester, NY'},
'1415721':{'en': 'San Rafael, CA'},
'1409985':{'en': 'Port Arthur, TX'},
'1409982':{'en': 'Port Arthur, TX'},
'1409983':{'en': 'Port Arthur, TX'},
'1609514':{'en': 'Princeton, NJ'},
'1573883':{'en': 'Ste. Genevieve, MO'},
'1573882':{'en': 'Columbia, MO'},
'1514748':{'en': 'Saint-Laurent, QC'},
'1573887':{'en': 'Chaffee, MO'},
'1573886':{'en': 'Columbia, MO'},
'1573885':{'en': 'Cuba, MO'},
'1573884':{'en': 'Columbia, MO'},
'1573888':{'en': 'Kennett, MO'},
'1514747':{'en': 'Saint-Laurent, QC'},
'1514744':{'en': 'Saint-Laurent, QC'},
'1515294':{'en': 'Ames, IA'},
'1515295':{'en': 'Algona, IA'},
'1515292':{'en': 'Ames, IA'},
'1501771':{'en': 'N Little Rock, AR'},
'1501778':{'en': 'Benton, AR'},
'1512746':{'en': 'Jarrell, TX'},
'1609771':{'en': 'Ewing Township, NJ'},
'1610473':{'en': 'Boyertown, PA'},
'1502239':{'en': 'Louisville, KY'},
'1502231':{'en': 'Louisville, KY'},
'1530384':{'en': 'Los Molinos, CA'},
'1506432':{'en': 'Sussex, NB'},
'1506433':{'en': 'Sussex, NB'},
'1432333':{'en': 'Odessa, TX'},
'1432332':{'en': 'Odessa, TX'},
'1432335':{'en': 'Odessa, TX'},
'1432334':{'en': 'Odessa, TX'},
'1432337':{'en': 'Odessa, TX'},
'1432336':{'en': 'Fort Stockton, TX'},
'1520319':{'en': 'Tucson, AZ'},
'1450936':{'en': 'Laval, QC'},
'1520316':{'en': 'Casa Grande, AZ'},
'1417429':{'en': 'Springfield, MO'},
'1507346':{'en': 'Spring Valley, MN'},
'1507345':{'en': 'Mankato, MN'},
'1507344':{'en': 'Mankato, MN'},
'1414454':{'en': 'Milwaukee, WI'},
'1414455':{'en': 'Milwaukee, WI'},
'1414456':{'en': 'Milwaukee, WI'},
'1520387':{'en': 'Ajo, AZ'},
'1573223':{'en': 'Piedmont, MO'},
'1506693':{'en': 'Saint John, NB'},
'1573221':{'en': 'Hannibal, MO'},
'1414453':{'en': 'Milwaukee, WI'},
'1415563':{'en': 'San Francisco, CA'},
'1541683':{'en': 'Eugene, OR'},
'1541684':{'en': 'Eugene, OR'},
'1606423':{'en': 'Science Hill, KY'},
'1541686':{'en': 'Eugene, OR'},
'1440934':{'en': 'Avon, OH'},
'1561427':{'en': 'Jupiter, FL'},
'1561422':{'en': 'Riviera Beach, FL'},
'1612588':{'en': 'Minneapolis, MN'},
'1417395':{'en': 'Rich Hill, MO'},
'1562864':{'en': 'Norwalk, CA'},
'1605874':{'en': 'Clear Lake, SD'},
'1562863':{'en': 'Norwalk, CA'},
'1605878':{'en': 'Watertown, SD'},
'1603889':{'en': 'Nashua, NH'},
'1419729':{'en': 'Toledo, OH'},
'1614416':{'en': 'Columbus, OH'},
'1614539':{'en': 'Grove City, OH'},
'1419720':{'en': 'Toledo, OH'},
'1419725':{'en': 'Toledo, OH'},
'1419724':{'en': 'Toledo, OH'},
'1419727':{'en': 'Toledo, OH'},
'1419726':{'en': 'Toledo, OH'},
'1614777':{'en': 'Hilliard, OH'},
'1614775':{'en': 'New Albany, OH'},
'1516249':{'en': 'Farmingdale, NY'},
'1614771':{'en': 'Hilliard, OH'},
'1410571':{'en': 'Annapolis, MD'},
'1613746':{'en': 'Ottawa, ON'},
'1614538':{'en': 'Columbus, OH'},
'1613741':{'en': 'Ottawa, ON'},
'1517592':{'en': 'Brooklyn, MI'},
'1410576':{'en': 'Baltimore, MD'},
'1505275':{'en': 'Albuquerque, NM'},
'1505277':{'en': 'Albuquerque, NM'},
'1573785':{'en': 'Poplar Bluff, MO'},
'1505271':{'en': 'Albuquerque, NM'},
'1503485':{'en': 'Salem, OR'},
'1562868':{'en': 'Norwalk, CA'},
'1541372':{'en': 'Nyssa, OR'},
'1410517':{'en': 'Reisterstown, MD'},
'1408739':{'en': 'Sunnyvale, CA'},
'1410519':{'en': 'Severn, MD'},
'1423542':{'en': 'Elizabethton, TN'},
'1585242':{'en': 'Rochester, NY'},
'1469':{'en': 'Texas'},
'1614418':{'en': 'Columbus, OH'},
'1409813':{'en': 'Beaumont, TX'},
'1463':{'en': 'Indiana'},
'1559294':{'en': 'Fresno, CA'},
'1541752':{'en': 'Corvallis, OR'},
'1505319':{'en': 'Albuquerque, NM'},
'1541753':{'en': 'Corvallis, OR'},
'1505312':{'en': 'Albuquerque, NM'},
'1570853':{'en': 'Susquehanna, PA'},
'1505314':{'en': 'Albuquerque, NM'},
'1505315':{'en': 'Albuquerque, NM'},
'1541751':{'en': 'North Bend, OR'},
'1541756':{'en': 'North Bend, OR'},
'1608850':{'en': 'Waunakee, WI'},
'1541757':{'en': 'Corvallis, OR'},
'1479756':{'en': 'Springdale, AR'},
'1479754':{'en': 'Clarksville, AR'},
'1580774':{'en': 'Weatherford, OK'},
'1541754':{'en': 'Corvallis, OR'},
'1479750':{'en': 'Springdale, AR'},
'1479751':{'en': 'Springdale, AR'},
'1415931':{'en': 'San Francisco, CA'},
'1580477':{'en': 'Altus, OK'},
'1415933':{'en': 'San Francisco, CA'},
'1585461':{'en': 'Rochester, NY'},
'1570833':{'en': 'Meshoppen, PA'},
'1602896':{'en': 'Phoenix, AZ'},
'1575647':{'en': 'Las Cruces, NM'},
'1530284':{'en': 'Greenville, CA'},
'1570837':{'en': 'Middleburg, PA'},
'1609581':{'en': 'Trenton, NJ'},
'1440233':{'en': 'Lorain, OH'},
'1614470':{'en': 'Columbus, OH'},
'1440237':{'en': 'Cleveland, OH'},
'1440236':{'en': 'Columbia Station, OH'},
'1440238':{'en': 'Strongsville, OH'},
'1517625':{'en': 'Perry, MI'},
'1517627':{'en': 'Grand Ledge, MI'},
'1502595':{'en': 'Louisville, KY'},
'1517622':{'en': 'Grand Ledge, MI'},
'1517629':{'en': 'Albion, MI'},
'1432689':{'en': 'Midland, TX'},
'1440357':{'en': 'Painesville, OH'},
'1440354':{'en': 'Painesville, OH'},
'1440355':{'en': 'LaGrange, OH'},
'1440352':{'en': 'Painesville, OH'},
'1440353':{'en': 'North Ridgeville, OH'},
'1440350':{'en': 'Painesville, OH'},
'1432683':{'en': 'Midland, TX'},
'1432682':{'en': 'Midland, TX'},
'1432685':{'en': 'Midland, TX'},
'1432684':{'en': 'Midland, TX'},
'1432687':{'en': 'Midland, TX'},
'1432686':{'en': 'Midland, TX'},
'1603279':{'en': 'Meredith, NH'},
'1450346':{'en': 'Saint-Jean-sur-Richelieu, QC'},
'1450347':{'en': 'Saint-Jean-sur-Richelieu, QC'},
'1450348':{'en': 'Saint-Jean-sur-Richelieu, QC'},
'1450349':{'en': 'Saint-Jean-sur-Richelieu, QC'},
'1603271':{'en': 'Concord, NH'},
'1515993':{'en': 'Adel, IA'},
'1505869':{'en': 'Bosque Farms, NM'},
'1505861':{'en': 'Belen, NM'},
'1505863':{'en': 'Gallup, NM'},
'1505864':{'en': 'Belen, NM'},
'1505865':{'en': 'Los Lunas, NM'},
'1505866':{'en': 'Los Lunas, NM'},
'1505867':{'en': 'Bernalillo, NM'},
'1408918':{'en': 'San Jose, CA'},
'1608586':{'en': 'Oxford, WI'},
'1416609':{'en': 'Scarborough, ON'},
'1608582':{'en': 'Galesville, WI'},
'1416604':{'en': 'Toronto, ON'},
'1416603':{'en': 'Toronto, ON'},
'1608588':{'en': 'Spring Green, WI'},
'1416601':{'en': 'Toronto, ON'},
'1519887':{'en': 'Brussels, ON'},
'1519886':{'en': 'Waterloo, ON'},
'1415558':{'en': 'San Francisco, CA'},
'1412279':{'en': 'Carnegie, PA'},
'1519883':{'en': 'Waterloo, ON'},
'1425271':{'en': 'Renton, WA'},
'1519881':{'en': 'Walkerton, ON'},
'1519880':{'en': 'Waterloo, ON'},
'1415552':{'en': 'San Francisco, CA'},
'1415553':{'en': 'San Francisco, CA'},
'1415550':{'en': 'San Francisco, CA'},
'1415551':{'en': 'San Francisco, CA'},
'1412276':{'en': 'Carnegie, PA'},
'1415554':{'en': 'San Francisco, CA'},
'1519888':{'en': 'Waterloo, ON'},
'1573769':{'en': 'Palmyra, MO'},
'1573760':{'en': 'Farmington, MO'},
'1573761':{'en': 'Jefferson City, MO'},
'1414604':{'en': 'Milwaukee, WI'},
'1414607':{'en': 'Milwaukee, WI'},
'1573765':{'en': 'Richland, MO'},
'1608361':{'en': 'Beloit, WI'},
'1608363':{'en': 'Beloit, WI'},
'1608362':{'en': 'Beloit, WI'},
'1520784':{'en': 'Tucson, AZ'},
'1608364':{'en': 'Beloit, WI'},
'1603856':{'en': 'Concord, NH'},
'1507646':{'en': 'Northfield, MN'},
'1507647':{'en': 'Winthrop, MN'},
'1507644':{'en': 'Redwood Falls, MN'},
'1507645':{'en': 'Northfield, MN'},
'1507642':{'en': 'Madelia, MN'},
'1585798':{'en': 'Medina, NY'},
'1508370':{'en': 'Framingham, MA'},
'1508376':{'en': 'Millis, MA'},
'1512973':{'en': 'Austin, TX'},
'1508379':{'en': 'Swansea, MA'},
'1508378':{'en': 'East Bridgewater, MA'},
'1512974':{'en': 'Austin, TX'},
'1423892':{'en': 'Chattanooga, TN'},
'1504734':{'en': 'New Orleans, LA'},
'1504733':{'en': 'New Orleans, LA'},
'1615494':{'en': 'Murfreesboro, TN'},
'1615499':{'en': 'Nashville, TN'},
'1615942':{'en': 'Nashville, TN'},
'1503331':{'en': 'Portland, OR'},
'1503335':{'en': 'Portland, OR'},
'1503338':{'en': 'Astoria, OR'},
'1423725':{'en': 'Hampton, TN'},
'1507426':{'en': 'Fairfax, MN'},
'1507427':{'en': 'Mountain Lake, MN'},
'1412858':{'en': 'Monroeville, PA'},
'1418296':{'en': 'Baie-Comeau, QC'},
'1614545':{'en': 'Columbus, OH'},
'1412854':{'en': 'Bethel Park, PA'},
'1585218':{'en': 'Pittsford, NY'},
'1423728':{'en': 'Cleveland, TN'},
'1559877':{'en': 'North Fork, CA'},
'1606564':{'en': 'Maysville, KY'},
'1559875':{'en': 'Sanger, CA'},
'1409736':{'en': 'Port Arthur, TX'},
'1410727':{'en': 'Baltimore, MD'},
'1505489':{'en': 'Albuquerque, NM'},
'1410723':{'en': 'Ocean City, MD'},
'1505480':{'en': 'Albuquerque, NM'},
'1410728':{'en': 'Baltimore, MD'},
'1410729':{'en': 'Millersville, MD'},
'1580759':{'en': 'Stratford, OK'},
'1574231':{'en': 'South Bend, IN'},
'1574233':{'en': 'South Bend, IN'},
'1412882':{'en': 'Pittsburgh, PA'},
'1574235':{'en': 'South Bend, IN'},
'1574234':{'en': 'South Bend, IN'},
'1574237':{'en': 'South Bend, IN'},
'1508997':{'en': 'New Bedford, MA'},
'1508995':{'en': 'New Bedford, MA'},
'1508993':{'en': 'New Bedford, MA'},
'1508992':{'en': 'New Bedford, MA'},
'1508991':{'en': 'New Bedford, MA'},
'1508990':{'en': 'New Bedford, MA'},
'1512355':{'en': 'Bertram, TX'},
'1512352':{'en': 'Taylor, TX'},
'1512353':{'en': 'San Marcos, TX'},
'1508999':{'en': 'New Bedford, MA'},
'1512351':{'en': 'Austin, TX'},
'1601722':{'en': 'Seminary, MS'},
'1561852':{'en': 'Boca Raton, FL'},
'1601729':{'en': 'Soso, MS'},
'1480730':{'en': 'Tempe, AZ'},
'1480732':{'en': 'Chandler, AZ'},
'1480733':{'en': 'Mesa, AZ'},
'1484895':{'en': 'Bethlehem, PA'},
'1480736':{'en': 'Tempe, AZ'},
'1418602':{'en': 'Chicoutimi, QC'},
'1608245':{'en': 'Madison, WI'},
'1605374':{'en': 'Lemmon, SD'},
'1580544':{'en': 'Boise City, OK'},
'1607962':{'en': 'Corning, NY'},
'1518842':{'en': 'Amsterdam, NY'},
'1518843':{'en': 'Amsterdam, NY'},
'1518846':{'en': 'Chazy, NY'},
'1506773':{'en': 'Nelson-Miramichi, NB'},
'1601321':{'en': 'Jackson, MS'},
'1506776':{'en': 'Neguac, NB'},
'1506778':{'en': 'Nelson-Miramichi, NB'},
'1613241':{'en': 'Ottawa, ON'},
'1613530':{'en': 'Kingston, ON'},
'1613247':{'en': 'Ottawa, ON'},
'1613244':{'en': 'Ottawa, ON'},
'1513759':{'en': 'West Chester, OH'},
'1513755':{'en': 'West Chester, OH'},
'1513754':{'en': 'Mason, OH'},
'1516504':{'en': 'Great Neck, NY'},
'1513751':{'en': 'Cincinnati, OH'},
'1513752':{'en': 'Cincinnati, OH'},
'1602870':{'en': 'Phoenix, AZ'},
'1501907':{'en': 'Little Rock, AR'},
'1610779':{'en': 'Reading, PA'},
'1517458':{'en': 'Morenci, MI'},
'1517456':{'en': 'Clinton, MI'},
'1408729':{'en': 'San Jose, CA'},
'1541749':{'en': 'Bend, OR'},
'1408723':{'en': 'San Jose, CA'},
'1541744':{'en': 'Springfield, OR'},
'1541747':{'en': 'Springfield, OR'},
'1408720':{'en': 'Sunnyvale, CA'},
'1408727':{'en': 'Santa Clara, CA'},
'1408725':{'en': 'Cupertino, CA'},
'1585421':{'en': 'Fairport, NY'},
'1530628':{'en': 'Hayfork, CA'},
'1530629':{'en': 'Willow Creek, CA'},
'1540839':{'en': 'Hot Springs, VA'},
'1480443':{'en': 'Scottsdale, AZ'},
'1530622':{'en': 'Placerville, CA'},
'1530623':{'en': 'Weaverville, CA'},
'1530620':{'en': 'Somerset, CA'},
'1530621':{'en': 'Placerville, CA'},
'1530626':{'en': 'Placerville, CA'},
'1540832':{'en': 'Gordonsville, VA'},
'1530625':{'en': 'Hoopa, CA'},
'1502451':{'en': 'Louisville, KY'},
'1502452':{'en': 'Louisville, KY'},
'1502454':{'en': 'Louisville, KY'},
'1502456':{'en': 'Louisville, KY'},
'1502458':{'en': 'Louisville, KY'},
'1502459':{'en': 'Louisville, KY'},
'1606674':{'en': 'Owingsville, KY'},
'1607562':{'en': 'Big Flats, NY'},
'1561672':{'en': 'Boca Raton, FL'},
'1515382':{'en': 'Nevada, IA'},
'1434685':{'en': 'Danville, VA'},
'1606679':{'en': 'Somerset, KY'},
'1570339':{'en': 'Mount Carmel, PA'},
'1570443':{'en': 'White Haven, PA'},
'1570331':{'en': 'Kingston, PA'},
'1603664':{'en': 'Barrington, NH'},
'1607564':{'en': 'Newfield, NY'},
'1603888':{'en': 'Nashua, NH'},
'1607565':{'en': 'Waverly, NY'},
'1603669':{'en': 'Manchester, NH'},
'1434352':{'en': 'Appomattox, VA'},
'1510596':{'en': 'Emeryville, CA'},
'1510226':{'en': 'Fremont, CA'},
'1414988':{'en': 'Milwaukee, WI'},
'1602406':{'en': 'Phoenix, AZ'},
'1478414':{'en': 'Milledgeville, GA'},
'1607569':{'en': 'Hammondsport, NY'},
'1425462':{'en': 'Bellevue, WA'},
'1505400':{'en': 'Albuquerque, NM'},
'1425467':{'en': 'Bellevue, WA'},
'1612375':{'en': 'Minneapolis, MN'},
'1514908':{'en': 'Montreal, QC'},
'1612377':{'en': 'Minneapolis, MN'},
'1612371':{'en': 'Minneapolis, MN'},
'1503852':{'en': 'Carlton, OR'},
'1514903':{'en': 'Montreal, QC'},
'1514905':{'en': 'Montreal, QC'},
'1514904':{'en': 'Montreal, QC'},
'1503859':{'en': 'Lyons, OR'},
'1514906':{'en': 'Montreal, QC'},
'1502366':{'en': 'Louisville, KY'},
'1518279':{'en': 'Troy, NY'},
'1518273':{'en': 'Troy, NY'},
'1509766':{'en': 'Moses Lake, WA'},
'1509765':{'en': 'Moses Lake, WA'},
'1518270':{'en': 'Troy, NY'},
'1607324':{'en': 'Hornell, NY'},
'1509762':{'en': 'Moses Lake, WA'},
'1509760':{'en': 'Moses Lake, WA'},
'1508923':{'en': 'Middleborough, MA'},
'1602667':{'en': 'Phoenix, AZ'},
'1602535':{'en': 'Phoenix, AZ'},
'1616863':{'en': 'Rockford, MI'},
'1585494':{'en': 'Bergen, NY'},
'1585492':{'en': 'Arcade, NY'},
'1616866':{'en': 'Rockford, MI'},
'1441295':{'en': 'Hamilton'},
'1502368':{'en': 'Louisville, KY'},
'1503540':{'en': 'Salem, OR'},
'1585429':{'en': 'Rochester, NY'},
'1416290':{'en': 'Scarborough, ON'},
'1413663':{'en': 'North Adams, MA'},
'1416292':{'en': 'Scarborough, ON'},
'1416293':{'en': 'Scarborough, ON'},
'1413667':{'en': 'Huntington, MA'},
'1413664':{'en': 'North Adams, MA'},
'1416297':{'en': 'Scarborough, ON'},
'1416298':{'en': 'Scarborough, ON'},
'1416299':{'en': 'Scarborough, ON'},
'1614824':{'en': 'Columbus, OH'},
'1503543':{'en': 'Scappoose, OR'},
'1423610':{'en': 'Johnson City, TN'},
'1512502':{'en': 'Austin, TX'},
'1423613':{'en': 'Newport, TN'},
'1423614':{'en': 'Cleveland, TN'},
'1512506':{'en': 'Austin, TX'},
'1512505':{'en': 'Austin, TX'},
'1604854':{'en': 'Abbotsford, BC'},
'1512509':{'en': 'Round Rock, TX'},
'1604858':{'en': 'Chilliwack, BC'},
'1604678':{'en': 'Vancouver, BC'},
'1514761':{'en': 'Verdun, QC'},
'1605673':{'en': 'Custer, SD'},
'1450623':{'en': 'Saint-Eustache, QC'},
'1501758':{'en': 'N Little Rock, AR'},
'1509775':{'en': 'Republic, WA'},
'1501753':{'en': 'N Little Rock, AR'},
'1615460':{'en': 'Nashville, TN'},
'1502212':{'en': 'Louisville, KY'},
'1423928':{'en': 'Johnson City, TN'},
'1423929':{'en': 'Johnson City, TN'},
'1423926':{'en': 'Johnson City, TN'},
'1423921':{'en': 'Rogersville, TN'},
'1414290':{'en': 'Milwaukee, WI'},
'1414291':{'en': 'Milwaukee, WI'},
'1414297':{'en': 'Milwaukee, WI'},
'1414294':{'en': 'Milwaukee, WI'},
'1414298':{'en': 'Milwaukee, WI'},
'1419354':{'en': 'Bowling Green, OH'},
'1419355':{'en': 'Fremont, OH'},
'1614891':{'en': 'Westerville, OH'},
'1419352':{'en': 'Bowling Green, OH'},
'1419353':{'en': 'Bowling Green, OH'},
'1530367':{'en': 'Foresthill, CA'},
'1530365':{'en': 'Anderson, CA'},
'1419358':{'en': 'Bluffton, OH'},
'1559486':{'en': 'Fresno, CA'},
'1559485':{'en': 'Fresno, CA'},
'1573204':{'en': 'Jackson, MO'},
'1414479':{'en': 'Milwaukee, WI'},
'1414476':{'en': 'Milwaukee, WI'},
'1414475':{'en': 'Milwaukee, WI'},
'1616892':{'en': 'Allendale Charter Township, MI'},
'1606408':{'en': 'Ashland, KY'},
'1603898':{'en': 'Salem, NH'},
'1541550':{'en': 'Bend, OR'},
'1561447':{'en': 'Boca Raton, FL'},
'1601579':{'en': 'Hattiesburg, MS'},
'1419747':{'en': 'Mansfield, OH'},
'1586806':{'en': 'Warren, MI'},
'1605892':{'en': 'Belle Fourche, SD'},
'1502632':{'en': 'Louisville, KY'},
'1507364':{'en': 'Montgomery, MN'},
'1610983':{'en': 'Phoenixville, PA'},
'1559935':{'en': 'Coalinga, CA'},
'1507362':{'en': 'Waterville, MN'},
'1610988':{'en': 'Reading, PA'},
'1480380':{'en': 'Mesa, AZ'},
'1517203':{'en': 'East Lansing, MI'},
'1613761':{'en': 'Ottawa, ON'},
'1541357':{'en': 'Eugene, OR'},
'1541354':{'en': 'Hood River, OR'},
'1541352':{'en': 'Mount Hood Parkdale, OR'},
'1613764':{'en': 'Casselman, ON'},
'1613766':{'en': 'Kingston, ON'},
'1541359':{'en': 'Eugene, OR'},
'1541688':{'en': 'Eugene, OR'},
'1541689':{'en': 'Eugene, OR'},
'1505299':{'en': 'Albuquerque, NM'},
'1505298':{'en': 'Albuquerque, NM'},
'1505296':{'en': 'Albuquerque, NM'},
'1541682':{'en': 'Eugene, OR'},
'1505294':{'en': 'Albuquerque, NM'},
'1505293':{'en': 'Albuquerque, NM'},
'1505292':{'en': 'Albuquerque, NM'},
'1505291':{'en': 'Albuquerque, NM'},
'1541687':{'en': 'Eugene, OR'},
'1562867':{'en': 'Bellflower, CA'},
'1562866':{'en': 'Bellflower, CA'},
'1410579':{'en': 'Elkridge, MD'},
'1410578':{'en': 'Baltimore, MD'},
'1503628':{'en': 'Hillsboro, OR'},
'1562862':{'en': 'Downey, CA'},
'1562861':{'en': 'Downey, CA'},
'1410573':{'en': 'Annapolis, MD'},
'1503625':{'en': 'Sherwood, OR'},
'1503626':{'en': 'Beaverton, OR'},
'1503621':{'en': 'Portland, OR'},
'1562869':{'en': 'Downey, CA'},
'1503623':{'en': 'Dallas, OR'},
'1409':{'en': 'Texas'},
'1603267':{'en': 'Belmont, NH'},
'1570785':{'en': 'Forest City, PA'},
'1570784':{'en': 'Bloomsburg, PA'},
'1541536':{'en': 'La Pine, OR'},
'1570836':{'en': 'Tunkhannock, PA'},
'1503990':{'en': 'Salem, OR'},
'1435743':{'en': 'Fillmore, UT'},
'1540':{'en': 'Virginia'},
'1541':{'en': 'Oregon'},
'1516997':{'en': 'Westbury, NY'},
'1609898':{'en': 'Cape May, NJ'},
'1573372':{'en': 'Gravois Mills, MO'},
'1479736':{'en': 'Gentry, AR'},
'1479738':{'en': 'Huntsville, AR'},
'1609893':{'en': 'Browns Mills, NJ'},
'1609894':{'en': 'Pemberton, NJ'},
'1609895':{'en': 'Lawrenceville, NJ'},
'1609896':{'en': 'Lawrenceville, NJ'},
'1514223':{'en': 'Montreal, QC'},
'1514227':{'en': 'Montreal, QC'},
'1418688':{'en': 'Quebec City, QC'},
'1513922':{'en': 'Cincinnati, OH'},
'1513923':{'en': 'Cincinnati, OH'},
'1513921':{'en': 'Cincinnati, OH'},
'1513251':{'en': 'Cincinnati, OH'},
'1573378':{'en': 'Versailles, MO'},
'1440259':{'en': 'Perry, OH'},
'1586582':{'en': 'Warren, MI'},
'1440257':{'en': 'Mentor, OH'},
'1440255':{'en': 'Mentor, OH'},
'1502868':{'en': 'Georgetown, KY'},
'1502863':{'en': 'Georgetown, KY'},
'1510690':{'en': 'Hayward, CA'},
'1502867':{'en': 'Georgetown, KY'},
'1616464':{'en': 'Grand Rapids, MI'},
'1514598':{'en': 'Montreal, QC'},
'1514593':{'en': 'Montreal, QC'},
'1514596':{'en': 'Montreal, QC'},
'1514595':{'en': 'Lasalle, QC'},
'1440331':{'en': 'Cleveland, OH'},
'1440333':{'en': 'Cleveland, OH'},
'1440338':{'en': 'Novelty, OH'},
'1615688':{'en': 'Lafayette, TN'},
'1423272':{'en': 'Rogersville, TN'},
'1509374':{'en': 'Kennewick, WA'},
'1509375':{'en': 'Richland, WA'},
'1450361':{'en': 'Granby, QC'},
'1530342':{'en': 'Chico, CA'},
'1408937':{'en': 'San Jose, CA'},
'1408934':{'en': 'Milpitas, CA'},
'1408935':{'en': 'Milpitas, CA'},
'1607796':{'en': 'Horseheads, NY'},
'1519948':{'en': 'Windsor, ON'},
'1607795':{'en': 'Horseheads, NY'},
'1416332':{'en': 'Scarborough, ON'},
'1416621':{'en': 'Etobicoke, ON'},
'1416620':{'en': 'Etobicoke, ON'},
'1608565':{'en': 'Necedah, WI'},
'1416622':{'en': 'Etobicoke, ON'},
'1608562':{'en': 'New Lisbon, WI'},
'1416335':{'en': 'Scarborough, ON'},
'1416626':{'en': 'Etobicoke, ON'},
'1575437':{'en': 'Alamogordo, NM'},
'1604448':{'en': 'Richmond, BC'},
'1425258':{'en': 'Everett, WA'},
'1425259':{'en': 'Everett, WA'},
'1604444':{'en': 'Burnaby, BC'},
'1425257':{'en': 'Everett, WA'},
'1425255':{'en': 'Renton, WA'},
'1425252':{'en': 'Everett, WA'},
'1563383':{'en': 'Davenport, IA'},
'1563382':{'en': 'Decorah, IA'},
'1563928':{'en': 'Edgewood, IA'},
'1563386':{'en': 'Davenport, IA'},
'1563388':{'en': 'Davenport, IA'},
'1563927':{'en': 'Manchester, IA'},
'1605796':{'en': 'Woonsocket, SD'},
'1603838':{'en': 'Lisbon, NH'},
'1540890':{'en': 'Vinton, VA'},
'1409886':{'en': 'Orange, TX'},
'1509590':{'en': 'Spokane, WA'},
'1409883':{'en': 'Orange, TX'},
'1409882':{'en': 'Orange, TX'},
'1607863':{'en': 'Cincinnatus, NY'},
'1612672':{'en': 'Minneapolis, MN'},
'1608301':{'en': 'Madison, WI'},
'1603835':{'en': 'Alstead, NH'},
'1603836':{'en': 'Manchester, NH'},
'1603837':{'en': 'Whitefield, NH'},
'1562529':{'en': 'Paramount, CA'},
'1507625':{'en': 'Mankato, MN'},
'1507629':{'en': 'Tracy, MN'},
'1505842':{'en': 'Albuquerque, NM'},
'1505843':{'en': 'Albuquerque, NM'},
'1505841':{'en': 'Albuquerque, NM'},
'1508359':{'en': 'Medfield, MA'},
'1508358':{'en': 'Wayland, MA'},
'1508429':{'en': 'Holliston, MA'},
'1508427':{'en': 'Brockton, MA'},
'1505848':{'en': 'Albuquerque, NM'},
'1580726':{'en': 'Hobart, OK'},
'1508422':{'en': 'Milford, MA'},
'1508421':{'en': 'Worcester, MA'},
'1563659':{'en': 'DeWitt, IA'},
'1504712':{'en': 'Kenner, LA'},
'1563652':{'en': 'Maquoketa, IA'},
'1615962':{'en': 'Murfreesboro, TN'},
'1614566':{'en': 'Columbus, OH'},
'1510841':{'en': 'Berkeley, CA'},
'1510842':{'en': 'Oakland, CA'},
'1510843':{'en': 'Berkeley, CA'},
'1510845':{'en': 'Berkeley, CA'},
'1510848':{'en': 'Berkeley, CA'},
'1510849':{'en': 'Berkeley, CA'},
'1607642':{'en': 'Newark Valley, NY'},
'1412835':{'en': 'Bethel Park, PA'},
'1410740':{'en': 'Columbia, MD'},
'1410741':{'en': 'Lothian, MD'},
'1410742':{'en': 'Salisbury, MD'},
'1410744':{'en': 'Catonsville, MD'},
'1410745':{'en': 'St. Michaels, MD'},
'1410962':{'en': 'Baltimore, MD'},
'1410747':{'en': 'Catonsville, MD'},
'1410749':{'en': 'Salisbury, MD'},
'1574259':{'en': 'Mishawaka, IN'},
'1574258':{'en': 'Mishawaka, IN'},
'1410968':{'en': 'Crisfield, MD'},
'1418763':{'en': 'Sainte-Anne-des-Monts, QC'},
'1418766':{'en': 'Port-Cartier, QC'},
'1423559':{'en': 'Cleveland, TN'},
'1512338':{'en': 'Austin, TX'},
'1512339':{'en': 'Austin, TX'},
'1512330':{'en': 'Austin, TX'},
'1512331':{'en': 'Austin, TX'},
'1512332':{'en': 'Bastrop, TX'},
'1512334':{'en': 'Austin, TX'},
'1512335':{'en': 'Austin, TX'},
'1601964':{'en': 'New Augusta, MS'},
'1601965':{'en': 'Jackson, MS'},
'1601743':{'en': 'De Kalb, MS'},
'1601960':{'en': 'Jackson, MS'},
'1601961':{'en': 'Jackson, MS'},
'1506577':{'en': 'Cap-Pele, NB'},
'1506576':{'en': 'Cocagne, NB'},
'1601968':{'en': 'Jackson, MS'},
'1601969':{'en': 'Jackson, MS'},
'1606218':{'en': 'Pikeville, KY'},
'1518862':{'en': 'Albany, NY'},
'1518863':{'en': 'Northville, NY'},
'1580564':{'en': 'Kingston, OK'},
'1518861':{'en': 'Altamont, NY'},
'1604660':{'en': 'Vancouver, BC'},
'1518869':{'en': 'Albany, NY'},
'1580569':{'en': 'Snyder, OK'},
'1425822':{'en': 'Kirkland, WA'},
'1604846':{'en': 'Chilliwack, BC'},
'1609567':{'en': 'Hammonton, NJ'},
'1540477':{'en': 'Mount Jackson, VA'},
'1615612':{'en': 'Madison, TN'},
'1614840':{'en': 'Columbus, OH'},
'1540473':{'en': 'Fincastle, VA'},
'1540479':{'en': 'Fredericksburg, VA'},
'1501296':{'en': 'Little Rock, AR'},
'1516522':{'en': 'Uniondale, NY'},
'1613961':{'en': 'Belleville, ON'},
'1604669':{'en': 'Vancouver, BC'},
'1609278':{'en': 'Trenton, NJ'},
'1580699':{'en': 'Lawton, OK'},
'1425899':{'en': 'Kirkland, WA'},
'1609279':{'en': 'Princeton, NJ'},
'1419684':{'en': 'Castalia, OH'},
'1419683':{'en': 'Crestline, OH'},
'1530993':{'en': 'Loyalton, CA'},
'1418888':{'en': 'St-Agapit, QC'},
'1418881':{'en': 'St-Apollinaire, QC'},
'1418885':{'en': 'St-Anselme, QC'},
'1561655':{'en': 'West Palm Beach, FL'},
'1502479':{'en': 'Louisville, KY'},
'1561650':{'en': 'West Palm Beach, FL'},
'1561653':{'en': 'West Palm Beach, FL'},
'1502473':{'en': 'Louisville, KY'},
'1561659':{'en': 'West Palm Beach, FL'},
'1502477':{'en': 'Taylorsville, KY'},
'1614481':{'en': 'Columbus, OH'},
'1570628':{'en': 'Pottsville, PA'},
'1603826':{'en': 'Charlestown, NH'},
'1602954':{'en': 'Phoenix, AZ'},
'1443755':{'en': 'Hanover, MD'},
'1607865':{'en': 'Walton, NY'},
'1614485':{'en': 'Columbus, OH'},
'1602956':{'en': 'Phoenix, AZ'},
'1443759':{'en': 'Baltimore, MD'},
'1510204':{'en': 'Berkeley, CA'},
'1602957':{'en': 'Phoenix, AZ'},
'1518783':{'en': 'Latham, NY'},
'1518782':{'en': 'Latham, NY'},
'1614338':{'en': 'Columbus, OH'},
'1518786':{'en': 'Latham, NY'},
'1518785':{'en': 'Latham, NY'},
'1614337':{'en': 'Columbus, OH'},
'1425401':{'en': 'Bellevue, WA'},
'1614488':{'en': 'Columbus, OH'},
'1604576':{'en': 'Surrey, BC'},
'1602953':{'en': 'Phoenix, AZ'},
'1478471':{'en': 'Macon, GA'},
'1478472':{'en': 'Montezuma, GA'},
'1478474':{'en': 'Macon, GA'},
'1478475':{'en': 'Macon, GA'},
'1478476':{'en': 'Macon, GA'},
'1478477':{'en': 'Macon, GA'},
'1602468':{'en': 'Phoenix, AZ'},
'1503873':{'en': 'Silverton, OR'},
'1507529':{'en': 'Rochester, MN'},
'1616878':{'en': 'Byron Center, MI'},
'1616877':{'en': 'Wayland, MI'},
'1616874':{'en': 'Rockford, MI'},
'1616696':{'en': 'Cedar Springs, MI'},
'1509299':{'en': 'Medical Lake, WA'},
'1612789':{'en': 'Minneapolis, MN'},
'1509293':{'en': 'Wenatchee, WA'},
'1509292':{'en': 'Elk, WA'},
'1509290':{'en': 'Spokane, WA'},
'1509744':{'en': 'Spokane, WA'},
'1509747':{'en': 'Spokane, WA'},
'1519780':{'en': 'Guelph, ON'},
'1519782':{'en': 'Port Stanley, ON'},
'1519786':{'en': 'Forest, ON'},
'1519787':{'en': 'Fergus, ON'},
'1602687':{'en': 'Phoenix, AZ'},
'1602682':{'en': 'Phoenix, AZ'},
'1617354':{'en': 'Cambridge, MA'},
'1413467':{'en': 'Granby, MA'},
'1571379':{'en': 'Manassas, VA'},
'1505847':{'en': 'Mountainair, NM'},
'1412481':{'en': 'Pittsburgh, PA'},
'1617357':{'en': 'Boston, MA'},
'1415459':{'en': 'San Rafael, CA'},
'1412338':{'en': 'Pittsburgh, PA'},
'1415457':{'en': 'San Rafael, CA'},
'1415456':{'en': 'San Rafael, CA'},
'1415455':{'en': 'San Rafael, CA'},
'1415454':{'en': 'San Rafael, CA'},
'1415453':{'en': 'San Rafael, CA'},
'1415452':{'en': 'San Francisco, CA'},
'1415451':{'en': 'San Rafael, CA'},
'1412330':{'en': 'Pittsburgh, PA'},
'1478296':{'en': 'Dublin, GA'},
'1612821':{'en': 'Minneapolis, MN'},
'1612823':{'en': 'Minneapolis, MN'},
'1612822':{'en': 'Minneapolis, MN'},
'1612825':{'en': 'Minneapolis, MN'},
'1612824':{'en': 'Minneapolis, MN'},
'1612827':{'en': 'Minneapolis, MN'},
'1518525':{'en': 'Albany, NY'},
'1518523':{'en': 'Lake Placid, NY'},
'1607655':{'en': 'Windsor, NY'},
'1603487':{'en': 'New Boston, NH'},
'1413684':{'en': 'Dalton, MA'},
'1607659':{'en': 'Candor, NY'},
'1603335':{'en': 'Rochester, NH'},
'1603332':{'en': 'Rochester, NH'},
'1518529':{'en': 'Moira, NY'},
'1603330':{'en': 'Rochester, NH'},
'1423638':{'en': 'Greeneville, TN'},
'1423639':{'en': 'Greeneville, TN'},
'1604879':{'en': 'Vancouver, BC'},
'1512837':{'en': 'Austin, TX'},
'1512836':{'en': 'Austin, TX'},
'1512527':{'en': 'Austin, TX'},
'1512834':{'en': 'Austin, TX'},
'1512833':{'en': 'Austin, TX'},
'1512832':{'en': 'Austin, TX'},
'1423634':{'en': 'Chattanooga, TN'},
'1604872':{'en': 'Vancouver, BC'},
'1514789':{'en': 'Montreal, QC'},
'1514788':{'en': 'Montreal, QC'},
'1508643':{'en': 'North Attleborough, MA'},
'1504524':{'en': 'New Orleans, LA'},
'1504525':{'en': 'New Orleans, LA'},
'1504522':{'en': 'New Orleans, LA'},
'1504523':{'en': 'New Orleans, LA'},
'1509933':{'en': 'Ellensburg, WA'},
'1530209':{'en': 'Redding, CA'},
'1504528':{'en': 'New Orleans, LA'},
'1504529':{'en': 'New Orleans, LA'},
'1502271':{'en': 'Louisville, KY'},
'1508650':{'en': 'Natick, MA'},
'1508651':{'en': 'Natick, MA'},
'1508653':{'en': 'Natick, MA'},
'1423942':{'en': 'Jasper, TN'},
'1559713':{'en': 'Visalia, CA'},
'1601883':{'en': 'Vicksburg, MS'},
'1414278':{'en': 'Milwaukee, WI'},
'1601885':{'en': 'Utica, MS'},
'1414276':{'en': 'Milwaukee, WI'},
'1414277':{'en': 'Milwaukee, WI'},
'1414270':{'en': 'Milwaukee, WI'},
'1414271':{'en': 'Milwaukee, WI'},
'1414272':{'en': 'Milwaukee, WI'},
'1414273':{'en': 'Milwaukee, WI'},
'1608795':{'en': 'Mazomanie, WI'},
'1608796':{'en': 'La Crosse, WI'},
'1608791':{'en': 'La Crosse, WI'},
'1540261':{'en': 'Buena Vista, VA'},
'1530343':{'en': 'Chico, CA'},
'1419375':{'en': 'Fort Recovery, OH'},
'1530345':{'en': 'Chico, CA'},
'1530344':{'en': 'Placerville, CA'},
'1530347':{'en': 'Cottonwood, CA'},
'1530346':{'en': 'Colfax, CA'},
'1508892':{'en': 'Leicester, MA'},
'1409772':{'en': 'Galveston, TX'},
'1573592':{'en': 'Fulton, MO'},
'1573594':{'en': 'Vandalia, MO'},
'1573265':{'en': 'St. James, MO'},
'1573264':{'en': 'Scott City, MO'},
'1503274':{'en': 'Portland, OR'},
'1410885':{'en': 'Chesapeake City, MD'},
'1410884':{'en': 'Columbia, MD'},
'1410889':{'en': 'Baltimore, MD'},
'1515432':{'en': 'Boone, IA'},
'1515433':{'en': 'Boone, IA'},
'1503278':{'en': 'Portland, OR'},
'1423496':{'en': 'Copperhill, TN'},
'1610431':{'en': 'West Chester, PA'},
'1610432':{'en': 'Allentown, PA'},
'1423495':{'en': 'Chattanooga, TN'},
'1610434':{'en': 'Allentown, PA'},
'1423493':{'en': 'Chattanooga, TN'},
'1423490':{'en': 'Chattanooga, TN'},
'1610437':{'en': 'Allentown, PA'},
'1610438':{'en': 'Easton, PA'},
'1610439':{'en': 'Allentown, PA'},
'1423499':{'en': 'Chattanooga, TN'},
'1506384':{'en': 'Moncton, NB'},
'1608787':{'en': 'La Crosse, WI'},
'1601225':{'en': 'Gloster, MS'},
'1506382':{'en': 'Moncton, NB'},
'1506383':{'en': 'Moncton, NB'},
'1506388':{'en': 'Moncton, NB'},
'1506389':{'en': 'Moncton, NB'},
'1608784':{'en': 'La Crosse, WI'},
'1505727':{'en': 'Albuquerque, NM'},
'1505726':{'en': 'Gallup, NM'},
'1505724':{'en': 'Albuquerque, NM'},
'1505722':{'en': 'Gallup, NM'},
'1505720':{'en': 'Albuquerque, NM'},
'1443438':{'en': 'Baltimore, MD'},
'1443923':{'en': 'Baltimore, MD'},
'1614228':{'en': 'Columbus, OH'},
'1507389':{'en': 'Mankato, MN'},
'1507388':{'en': 'Mankato, MN'},
'1507387':{'en': 'Mankato, MN'},
'1507386':{'en': 'Mankato, MN'},
'1507385':{'en': 'Mankato, MN'},
'1614222':{'en': 'Columbus, OH'},
'1614225':{'en': 'Columbus, OH'},
'1614224':{'en': 'Columbus, OH'},
'1614227':{'en': 'Columbus, OH'},
'1541330':{'en': 'Bend, OR'},
'1541332':{'en': 'Port Orford, OR'},
'1530832':{'en': 'Portola, CA'},
'1541336':{'en': 'Toledo, OR'},
'1541338':{'en': 'Eugene, OR'},
'1410554':{'en': 'Baltimore, MD'},
'1410225':{'en': 'Baltimore, MD'},
'1410224':{'en': 'Annapolis, MD'},
'1410550':{'en': 'Baltimore, MD'},
'1410553':{'en': 'Glen Burnie, MD'},
'1410552':{'en': 'Sykesville, MD'},
'1410558':{'en': 'Baltimore, MD'},
'1410228':{'en': 'Cambridge, MD'},
'1423':{'en': 'Tennessee'},
'1425':{'en': 'Washington State'},
'1424':{'en': 'California'},
'1417682':{'en': 'Lamar, MO'},
'1417683':{'en': 'Ava, MO'},
'1605842':{'en': 'Winner, SD'},
'1570819':{'en': 'Wilkes-Barre, PA'},
'1480502':{'en': 'Scottsdale, AZ'},
'1505342':{'en': 'Albuquerque, NM'},
'1504899':{'en': 'New Orleans, LA'},
'1504896':{'en': 'New Orleans, LA'},
'1504897':{'en': 'New Orleans, LA'},
'1504894':{'en': 'New Orleans, LA'},
'1504895':{'en': 'New Orleans, LA'},
'1435725':{'en': 'Roosevelt, UT'},
'1504891':{'en': 'New Orleans, LA'},
'1580229':{'en': 'Healdton, OK'},
'1580228':{'en': 'Waurika, OK'},
'1617424':{'en': 'Boston, MA'},
'1617422':{'en': 'Boston, MA'},
'1617423':{'en': 'Boston, MA'},
'1617421':{'en': 'Boston, MA'},
'1479246':{'en': 'Rogers, AR'},
'1580225':{'en': 'Elk City, OK'},
'1517552':{'en': 'Howell, MI'},
'1479242':{'en': 'Fort Smith, AR'},
'1479715':{'en': 'Bentonville, AR'},
'1410964':{'en': 'Columbia, MD'},
'1415351':{'en': 'San Francisco, CA'},
'1574252':{'en': 'Mishawaka, IN'},
'1440275':{'en': 'Austinburg, OH'},
'1440277':{'en': 'Lorain, OH'},
'1574257':{'en': 'Mishawaka, IN'},
'1513272':{'en': 'Cincinnati, OH'},
'1513271':{'en': 'Cincinnati, OH'},
'1574255':{'en': 'Mishawaka, IN'},
'1519583':{'en': 'Port Dover, ON'},
'1574254':{'en': 'Mishawaka, IN'},
'1585328':{'en': 'Rochester, NY'},
'1519584':{'en': 'Kitchener, ON'},
'1450836':{'en': 'Berthierville, QC'},
'1414906':{'en': 'Milwaukee, WI'},
'1450834':{'en': 'Rawdon, QC'},
'1450835':{'en': 'St-Gabriel-de-Brandon, QC'},
'1450833':{'en': 'St-Michel-des-Saints, QC'},
'1450831':{'en': 'Sainte-Julienne, QC'},
'1440312':{'en': 'Cleveland, OH'},
'1509353':{'en': 'Spokane, WA'},
'1423553':{'en': 'Chattanooga, TN'},
'1601442':{'en': 'Natchez, MS'},
'1418338':{'en': 'Thetford Mines, QC'},
'1604466':{'en': 'Maple Ridge, BC'},
'1604467':{'en': 'Maple Ridge, BC'},
'1604462':{'en': 'Maple Ridge, BC'},
'1585865':{'en': 'Rochester, NY'},
'1604461':{'en': 'Port Moody, BC'},
'1604469':{'en': 'Port Moody, BC'},
'1478625':{'en': 'Louisville, GA'},
'1418335':{'en': 'Thetford Mines, QC'},
'1519332':{'en': 'Sarnia, ON'},
'1519335':{'en': 'Gorrie, ON'},
'1478628':{'en': 'Gordon, GA'},
'1519337':{'en': 'Sarnia, ON'},
'1519336':{'en': 'Sarnia, ON'},
'1608325':{'en': 'Monroe, WI'},
'1607844':{'en': 'Dryden, NY'},
'1607847':{'en': 'New Berlin, NY'},
'1585544':{'en': 'Rochester, NY'},
'1608897':{'en': 'Brodhead, WI'},
'1607843':{'en': 'Oxford, NY'},
'1515332':{'en': 'Humboldt, IA'},
'1607849':{'en': 'Marathon, NY'},
'1608328':{'en': 'Monroe, WI'},
'1409866':{'en': 'Beaumont, TX'},
'1418332':{'en': 'Thetford Mines, QC'},
'1409861':{'en': 'Beaumont, TX'},
'1409860':{'en': 'Beaumont, TX'},
'1604792':{'en': 'Chilliwack, BC'},
'1604793':{'en': 'Chilliwack, BC'},
'1604794':{'en': 'Chilliwack, BC'},
'1604795':{'en': 'Chilliwack, BC'},
'1604796':{'en': 'Agassiz, BC'},
'1508405':{'en': 'Framingham, MA'},
'1504779':{'en': 'Metairie, LA'},
'1415664':{'en': 'San Francisco, CA'},
'1423794':{'en': 'Johnson City, TN'},
'1415666':{'en': 'San Francisco, CA'},
'1510869':{'en': 'Oakland, CA'},
'1423790':{'en': 'Cleveland, TN'},
'1601445':{'en': 'Natchez, MS'},
'1480883':{'en': 'Chandler, AZ'},
'1415668':{'en': 'San Francisco, CA'},
'1423798':{'en': 'Greeneville, TN'},
'1510864':{'en': 'Alameda, CA'},
'1510865':{'en': 'Alameda, CA'},
'1605425':{'en': 'Salem, SD'},
'1559386':{'en': 'Avenal, CA'},
'1605223':{'en': 'Fort Pierre, SD'},
'1605426':{'en': 'Ipswich, SD'},
'1414649':{'en': 'Milwaukee, WI'},
'1605226':{'en': 'Aberdeen, SD'},
'1605225':{'en': 'Aberdeen, SD'},
'1605224':{'en': 'Pierre, SD'},
'1414645':{'en': 'Milwaukee, WI'},
'1414647':{'en': 'Milwaukee, WI'},
'1414643':{'en': 'Milwaukee, WI'},
'1410768':{'en': 'Glen Burnie, MD'},
'1410763':{'en': 'Easton, MD'},
'1410760':{'en': 'Glen Burnie, MD'},
'1410761':{'en': 'Glen Burnie, MD'},
'1410766':{'en': 'Glen Burnie, MD'},
'1410767':{'en': 'Baltimore, MD'},
'1410764':{'en': 'Baltimore, MD'},
'1574272':{'en': 'South Bend, IN'},
'1512312':{'en': 'Buda, TX'},
'1423570':{'en': 'Dayton, TN'},
'1512310':{'en': 'Round Rock, TX'},
'1601749':{'en': 'Picayune, MS'},
'1423578':{'en': 'Kingsport, TN'},
'1418780':{'en': 'Quebec City, QC'},
'1418781':{'en': 'Quebec City, QC'},
'1418782':{'en': u('Perc\u00e9, QC')},
'1615331':{'en': 'Nashville, TN'},
'1561819':{'en': 'Delray Beach, FL'},
'1502394':{'en': 'Louisville, KY'},
'1615907':{'en': 'Murfreesboro, TN'},
'1601948':{'en': 'Jackson, MS'},
'1601949':{'en': 'Jackson, MS'},
'1601947':{'en': 'Lucedale, MS'},
'1601944':{'en': 'Jackson, MS'},
'1601766':{'en': 'Lucedale, MS'},
'1585325':{'en': 'Rochester, NY'},
'1601765':{'en': 'Collins, MS'},
'1610377':{'en': 'Lehighton, PA'},
'1610376':{'en': 'Reading, PA'},
'1610375':{'en': 'Reading, PA'},
'1585948':{'en': 'Oakfield, NY'},
'1610373':{'en': 'Reading, PA'},
'1610372':{'en': 'Reading, PA'},
'1610371':{'en': 'Reading, PA'},
'1610370':{'en': 'Reading, PA'},
'1606237':{'en': 'South Williamson, KY'},
'1610378':{'en': 'Reading, PA'},
'1518884':{'en': 'Ballston Spa, NY'},
'1518885':{'en': 'Ballston Spa, NY'},
'1559528':{'en': 'Orosi, CA'},
'1518882':{'en': 'Galway, NY'},
'1518883':{'en': 'Broadalbin, NY'},
'1506735':{'en': 'Edmundston, NB'},
'1615333':{'en': 'Nashville, TN'},
'1506737':{'en': 'Edmundston, NB'},
'1506739':{'en': 'Edmundston, NB'},
'1607231':{'en': 'Binghamton, NY'},
'1540459':{'en': 'Woodstock, VA'},
'1540450':{'en': 'Winchester, VA'},
'1417239':{'en': 'Branson, MO'},
'1604501':{'en': 'Surrey, BC'},
'1417235':{'en': 'Monett, MO'},
'1417236':{'en': 'Monett, MO'},
'1604502':{'en': 'Surrey, BC'},
'1604504':{'en': 'Abbotsford, BC'},
'1608994':{'en': 'Bloomington, WI'},
'1613394':{'en': 'Trenton, ON'},
'1613395':{'en': 'Stirling, ON'},
'1613396':{'en': 'Deseronto, ON'},
'1613392':{'en': 'Trenton, ON'},
'1613393':{'en': 'Bloomfield, ON'},
'1434645':{'en': 'Crewe, VA'},
'1613398':{'en': 'Frankford, ON'},
'1613399':{'en': 'Wellington, ON'},
'1604988':{'en': 'North Vancouver, BC'},
'1505554':{'en': 'Albuquerque, NM'},
'1570373':{'en': 'Kulpmont, PA'},
'1505550':{'en': 'Albuquerque, NM'},
'1505553':{'en': 'Albuquerque, NM'},
'1469366':{'en': 'Plano, TX'},
'1609465':{'en': 'Cape May Ct Hse, NJ'},
'1516541':{'en': 'Massapequa, NY'},
'1443777':{'en': 'Baltimore, MD'},
'1509324':{'en': 'Spokane, WA'},
'1612625':{'en': 'Minneapolis, MN'},
'1612624':{'en': 'Minneapolis, MN'},
'1612623':{'en': 'Minneapolis, MN'},
'1604514':{'en': 'Langley, BC'},
'1612331':{'en': 'Minneapolis, MN'},
'1517764':{'en': 'Jackson, MI'},
'1510261':{'en': 'Oakland, CA'},
'1585760':{'en': 'Rochester, NY'},
'1510264':{'en': 'Hayward, CA'},
'1510265':{'en': 'Hayward, CA'},
'1510266':{'en': 'Hayward, CA'},
'1510268':{'en': 'Oakland, CA'},
'1517768':{'en': 'Jackson, MI'},
'1541476':{'en': 'Grants Pass, OR'},
'1541475':{'en': 'Madras, OR'},
'1541474':{'en': 'Grants Pass, OR'},
'1541473':{'en': 'Vale, OR'},
'1541472':{'en': 'Grants Pass, OR'},
'1541471':{'en': 'Grants Pass, OR'},
'1425427':{'en': 'Issaquah, WA'},
'1434392':{'en': 'Farmville, VA'},
'1541479':{'en': 'Grants Pass, OR'},
'1517266':{'en': 'Adrian, MI'},
'1514948':{'en': 'Montreal, QC'},
'1478452':{'en': 'Milledgeville, GA'},
'1478453':{'en': 'Milledgeville, GA'},
'1602336':{'en': 'Phoenix, AZ'},
'1478451':{'en': 'Milledgeville, GA'},
'1514940':{'en': 'Montreal, QC'},
'1478454':{'en': 'Milledgeville, GA'},
'1602445':{'en': 'Phoenix, AZ'},
'1415897':{'en': 'Novato, CA'},
'1415896':{'en': 'San Francisco, CA'},
'1415895':{'en': 'Novato, CA'},
'1415892':{'en': 'Novato, CA'},
'1540877':{'en': 'Winchester, VA'},
'1503813':{'en': 'Portland, OR'},
'1540879':{'en': 'Dayton, VA'},
'1415899':{'en': 'Novato, CA'},
'1415898':{'en': 'Novato, CA'},
'1570596':{'en': 'Gillett, PA'},
'1608441':{'en': 'Madison, WI'},
'1616551':{'en': 'Grand Rapids, MI'},
'1513686':{'en': 'Cincinnati, OH'},
'1610270':{'en': 'Norristown, PA'},
'1513683':{'en': 'Loveland, OH'},
'1513681':{'en': 'Cincinnati, OH'},
'1413448':{'en': 'Pittsfield, MA'},
'1413442':{'en': 'Pittsfield, MA'},
'1413443':{'en': 'Pittsfield, MA'},
'1413447':{'en': 'Pittsfield, MA'},
'1413445':{'en': 'Pittsfield, MA'},
'1415479':{'en': 'San Rafael, CA'},
'1585458':{'en': 'Rochester, NY'},
'1615731':{'en': 'Antioch, TN'},
'1415473':{'en': 'San Rafael, CA'},
'1415472':{'en': 'San Rafael, CA'},
'1415474':{'en': 'San Francisco, CA'},
'1415476':{'en': 'San Francisco, CA'},
'1514419':{'en': 'Montreal, QC'},
'1575526':{'en': 'Las Cruces, NM'},
'1575527':{'en': 'Las Cruces, NM'},
'1575524':{'en': 'Las Cruces, NM'},
'1575525':{'en': 'Las Cruces, NM'},
'1575522':{'en': 'Las Cruces, NM'},
'1575523':{'en': 'Las Cruces, NM'},
'1575521':{'en': 'Las Cruces, NM'},
'1604718':{'en': 'Vancouver, BC'},
'1450991':{'en': 'Granby, QC'},
'1450449':{'en': 'Boucherville, QC'},
'1450448':{'en': 'Longueuil, QC'},
'1450447':{'en': 'Chambly, QC'},
'1450445':{'en': 'Saint-Hubert, QC'},
'1450443':{'en': 'Saint-Hubert, QC'},
'1450442':{'en': 'Longueuil, QC'},
'1450441':{'en': 'St-Bruno-de-Montarville, QC'},
'1512819':{'en': 'Georgetown, TX'},
'1604638':{'en': 'Vancouver, BC'},
'1604321':{'en': 'Vancouver, BC'},
'1604632':{'en': 'Vancouver, BC'},
'1604323':{'en': 'Vancouver, BC'},
'1604322':{'en': 'Vancouver, BC'},
'1604325':{'en': 'Vancouver, BC'},
'1604324':{'en': 'Vancouver, BC'},
'1604327':{'en': 'Vancouver, BC'},
'1408871':{'en': 'Campbell, CA'},
'1408879':{'en': 'Campbell, CA'},
'1530229':{'en': 'Redding, CA'},
'1530226':{'en': 'Redding, CA'},
'1530227':{'en': 'Redding, CA'},
'1530224':{'en': 'Redding, CA'},
'1530225':{'en': 'Redding, CA'},
'1530222':{'en': 'Redding, CA'},
'1530223':{'en': 'Redding, CA'},
'1530221':{'en': 'Redding, CA'},
'1559739':{'en': 'Visalia, CA'},
'1414257':{'en': 'Milwaukee, WI'},
'1508898':{'en': 'Westborough, MA'},
'1502259':{'en': 'Louisville, KY'},
'1508678':{'en': 'Fall River, MA'},
'1508679':{'en': 'Fall River, MA'},
'1502252':{'en': 'Bloomfield, KY'},
'1502253':{'en': 'Louisville, KY'},
'1508674':{'en': 'Fall River, MA'},
'1508675':{'en': 'Fall River, MA'},
'1508672':{'en': 'Fall River, MA'},
'1508673':{'en': 'Fall River, MA'},
'1508894':{'en': 'Brockton, MA'},
'1414259':{'en': 'Milwaukee, WI'},
'1563886':{'en': 'Tipton, IA'},
'1540206':{'en': 'Roanoke, VA'},
'1508273':{'en': 'Wareham, MA'},
'1520378':{'en': 'Sierra Vista, AZ'},
'1520807':{'en': 'Tucson, AZ'},
'1520377':{'en': 'Nogales, AZ'},
'1520803':{'en': 'Sierra Vista, AZ'},
'1415781':{'en': 'San Francisco, CA'},
'1415788':{'en': 'San Francisco, CA'},
'1585638':{'en': 'Holley, NY'},
'1414431':{'en': 'Milwaukee, WI'},
'1573243':{'en': 'Jackson, MO'},
'1414438':{'en': 'Milwaukee, WI'},
'1573248':{'en': 'Hannibal, MO'},
'1503251':{'en': 'Portland, OR'},
'1503253':{'en': 'Portland, OR'},
'1503252':{'en': 'Portland, OR'},
'1503255':{'en': 'Portland, OR'},
'1503254':{'en': 'Portland, OR'},
'1503257':{'en': 'Portland, OR'},
'1503256':{'en': 'Portland, OR'},
'1503259':{'en': 'Beaverton, OR'},
'1503258':{'en': 'Portland, OR'},
'1515453':{'en': 'West Des Moines, IA'},
'1515457':{'en': 'West Des Moines, IA'},
'1610419':{'en': 'Bethlehem, PA'},
'1423968':{'en': 'Bristol, TN'},
'1610415':{'en': 'Phoenixville, PA'},
'1601200':{'en': 'Jackson, MS'},
'1613498':{'en': 'Brockville, ON'},
'1437':{'en': 'Ontario'},
'1614717':{'en': 'Dublin, OH'},
'1516229':{'en': 'Uniondale, NY'},
'1614462':{'en': 'Columbus, OH'},
'1516222':{'en': 'Garden City, NY'},
'1574594':{'en': 'Pierceton, IN'},
'1614718':{'en': 'Dublin, OH'},
'1541917':{'en': 'Albany, OR'},
'1614466':{'en': 'Columbus, OH'},
'1541318':{'en': 'Bend, OR'},
'1410563':{'en': 'Baltimore, MD'},
'1541312':{'en': 'Bend, OR'},
'1541647':{'en': 'Bend, OR'},
'1541316':{'en': 'Redmond, OR'},
'1541317':{'en': 'Bend, OR'},
'1503661':{'en': 'Gresham, OR'},
'1410203':{'en': 'Ellicott City, MD'},
'1503663':{'en': 'Boring, OR'},
'1503665':{'en': 'Gresham, OR'},
'1503666':{'en': 'Gresham, OR'},
'1503668':{'en': 'Sandy, OR'},
'1410208':{'en': 'Berlin, MD'},
'1614469':{'en': 'Columbus, OH'},
'1409925':{'en': 'Santa Fe, TX'},
'1614430':{'en': 'Columbus, OH'},
'1562826':{'en': 'Long Beach, CA'},
'1604713':{'en': 'Vancouver, BC'},
'1541842':{'en': 'Medford, OR'},
'1570742':{'en': 'Milton, PA'},
'1570297':{'en': 'Troy, PA'},
'1570296':{'en': 'Milford, PA'},
'1604714':{'en': 'Vancouver, BC'},
'1570746':{'en': 'Wyalusing, PA'},
'1435257':{'en': 'Tremonton, UT'},
'1608237':{'en': 'Madison, WI'},
'1418435':{'en': 'Baie-Saint-Paul, QC'},
'1435251':{'en': 'St. George, UT'},
'1513474':{'en': 'Cincinnati, OH'},
'1513475':{'en': 'Cincinnati, OH'},
'1516482':{'en': 'Great Neck, NY'},
'1513471':{'en': 'Cincinnati, OH'},
'1435259':{'en': 'Moab, UT'},
'1418439':{'en': 'Clermont, QC'},
'1580243':{'en': 'Elk City, OK'},
'1479267':{'en': 'Farmington, AR'},
'1609859':{'en': 'Southampton Township, NJ'},
'1580248':{'en': 'Lawton, OK'},
'1479268':{'en': 'Bentonville, AR'},
'1613725':{'en': 'Ottawa, ON'},
'1613724':{'en': 'Ottawa, ON'},
'1613722':{'en': 'Ottawa, ON'},
'1613729':{'en': 'Ottawa, ON'},
'1512581':{'en': 'Bastrop, TX'},
'1612455':{'en': 'Minneapolis, MN'},
'1616719':{'en': 'Grand Rapids, MI'},
'1540535':{'en': 'Winchester, VA'},
'1608849':{'en': 'Waunakee, WI'},
'1612335':{'en': 'Minneapolis, MN'},
'1440293':{'en': 'Andover, OH'},
'1513217':{'en': 'Middletown, OH'},
'1502538':{'en': 'Mount Washington, KY'},
'1413785':{'en': 'Springfield, MA'},
'1413787':{'en': 'Springfield, MA'},
'1413786':{'en': 'Agawam, MA'},
'1413781':{'en': 'Springfield, MA'},
'1413783':{'en': 'Springfield, MA'},
'1413782':{'en': 'Springfield, MA'},
'1413789':{'en': 'Agawam, MA'},
'1413788':{'en': 'Springfield, MA'},
'1603788':{'en': 'Lancaster, NH'},
'1603786':{'en': 'Rumney, NH'},
'1603787':{'en': 'North Haverhill, NH'},
'1479996':{'en': 'Greenwood, AR'},
'1479997':{'en': 'Mulberry, AR'},
'1602787':{'en': 'Phoenix, AZ'},
'1602839':{'en': 'Phoenix, AZ'},
'1602789':{'en': 'Phoenix, AZ'},
'1602788':{'en': 'Phoenix, AZ'},
'1608884':{'en': 'Edgerton, WI'},
'1608527':{'en': 'New Glarus, WI'},
'1608526':{'en': 'Holmen, WI'},
'1608524':{'en': 'Reedsburg, WI'},
'1416665':{'en': 'North York, ON'},
'1416667':{'en': 'North York, ON'},
'1416661':{'en': 'North York, ON'},
'1615678':{'en': 'Nashville, TN'},
'1416663':{'en': 'North York, ON'},
'1612929':{'en': 'Minneapolis, MN'},
'1510745':{'en': 'Fremont, CA'},
'1510744':{'en': 'Fremont, CA'},
'1510742':{'en': 'Fremont, CA'},
'1510749':{'en': 'Alameda, CA'},
'1510748':{'en': 'Alameda, CA'},
'1425212':{'en': 'Everett, WA'},
'1519352':{'en': 'Chatham, ON'},
'1412788':{'en': 'Pittsburgh, PA'},
'1507835':{'en': 'Waseca, MN'},
'1519355':{'en': 'Chatham, ON'},
'1507836':{'en': 'Slayton, MN'},
'1412782':{'en': 'Pittsburgh, PA'},
'1412781':{'en': 'Pittsburgh, PA'},
'1412787':{'en': 'Pittsburgh, PA'},
'1412784':{'en': 'Pittsburgh, PA'},
'1410869':{'en': 'Catonsville, MD'},
'1616827':{'en': 'Grand Rapids, MI'},
'1607776':{'en': 'Bath, NY'},
'1607533':{'en': 'Lansing, NY'},
'1504288':{'en': 'New Orleans, LA'},
'1607535':{'en': 'Watkins Glen, NY'},
'1504283':{'en': 'New Orleans, LA'},
'1504282':{'en': 'New Orleans, LA'},
'1602331':{'en': 'Phoenix, AZ'},
'1409840':{'en': 'Beaumont, TX'},
'1409842':{'en': 'Beaumont, TX'},
'1505884':{'en': 'Albuquerque, NM'},
'1508460':{'en': 'Marlborough, MA'},
'1505883':{'en': 'Albuquerque, NM'},
'1505880':{'en': 'Albuquerque, NM'},
'1505881':{'en': 'Albuquerque, NM'},
'1505888':{'en': 'Albuquerque, NM'},
'1505889':{'en': 'Albuquerque, NM'},
'1520498':{'en': 'Tucson, AZ'},
'1503391':{'en': 'Salem, OR'},
'1503394':{'en': 'Scio, OR'},
'1503397':{'en': 'St. Helens, OR'},
'1503399':{'en': 'Salem, OR'},
'1520495':{'en': 'Tucson, AZ'},
'1512482':{'en': 'Austin, TX'},
'1609693':{'en': 'Forked River, NJ'},
'1512480':{'en': 'Austin, TX'},
'1512481':{'en': 'Austin, TX'},
'1415648':{'en': 'San Francisco, CA'},
'1423778':{'en': 'Chattanooga, TN'},
'1415647':{'en': 'San Francisco, CA'},
'1415644':{'en': 'San Francisco, CA'},
'1415642':{'en': 'San Francisco, CA'},
'1415643':{'en': 'San Francisco, CA'},
'1418233':{'en': 'Les Escoumins, QC'},
'1605753':{'en': 'Watertown, SD'},
'1410928':{'en': 'Millington, MD'},
'1412675':{'en': 'McKeesport, PA'},
'1410922':{'en': 'Randallstown, MD'},
'1412673':{'en': 'McKeesport, PA'},
'1508285':{'en': 'Norton, MA'},
'1508281':{'en': 'Marlborough, MA'},
'1423510':{'en': 'Chattanooga, TN'},
'1506533':{'en': 'Shediac, NB'},
'1506532':{'en': 'Shediac, NB'},
'1506536':{'en': 'Sackville, NB'},
'1561835':{'en': 'West Palm Beach, FL'},
'1561833':{'en': 'West Palm Beach, FL'},
'1561832':{'en': 'West Palm Beach, FL'},
'1440842':{'en': 'Cleveland, OH'},
'1440843':{'en': 'Cleveland, OH'},
'1607277':{'en': 'Ithaca, NY'},
'1615382':{'en': 'Springfield, TN'},
'1440846':{'en': 'Strongsville, OH'},
'1615384':{'en': 'Springfield, TN'},
'1440845':{'en': 'Cleveland, OH'},
'1601922':{'en': 'Jackson, MS'},
'1601923':{'en': 'Jackson, MS'},
'1601924':{'en': 'Clinton, MS'},
'1601925':{'en': 'Clinton, MS'},
'1615431':{'en': 'Hendersonville, TN'},
'1563690':{'en': 'Dubuque, IA'},
'1610351':{'en': 'Allentown, PA'},
'1507226':{'en': 'Rochester, MN'},
'1610352':{'en': 'Upper Darby, PA'},
'1610354':{'en': 'King of Prussia, PA'},
'1507223':{'en': 'Canby, MN'},
'1502292':{'en': 'Prospect, KY'},
'1518789':{'en': 'Millerton, NY'},
'1608231':{'en': 'Madison, WI'},
'1573659':{'en': 'Jefferson City, MO'},
'1573657':{'en': 'Ashland, MO'},
'1480839':{'en': 'Tempe, AZ'},
'1573651':{'en': 'Cape Girardeau, MO'},
'1540438':{'en': 'Harrisonburg, VA'},
'1540439':{'en': 'Bealeton, VA'},
'1507454':{'en': 'Winona, MN'},
'1615653':{'en': 'Murfreesboro, TN'},
'1540432':{'en': 'Harrisonburg, VA'},
'1540433':{'en': 'Harrisonburg, VA'},
'1540434':{'en': 'Harrisonburg, VA'},
'1540437':{'en': 'Harrisonburg, VA'},
'1417257':{'en': 'West Plains, MO'},
'1417256':{'en': 'West Plains, MO'},
'1417255':{'en': 'West Plains, MO'},
'1610768':{'en': 'King of Prussia, PA'},
'1510208':{'en': 'Oakland, CA'},
'1601684':{'en': 'McComb, MS'},
'1561347':{'en': 'Boca Raton, FL'},
'1605977':{'en': 'Sioux Falls, SD'},
'1601683':{'en': 'Newton, MS'},
'1606258':{'en': 'Corbin, KY'},
'1479434':{'en': 'Fort Smith, AR'},
'1617389':{'en': 'Everett, MA'},
'1617381':{'en': 'Everett, MA'},
'1617387':{'en': 'Everett, MA'},
'1561697':{'en': 'West Palm Beach, FL'},
'1606668':{'en': 'Campton, KY'},
'1505577':{'en': 'Santa Fe, NM'},
'1613238':{'en': 'Ottawa, ON'},
'1450746':{'en': 'Sorel, QC'},
'1603899':{'en': 'Rindge, NH'},
'1516568':{'en': 'Valley Stream, NY'},
'1617265':{'en': 'Dorchester, MA'},
'1516561':{'en': 'Valley Stream, NY'},
'1617266':{'en': 'Boston, MA'},
'1516562':{'en': 'Manhasset, NY'},
'1434447':{'en': 'South Hill, VA'},
'1573893':{'en': 'Jefferson City, MO'},
'1479521':{'en': 'Fayetteville, AR'},
'1510535':{'en': 'Oakland, CA'},
'1510536':{'en': 'Oakland, CA'},
'1510537':{'en': 'Castro Valley, CA'},
'1510530':{'en': 'Oakland, CA'},
'1479524':{'en': 'Siloam Springs, AR'},
'1479527':{'en': 'Fayetteville, AR'},
'1517741':{'en': 'Union City, MI'},
'1541451':{'en': 'Lebanon, OR'},
'1602314':{'en': 'Phoenix, AZ'},
'1617262':{'en': 'Boston, MA'},
'1519662':{'en': 'New Hamburg, ON'},
'1541459':{'en': 'Sutherlin, OR'},
'1603890':{'en': 'Salem, NH'},
'1503835':{'en': 'Amity, OR'},
'1616831':{'en': 'Grand Rapids, MI'},
'1503831':{'en': 'Dallas, OR'},
'1602466':{'en': 'Phoenix, AZ'},
'1519667':{'en': 'London, ON'},
'1418849':{'en': 'Quebec City, QC'},
'1418848':{'en': 'Stoneham, QC'},
'1540853':{'en': 'Roanoke, VA'},
'1540857':{'en': 'Roanoke, VA'},
'1418841':{'en': 'Quebec City, QC'},
'1512398':{'en': 'Lockhart, TX'},
'1413315':{'en': 'Holyoke, MA'},
'1518747':{'en': 'Hudson Falls, NY'},
'1575894':{'en': 'Truth Or Cnsqncs, NM'},
'1478922':{'en': 'Warner Robins, GA'},
'1478923':{'en': 'Warner Robins, GA'},
'1410945':{'en': 'Baltimore, MD'},
'1507794':{'en': 'Sleepy Eye, MN'},
'1478929':{'en': 'Warner Robins, GA'},
'1514439':{'en': 'Montreal, QC'},
'1616527':{'en': 'Ionia, MI'},
'1612863':{'en': 'Minneapolis, MN'},
'1575541':{'en': 'Las Cruces, NM'},
'1575542':{'en': 'Lordsburg, NM'},
'1432729':{'en': 'Marfa, TX'},
'1575544':{'en': 'Deming, NM'},
'1575546':{'en': 'Deming, NM'},
'1530795':{'en': 'Winters, CA'},
'1530790':{'en': 'Yuba City, CA'},
'1450469':{'en': u('Saint-C\u00e9saire, QC')},
'1518298':{'en': 'Champlain, NY'},
'1518568':{'en': 'St. Johnsville, NY'},
'1450461':{'en': 'St-Bruno-de-Montarville, QC'},
'1450460':{'en': 'Marieville, QC'},
'1450463':{'en': 'Longueuil, QC'},
'1518292':{'en': 'Albany, NY'},
'1518295':{'en': 'Schoharie, NY'},
'1509252':{'en': 'Spokane, WA'},
'1518297':{'en': 'Rouses Point, NY'},
'1410943':{'en': 'Hurlock, MD'},
'1408851':{'en': 'Santa Clara, CA'},
'1408855':{'en': 'Santa Clara, CA'},
'1612725':{'en': 'Minneapolis, MN'},
'1450645':{'en': 'Boucherville, QC'},
'1450647':{'en': 'Longueuil, QC'},
'1450646':{'en': 'Longueuil, QC'},
'1450641':{'en': 'Boucherville, QC'},
'1530241':{'en': 'Redding, CA'},
'1530242':{'en': 'Redding, CA'},
'1504561':{'en': 'New Orleans, LA'},
'1450649':{'en': 'Sainte-Julie, QC'},
'1530245':{'en': 'Redding, CA'},
'1530246':{'en': 'Redding, CA'},
'1530247':{'en': 'Redding, CA'},
'1412373':{'en': 'Monroeville, PA'},
'1412372':{'en': 'Monroeville, PA'},
'1412371':{'en': 'Pittsburgh, PA'},
'1585436':{'en': 'Rochester, NY'},
'1412374':{'en': 'Monroeville, PA'},
'1416971':{'en': 'Toronto, ON'},
'1508616':{'en': 'Westborough, MA'},
'1416504':{'en': 'Toronto, ON'},
'1419333':{'en': 'Fremont, OH'},
'1416506':{'en': 'Toronto, ON'},
'1419331':{'en': 'Lima, OH'},
'1604630':{'en': 'Vancouver, BC'},
'1419337':{'en': 'Wauseon, OH'},
'1419334':{'en': 'Fremont, OH'},
'1419335':{'en': 'Wauseon, OH'},
'1563864':{'en': 'Postville, IA'},
'1416975':{'en': 'Toronto, ON'},
'1419339':{'en': 'Elida, OH'},
'1520829':{'en': 'Tucson, AZ'},
'1419257':{'en': 'North Baltimore, OH'},
'1520822':{'en': 'Tucson, AZ'},
'1520825':{'en': 'Tucson, AZ'},
'1520826':{'en': 'Pearce, AZ'},
'1512873':{'en': 'Austin, TX'},
'1419259':{'en': 'Toledo, OH'},
'1604637':{'en': 'Vancouver, BC'},
'1585389':{'en': 'Pittsford, NY'},
'1585388':{'en': 'Fairport, NY'},
'1540365':{'en': 'Ferrum, VA'},
'1512878':{'en': 'San Marcos, TX'},
'1615325':{'en': 'Portland, TN'},
'1615451':{'en': 'Gallatin, TN'},
'1540361':{'en': 'Fredericksburg, VA'},
'1615321':{'en': 'Nashville, TN'},
'1615320':{'en': 'Nashville, TN'},
'1503239':{'en': 'Portland, OR'},
'1503238':{'en': 'Portland, OR'},
'1503233':{'en': 'Portland, OR'},
'1503232':{'en': 'Portland, OR'},
'1503231':{'en': 'Portland, OR'},
'1503230':{'en': 'Portland, OR'},
'1503236':{'en': 'Portland, OR'},
'1503235':{'en': 'Portland, OR'},
'1503234':{'en': 'Portland, OR'},
'1559757':{'en': 'Pixley, CA'},
'1423989':{'en': 'Bristol, TN'},
'1601268':{'en': 'Hattiesburg, MS'},
'1505766':{'en': 'Albuquerque, NM'},
'1505764':{'en': 'Albuquerque, NM'},
'1601591':{'en': 'Brandon, MS'},
'1601261':{'en': 'Hattiesburg, MS'},
'1505768':{'en': 'Albuquerque, NM'},
'1601267':{'en': 'Carthage, MS'},
'1601264':{'en': 'Hattiesburg, MS'},
'1609':{'en': 'New Jersey'},
'1512296':{'en': 'Austin, TX'},
'1512295':{'en': 'Buda, TX'},
'1610293':{'en': 'Wayne, PA'},
'1512292':{'en': 'Austin, TX'},
'1512291':{'en': 'Austin, TX'},
'1601':{'en': 'Mississippi'},
'1603':{'en': 'New Hampshire'},
'1435896':{'en': 'Richfield, UT'},
'1605':{'en': 'South Dakota'},
'1604':{'en': 'British Columbia'},
'1435893':{'en': 'Richfield, UT'},
'1606':{'en': 'Kentucky'},
'1541938':{'en': 'Milton-Freewater, OR'},
'1541935':{'en': 'Veneta, OR'},
'1530879':{'en': 'Chico, CA'},
'1530873':{'en': 'Magalia, CA'},
'1530872':{'en': 'Paradise, CA'},
'1530877':{'en': 'Paradise, CA'},
'1530876':{'en': 'Paradise, CA'},
'1562804':{'en': 'Bellflower, CA'},
'1410269':{'en': 'Annapolis, MD'},
'1410268':{'en': 'Annapolis, MD'},
'1562801':{'en': 'Pico Rivera, CA'},
'1562803':{'en': 'Downey, CA'},
'1410263':{'en': 'Annapolis, MD'},
'1503643':{'en': 'Beaverton, OR'},
'1503640':{'en': 'Hillsboro, OR'},
'1503641':{'en': 'Beaverton, OR'},
'1503646':{'en': 'Beaverton, OR'},
'1503647':{'en': 'North Plains, OR'},
'1503644':{'en': 'Beaverton, OR'},
'1423238':{'en': 'Ooltewah, TN'},
'1423239':{'en': 'Kingsport, TN'},
'1423235':{'en': 'Bulls Gap, TN'},
'1423232':{'en': 'Johnson City, TN'},
'1423230':{'en': 'Kingsport, TN'},
'1432267':{'en': 'Big Spring, TX'},
'1432264':{'en': 'Big Spring, TX'},
'1432263':{'en': 'Big Spring, TX'},
'1432262':{'en': 'Midland, TX'},
'1551':{'en': 'New Jersey'},
'1513451':{'en': 'Cincinnati, OH'},
'1608786':{'en': 'West Salem, WI'},
'1513459':{'en': 'Mason, OH'},
'1501865':{'en': 'Bismarck, AR'},
'1610837':{'en': 'Bath, PA'},
'1501860':{'en': 'Benton, AR'},
'1610831':{'en': 'Collegeville, PA'},
'1440729':{'en': 'Chesterland, OH'},
'1609871':{'en': 'Willingboro, NJ'},
'1480543':{'en': 'Gilbert, AZ'},
'1418459':{'en': 'La Guadeloupe, QC'},
'1501868':{'en': 'Little Rock, AR'},
'1501262':{'en': 'Hot Springs, AR'},
'1609737':{'en': 'Pennington, NJ'},
'1541667':{'en': 'Hermiston, OR'},
'1541664':{'en': 'Central Point, OR'},
'1541665':{'en': 'Central Point, OR'},
'1541663':{'en': 'La Grande, OR'},
'1541660':{'en': 'Grants Pass, OR'},
'1408683':{'en': 'San Martin, CA'},
'1513232':{'en': 'Cincinnati, OH'},
'1513233':{'en': 'Cincinnati, OH'},
'1513231':{'en': 'Cincinnati, OH'},
'1513984':{'en': 'Cincinnati, OH'},
'1513985':{'en': 'Cincinnati, OH'},
'1513234':{'en': 'Mason, OH'},
'1513988':{'en': 'Trenton, OH'},
'1616732':{'en': 'Grand Rapids, MI'},
'1616735':{'en': 'Grand Rapids, MI'},
'1516609':{'en': 'Glen Cove, NY'},
'1561575':{'en': 'Jupiter, FL'},
'1609393':{'en': 'Trenton, NJ'},
'1561572':{'en': 'Boynton Beach, FL'},
'1570723':{'en': 'Wellsboro, PA'},
'1570722':{'en': 'Albrightsville, PA'},
'1419855':{'en': 'Genoa, OH'},
'1563589':{'en': 'Dubuque, IA'},
'1412488':{'en': 'Pittsburgh, PA'},
'1570729':{'en': 'Beach Lake, PA'},
'1585475':{'en': 'Rochester, NY'},
'1585473':{'en': 'Rochester, NY'},
'1530493':{'en': 'Happy Camp, CA'},
'1412331':{'en': 'McKees Rocks, PA'},
'1575394':{'en': 'Eunice, NM'},
'1575397':{'en': 'Hobbs, NM'},
'1575396':{'en': 'Lovington, NM'},
'1478553':{'en': 'Sandersville, GA'},
'1478552':{'en': 'Sandersville, GA'},
'1575393':{'en': 'Hobbs, NM'},
'1575392':{'en': 'Hobbs, NM'},
'1607739':{'en': 'Horseheads, NY'},
'1607737':{'en': 'Elmira, NY'},
'1607735':{'en': 'Elmira, NY'},
'1607734':{'en': 'Elmira, NY'},
'1607733':{'en': 'Elmira, NY'},
'1607732':{'en': 'Elmira, NY'},
'1510763':{'en': 'Oakland, CA'},
'1541745':{'en': 'Corvallis, OR'},
'1510769':{'en': 'Alameda, CA'},
'1570929':{'en': 'McAdoo, PA'},
'1570928':{'en': 'Dushore, PA'},
'1607785':{'en': 'Endicott, NY'},
'1604420':{'en': 'Burnaby, BC'},
'1519376':{'en': 'Owen Sound, ON'},
'1519371':{'en': 'Owen Sound, ON'},
'1519372':{'en': 'Owen Sound, ON'},
'1570389':{'en': 'Bloomsburg, PA'},
'1585288':{'en': 'Rochester, NY'},
'1450258':{'en': 'Mirabel, QC'},
'1450252':{'en': 'Saint-Hyacinthe, QC'},
'1450250':{'en': 'Saint-Hyacinthe, QC'},
'1507931':{'en': 'St. Peter, MN'},
'1507932':{'en': 'St. Charles, MN'},
'1507934':{'en': 'St. Peter, MN'},
'1570923':{'en': 'Renovo, PA'},
'1610374':{'en': 'Reading, PA'},
'1607255':{'en': 'Ithaca, NY'},
'1609561':{'en': 'Hammonton, NJ'},
'1408993':{'en': 'San Jose, CA'},
'1408995':{'en': 'San Jose, CA'},
'1408996':{'en': 'Cupertino, CA'},
'1408997':{'en': 'San Jose, CA'},
'1408998':{'en': 'San Jose, CA'},
'1415337':{'en': 'San Francisco, CA'},
'1415334':{'en': 'San Francisco, CA'},
'1415332':{'en': 'Sausalito, CA'},
'1415333':{'en': 'San Francisco, CA'},
'1415330':{'en': 'San Francisco, CA'},
'1415331':{'en': 'Sausalito, CA'},
'1415339':{'en': 'Sausalito, CA'},
'1512469':{'en': 'Austin, TX'},
'1415621':{'en': 'San Francisco, CA'},
'1423753':{'en': 'Jonesborough, TN'},
'1423752':{'en': 'Chattanooga, TN'},
'1415626':{'en': 'San Francisco, CA'},
'1423756':{'en': 'Chattanooga, TN'},
'1603483':{'en': 'Candia, NH'},
'1605778':{'en': 'Kimball, SD'},
'1609888':{'en': 'Trenton, NJ'},
'1518251':{'en': 'North Creek, NY'},
'1605773':{'en': 'Pierre, SD'},
'1563324':{'en': 'Davenport, IA'},
'1563323':{'en': 'Davenport, IA'},
'1563322':{'en': 'Davenport, IA'},
'1423531':{'en': 'Chattanooga, TN'},
'1607656':{'en': 'Greene, NY'},
'1562498':{'en': 'Long Beach, CA'},
'1562496':{'en': 'Long Beach, CA'},
'1562494':{'en': 'Long Beach, CA'},
'1562495':{'en': 'Long Beach, CA'},
'1562492':{'en': 'Long Beach, CA'},
'1423538':{'en': 'Bluff City, TN'},
'1562490':{'en': 'Long Beach, CA'},
'1562491':{'en': 'Long Beach, CA'},
'1502352':{'en': 'Frankfort, KY'},
'1502350':{'en': 'Bardstown, KY'},
'1601638':{'en': 'Vicksburg, MS'},
'1605487':{'en': 'Lake Andes, SD'},
'1518626':{'en': 'Albany, NY'},
'1501520':{'en': 'Hot Springs, AR'},
'1501525':{'en': 'Hot Springs, AR'},
'1501526':{'en': 'Little Rock, AR'},
'1615410':{'en': 'Murfreesboro, TN'},
'1610628':{'en': 'Allentown, PA'},
'1507206':{'en': 'Rochester, MN'},
'1440437':{'en': 'Orwell, OH'},
'1610330':{'en': 'Easton, PA'},
'1610337':{'en': 'King of Prussia, PA'},
'1610336':{'en': 'Allentown, PA'},
'1610627':{'en': 'Media, PA'},
'1414571':{'en': 'Oak Creek, WI'},
'1414570':{'en': 'Oak Creek, WI'},
'1559561':{'en': 'Three Rivers, CA'},
'1559562':{'en': 'Lindsay, CA'},
'1559564':{'en': 'Woodlake, CA'},
'1615673':{'en': 'Nashville, TN'},
'1615672':{'en': 'White House, TN'},
'1605995':{'en': 'Mitchell, SD'},
'1573632':{'en': 'Jefferson City, MO'},
'1573634':{'en': 'Jefferson City, MO'},
'1573635':{'en': 'Jefferson City, MO'},
'1573636':{'en': 'Jefferson City, MO'},
'1410902':{'en': 'Owings Mills, MD'},
'1604875':{'en': 'Vancouver, BC'},
'1410901':{'en': 'Cambridge, MD'},
'1574946':{'en': 'Winamac, IN'},
'1512524':{'en': 'Austin, TX'},
'1601787':{'en': 'Heidelberg, MS'},
'1520615':{'en': 'Tucson, AZ'},
'1512835':{'en': 'Austin, TX'},
'1604304':{'en': 'Richmond, BC'},
'1423636':{'en': 'Greeneville, TN'},
'1417276':{'en': 'Stockton, MO'},
'1417272':{'en': 'Reeds Spring, MO'},
'1561369':{'en': 'Boynton Beach, FL'},
'1517355':{'en': 'East Lansing, MI'},
'1604873':{'en': 'Vancouver, BC'},
'1510434':{'en': 'Oakland, CA'},
'1561361':{'en': 'Boca Raton, FL'},
'1561362':{'en': 'Boca Raton, FL'},
'1561364':{'en': 'Boynton Beach, FL'},
'1561367':{'en': 'Boca Raton, FL'},
'1479441':{'en': 'Fort Smith, AR'},
'1419628':{'en': 'Minster, OH'},
'1419629':{'en': 'New Bremen, OH'},
'1419624':{'en': 'Sandusky, OH'},
'1419625':{'en': 'Sandusky, OH'},
'1419626':{'en': 'Sandusky, OH'},
'1419627':{'en': 'Sandusky, OH'},
'1419621':{'en': 'Sandusky, OH'},
'1510430':{'en': 'Oakland, CA'},
'1410221':{'en': 'Cambridge, MD'},
'1479444':{'en': 'Fayetteville, AR'},
'1510979':{'en': 'Fremont, CA'},
'1613824':{'en': u('Orl\u00e9ans, ON')},
'1613822':{'en': 'Gloucester, ON'},
'1423949':{'en': 'Dunlap, TN'},
'1517646':{'en': 'Dimondale, MI'},
'1610367':{'en': 'Boyertown, PA'},
'1419996':{'en': 'Lima, OH'},
'1419994':{'en': 'Loudonville, OH'},
'1419991':{'en': 'Lima, OH'},
'1419999':{'en': 'Lima, OH'},
'1410674':{'en': 'Odenton, MD'},
'1410675':{'en': 'Baltimore, MD'},
'1410676':{'en': 'Edgewood, MD'},
'1410677':{'en': 'Salisbury, MD'},
'1503581':{'en': 'Salem, OR'},
'1410671':{'en': 'Edgewood, MD'},
'1410672':{'en': 'Odenton, MD'},
'1503582':{'en': 'Wilsonville, OR'},
'1612668':{'en': 'Minneapolis, MN'},
'1503589':{'en': 'Salem, OR'},
'1503588':{'en': 'Salem, OR'},
'1501982':{'en': 'Jacksonville, AR'},
'1501985':{'en': 'Jacksonville, AR'},
'1610668':{'en': 'Bala Cynwyd, PA'},
'1602371':{'en': 'Phoenix, AZ'},
'1602372':{'en': 'Phoenix, AZ'},
'1602374':{'en': 'Phoenix, AZ'},
'1602375':{'en': 'Phoenix, AZ'},
'1541432':{'en': 'Joseph, OR'},
'1541431':{'en': 'Eugene, OR'},
'1570654':{'en': 'Pittston, PA'},
'1614326':{'en': 'Columbus, OH'},
'1418868':{'en': u('Rivi\u00e8re-du-Loup, QC')},
'1418860':{'en': u('Rivi\u00e8re-du-Loup, QC')},
'1418863':{'en': u('Rivi\u00e8re-du-Loup, QC')},
'1418862':{'en': u('Rivi\u00e8re-du-Loup, QC')},
'1418867':{'en': u('Rivi\u00e8re-du-Loup, QC')},
'1540887':{'en': 'Staunton, VA'},
'1469272':{'en': 'Cedar Hill, TX'},
'1519974':{'en': 'Windsor, ON'},
'1610515':{'en': 'Easton, PA'},
'1610841':{'en': 'Allentown, PA'},
'1440775':{'en': 'Oberlin, OH'},
'1501327':{'en': 'Conway, AR'},
'1501324':{'en': 'Little Rock, AR'},
'1501321':{'en': 'Hot Springs, AR'},
'1501329':{'en': 'Conway, AR'},
'1501328':{'en': 'Conway, AR'},
'1617361':{'en': 'Hyde Park, MA'},
'1604593':{'en': 'Surrey, BC'},
'1479549':{'en': 'Siloam Springs, AR'},
'1518762':{'en': 'Johnstown, NY'},
'1518765':{'en': 'Voorheesville, NY'},
'1614818':{'en': 'Westerville, OH'},
'1518767':{'en': 'Selkirk, NY'},
'1518766':{'en': 'Nassau, NY'},
'1602595':{'en': 'Phoenix, AZ'},
'1478945':{'en': 'Jeffersonville, GA'},
'1478946':{'en': 'Irwinton, GA'},
'1478763':{'en': 'Twin City, GA'},
'1604590':{'en': 'Surrey, BC'},
'1612886':{'en': 'Minneapolis, MN'},
'1518546':{'en': 'Port Henry, NY'},
'1603358':{'en': 'Keene, NH'},
'1603429':{'en': 'Merrimack, NH'},
'1603428':{'en': 'Henniker, NH'},
'1603355':{'en': 'Keene, NH'},
'1603354':{'en': 'Keene, NH'},
'1603357':{'en': 'Keene, NH'},
'1603356':{'en': 'North Conway, NH'},
'1603422':{'en': 'Portsmouth, NH'},
'1603421':{'en': 'Derry, NH'},
'1603352':{'en': 'Keene, NH'},
'1509279':{'en': 'Spokane, WA'},
'1509276':{'en': 'Deer Park, WA'},
'1508588':{'en': 'Brockton, MA'},
'1615654':{'en': 'Cross Plains, TN'},
'1508655':{'en': 'Natick, MA'},
'1508580':{'en': 'Brockton, MA'},
'1508583':{'en': 'Brockton, MA'},
'1508584':{'en': 'Brockton, MA'},
'1508586':{'en': 'Brockton, MA'},
'1508587':{'en': 'Brockton, MA'},
'1413594':{'en': 'Chicopee, MA'},
'1413596':{'en': 'Wilbraham, MA'},
'1413592':{'en': 'Chicopee, MA'},
'1413593':{'en': 'Chicopee, MA'},
'1530268':{'en': 'Grass Valley, CA'},
'1413598':{'en': 'Chicopee, MA'},
'1413599':{'en': 'Wilbraham, MA'},
'1425397':{'en': 'Lake Stevens, WA'},
'1425396':{'en': 'Snoqualmie, WA'},
'1414817':{'en': 'Milwaukee, WI'},
'1412359':{'en': 'Pittsburgh, PA'},
'1425392':{'en': 'Issaquah, WA'},
'1425391':{'en': 'Issaquah, WA'},
'1412355':{'en': 'Pittsburgh, PA'},
'1415434':{'en': 'San Francisco, CA'},
'1415437':{'en': 'San Francisco, CA'},
'1412351':{'en': 'Pittsburgh, PA'},
'1412350':{'en': 'Pittsburgh, PA'},
'1412421':{'en': 'Pittsburgh, PA'},
'1562984':{'en': 'Long Beach, CA'},
'1414219':{'en': 'Milwaukee, WI'},
'1410639':{'en': 'Rock Hall, MD'},
'1414744':{'en': 'Milwaukee, WI'},
'1414747':{'en': 'Milwaukee, WI'},
'1608265':{'en': 'Madison, WI'},
'1608266':{'en': 'Madison, WI'},
'1608267':{'en': 'Madison, WI'},
'1608260':{'en': 'Madison, WI'},
'1608262':{'en': 'Madison, WI'},
'1608263':{'en': 'Madison, WI'},
'1608268':{'en': 'Madison, WI'},
'1608269':{'en': 'Sparta, WI'},
'1562981':{'en': 'Long Beach, CA'},
'1509982':{'en': 'Odessa, WA'},
'1562983':{'en': 'Long Beach, CA'},
'1519634':{'en': 'Baden, ON'},
'1519637':{'en': 'St. Thomas, ON'},
'1512858':{'en': 'Dripping Springs, TX'},
'1519632':{'en': 'Ayr, ON'},
'1410631':{'en': 'Baltimore, MD'},
'1480899':{'en': 'Chandler, AZ'},
'1519638':{'en': 'Drayton, ON'},
'1409766':{'en': 'Galveston, TX'},
'1585292':{'en': 'Rochester, NY'},
'1573288':{'en': 'Canton, MO'},
'1615884':{'en': 'Nashville, TN'},
'1562988':{'en': 'Long Beach, CA'},
'1615889':{'en': 'Nashville, TN'},
'1562989':{'en': 'Long Beach, CA'},
'1503215':{'en': 'Portland, OR'},
'1503216':{'en': 'Portland, OR'},
'1409762':{'en': 'Galveston, TX'},
'1409763':{'en': 'Galveston, TX'},
'1415291':{'en': 'San Francisco, CA'},
'1608277':{'en': 'Madison, WI'},
'1415292':{'en': 'San Francisco, CA'},
'1415294':{'en': 'San Francisco, CA'},
'1415296':{'en': 'San Francisco, CA'},
'1562795':{'en': 'Los Alamitos, CA'},
'1605336':{'en': 'Sioux Falls, SD'},
'1508636':{'en': 'Westport, MA'},
'1508634':{'en': 'Milford, MA'},
'1605339':{'en': 'Sioux Falls, SD'},
'1505747':{'en': 'Espanola, NM'},
'1561479':{'en': 'Boca Raton, FL'},
'1443949':{'en': 'Annapolis, MD'},
'1443944':{'en': 'Salisbury, MD'},
'1604941':{'en': 'Port Coquitlam, BC'},
'1604942':{'en': 'Port Coquitlam, BC'},
'1604944':{'en': 'Port Coquitlam, BC'},
'1604947':{'en': 'Bowen Island, BC'},
'1561478':{'en': 'West Palm Beach, FL'},
'1541955':{'en': 'Grants Pass, OR'},
'1541956':{'en': 'Grants Pass, OR'},
'1541957':{'en': 'Roseburg, OR'},
'1605791':{'en': 'Rapid City, SD'},
'1410244':{'en': 'Baltimore, MD'},
'1416815':{'en': 'Toronto, ON'},
'1410243':{'en': 'Baltimore, MD'},
'1540265':{'en': 'Roanoke, VA'},
'1606598':{'en': 'Manchester, KY'},
'1606599':{'en': 'Manchester, KY'},
'1480':{'en': 'Arizona'},
'1484':{'en': 'Pennsylvania'},
'1574772':{'en': 'Knox, IN'},
'1540266':{'en': 'Roanoke, VA'},
'1615441':{'en': 'Dickson, TN'},
'1423253':{'en': 'Tellico Plains, TN'},
'1413967':{'en': 'Ware, MA'},
'1519924':{'en': 'Flesherton, ON'},
'1601249':{'en': 'McComb, MS'},
'1606735':{'en': 'Brooksville, KY'},
'1480563':{'en': 'Scottsdale, AZ'},
'1615446':{'en': 'Dickson, TN'},
'1606738':{'en': 'Sandy Hook, KY'},
'1606739':{'en': 'Catlettsburg, KY'},
'1612273':{'en': 'Minneapolis, MN'},
'1440708':{'en': 'Chagrin Falls, OH'},
'1504838':{'en': 'Metairie, LA'},
'1435213':{'en': 'Logan, UT'},
'1501847':{'en': 'Bryant, AR'},
'1504836':{'en': 'Metairie, LA'},
'1504837':{'en': 'Metairie, LA'},
'1501842':{'en': 'England, AR'},
'1501843':{'en': 'Cabot, AR'},
'1504832':{'en': 'Metairie, LA'},
'1504833':{'en': 'Metairie, LA'},
'1479229':{'en': 'Dardanelle, AR'},
'1616891':{'en': 'Caledonia, MI'},
'1517531':{'en': 'Parma, MI'},
'1606365':{'en': 'Stanford, KY'},
'1608270':{'en': 'Madison, WI'},
'1541607':{'en': 'Eugene, OR'},
'1541608':{'en': 'Medford, OR'},
'1616895':{'en': 'Allendale Charter Township, MI'},
'1615444':{'en': 'Lebanon, TN'},
'1516628':{'en': 'Bayville, NY'},
'1516626':{'en': 'Roslyn Heights, NY'},
'1516627':{'en': 'Manhasset, NY'},
'1516624':{'en': 'Oyster Bay, NY'},
'1616897':{'en': 'Lowell, MI'},
'1540953':{'en': 'Blacksburg, VA'},
'1540951':{'en': 'Blacksburg, VA'},
'1417736':{'en': 'Strafford, MO'},
'1502570':{'en': 'Georgetown, KY'},
'1417732':{'en': 'Republic, MO'},
'1502574':{'en': 'Louisville, KY'},
'1417739':{'en': 'Kimberling City, MO'},
'1615445':{'en': 'Nashville, TN'},
'1574246':{'en': 'South Bend, IN'},
'1561558':{'en': 'Boca Raton, FL'},
'1561509':{'en': 'Boynton Beach, FL'},
'1419873':{'en': 'Perrysburg, OH'},
'1419872':{'en': 'Perrysburg, OH'},
'1419874':{'en': 'Perrysburg, OH'},
'1419877':{'en': 'Whitehouse, OH'},
'1419878':{'en': 'Waterville, OH'},
'1570253':{'en': 'Honesdale, PA'},
'1469467':{'en': 'Plano, TX'},
'1413748':{'en': 'Springfield, MA'},
'1413298':{'en': 'Stockbridge, MA'},
'1586274':{'en': 'Sterling Heights, MI'},
'1413743':{'en': 'Adams, MA'},
'1413747':{'en': 'Springfield, MA'},
'1413746':{'en': 'Springfield, MA'},
'1517393':{'en': 'Lansing, MI'},
'1517394':{'en': 'Lansing, MI'},
'1580822':{'en': 'Okeene, OK'},
'1479484':{'en': 'Fort Smith, AR'},
'1580824':{'en': 'Waynoka, OK'},
'1425562':{'en': 'Bellevue, WA'},
'1602749':{'en': 'Phoenix, AZ'},
'1616752':{'en': 'Grand Rapids, MI'},
'1616975':{'en': 'Grand Rapids, MI'},
'1423547':{'en': 'Elizabethton, TN'},
'1514848':{'en': 'Montreal, QC'},
'1514849':{'en': 'Montreal, QC'},
'1616754':{'en': 'Greenville, MI'},
'1514844':{'en': 'Montreal, QC'},
'1514845':{'en': 'Montreal, QC'},
'1514846':{'en': 'Montreal, QC'},
'1514847':{'en': 'Montreal, QC'},
'1514840':{'en': 'Montreal, QC'},
'1602296':{'en': 'Phoenix, AZ'},
'1514842':{'en': 'Montreal, QC'},
'1514843':{'en': 'Montreal, QC'},
'1415814':{'en': 'San Francisco, CA'},
'1512651':{'en': 'Austin, TX'},
'1423543':{'en': 'Elizabethton, TN'},
'1507872':{'en': 'Minneota, MN'},
'1510704':{'en': 'Berkeley, CA'},
'1519829':{'en': 'Guelph, ON'},
'1608987':{'en': 'Mineral Point, WI'},
'1519821':{'en': 'Guelph, ON'},
'1519823':{'en': 'Guelph, ON'},
'1519822':{'en': 'Guelph, ON'},
'1519825':{'en': 'Wheatley, ON'},
'1519824':{'en': 'Guelph, ON'},
'1519827':{'en': 'Guelph, ON'},
'1519826':{'en': 'Guelph, ON'},
'1585554':{'en': 'Rushville, NY'},
'1412963':{'en': 'Pittsburgh, PA'},
'1573596':{'en': 'Fort Leonard Wood, MO'},
'1418325':{'en': u('Sainte-Anne-de-la-P\u00e9rade, QC')},
'1423733':{'en': 'Sneedville, TN'},
'1423884':{'en': 'Vonore, TN'},
'1415600':{'en': 'San Francisco, CA'},
'1423886':{'en': 'Signal Mountain, TN'},
'1418274':{'en': 'Normandin, QC'},
'1418275':{'en': 'Roberval, QC'},
'1512440':{'en': 'Austin, TX'},
'1415357':{'en': 'San Francisco, CA'},
'1415359':{'en': 'San Francisco, CA'},
'1512448':{'en': 'Austin, TX'},
'1559891':{'en': 'Selma, CA'},
'1559896':{'en': 'Selma, CA'},
'1559897':{'en': 'Kingsburg, CA'},
'1610430':{'en': 'West Chester, PA'},
'1605717':{'en': 'Spearfish, SD'},
'1605716':{'en': 'Rapid City, SD'},
'1605719':{'en': 'Rapid City, SD'},
'1605718':{'en': 'Rapid City, SD'},
'1603654':{'en': 'Wilton, NH'},
'1610433':{'en': 'Allentown, PA'},
'1603650':{'en': 'Lebanon, NH'},
'1603653':{'en': 'Lebanon, NH'},
'1504246':{'en': 'New Orleans, LA'},
'1504245':{'en': 'New Orleans, LA'},
'1504244':{'en': 'New Orleans, LA'},
'1504242':{'en': 'New Orleans, LA'},
'1504241':{'en': 'New Orleans, LA'},
'1610435':{'en': 'Allentown, PA'},
'1609628':{'en': 'Woodbine, NJ'},
'1610436':{'en': 'West Chester, PA'},
'1512628':{'en': 'Austin, TX'},
'1559855':{'en': 'Auberry, CA'},
'1601774':{'en': 'Union, MS'},
'1502375':{'en': 'Louisville, KY'},
'1440886':{'en': 'Cleveland, OH'},
'1440887':{'en': 'Cleveland, OH'},
'1440884':{'en': 'Cleveland, OH'},
'1440885':{'en': 'Cleveland, OH'},
'1540387':{'en': 'Salem, VA'},
'1540389':{'en': 'Salem, VA'},
'1440888':{'en': 'Cleveland, OH'},
'1419278':{'en': 'Deshler, OH'},
'1520458':{'en': 'Sierra Vista, AZ'},
'1520459':{'en': 'Sierra Vista, AZ'},
'1520455':{'en': 'Sonoita, AZ'},
'1520456':{'en': 'Huachuca City, AZ'},
'1520457':{'en': 'Tombstone, AZ'},
'1520452':{'en': 'Sierra Vista, AZ'},
'1425793':{'en': 'Renton, WA'},
'1559237':{'en': 'Fresno, CA'},
'1559230':{'en': 'Fresno, CA'},
'1559233':{'en': 'Fresno, CA'},
'1507263':{'en': 'Cannon Falls, MN'},
'1573346':{'en': 'Camdenton, MO'},
'1573341':{'en': 'Rolla, MO'},
'1573614':{'en': 'Dexter, MO'},
'1573348':{'en': 'Osage Beach, MO'},
'1604585':{'en': 'Surrey, BC'},
'1608924':{'en': 'Barneveld, WI'},
'1515532':{'en': 'Clarion, IA'},
'1615699':{'en': 'Red Boiling Spgs, TN'},
'1603968':{'en': 'Ashland, NH'},
'1520670':{'en': 'Tucson, AZ'},
'1574967':{'en': 'Flora, IN'},
'1510879':{'en': 'Oakland, CA'},
'1417924':{'en': 'Mansfield, MO'},
'1417926':{'en': 'Mountain Grove, MO'},
'1425814':{'en': 'Kirkland, WA'},
'1502942':{'en': 'Fort Knox, KY'},
'1608297':{'en': 'Montello, WI'},
'1408782':{'en': 'Morgan Hill, CA'},
'1608296':{'en': 'Westfield, WI'},
'1505681':{'en': 'Albuquerque, NM'},
'1606929':{'en': 'Ashland, KY'},
'1606928':{'en': 'Ashland, KY'},
'1610317':{'en': 'Bethlehem, PA'},
'1603964':{'en': 'North Hampton, NH'},
'1610645':{'en': 'Wynnewood, PA'},
'1610648':{'en': 'Paoli, PA'},
'1480970':{'en': 'Scottsdale, AZ'},
'1613841':{'en': u('Orl\u00e9ans, ON')},
'1613842':{'en': 'Ottawa, ON'},
'1617349':{'en': 'Cambridge, MA'},
'1617348':{'en': 'Boston, MA'},
'1617345':{'en': 'Boston, MA'},
'1604998':{'en': 'North Vancouver, BC'},
'1501364':{'en': 'Little Rock, AR'},
'1409783':{'en': 'Vidor, TX'},
'1409787':{'en': 'Hemphill, TX'},
'1410658':{'en': 'Rising Sun, MD'},
'1410659':{'en': 'Baltimore, MD'},
'1503566':{'en': 'Salem, OR'},
'1410654':{'en': 'Owings Mills, MD'},
'1410655':{'en': 'Randallstown, MD'},
'1410653':{'en': 'Pikesville, MD'},
'1503561':{'en': 'Salem, OR'},
'1410651':{'en': 'Princess Anne, MD'},
'1540965':{'en': 'Covington, VA'},
'1559539':{'en': 'Springville, CA'},
'1604584':{'en': 'Surrey, BC'},
'1540962':{'en': 'Covington, VA'},
'1604990':{'en': 'North Vancouver, BC'},
'1541416':{'en': 'Prineville, OR'},
'1541410':{'en': 'Bend, OR'},
'1541412':{'en': 'Brookings, OR'},
'1616949':{'en': 'Grand Rapids, MI'},
'1434485':{'en': 'Lynchburg, VA'},
'1585335':{'en': 'Dansville, NY'},
'1602358':{'en': 'Phoenix, AZ'},
'1512912':{'en': 'Austin, TX'},
'1602353':{'en': 'Phoenix, AZ'},
'1602354':{'en': 'Phoenix, AZ'},
'1435687':{'en': 'Huntington, UT'},
'1613564':{'en': 'Ottawa, ON'},
'1435688':{'en': 'St. George, UT'},
'1510732':{'en': 'Hayward, CA'},
'1575762':{'en': 'Clovis, NM'},
'1575763':{'en': 'Clovis, NM'},
'1575769':{'en': 'Clovis, NM'},
'1513376':{'en': 'Cincinnati, OH'},
'1608723':{'en': 'Lancaster, WI'},
'1501305':{'en': 'Searcy, AR'},
'1440576':{'en': 'Jefferson, OH'},
'1440572':{'en': 'Strongsville, OH'},
'1510573':{'en': 'Fremont, CA'},
'1502968':{'en': 'Louisville, KY'},
'1502969':{'en': 'Louisville, KY'},
'1502964':{'en': 'Louisville, KY'},
'1502966':{'en': 'Louisville, KY'},
'1502961':{'en': 'Louisville, KY'},
'1502962':{'en': 'Louisville, KY'},
'1520546':{'en': 'Tucson, AZ'},
'1604677':{'en': 'Vancouver, BC'},
'1478218':{'en': 'Perry, GA'},
'1478746':{'en': 'Macon, GA'},
'1575585':{'en': 'Tularosa, NM'},
'1575586':{'en': 'Questa, NM'},
'1478745':{'en': 'Macon, GA'},
'1478742':{'en': 'Macon, GA'},
'1478743':{'en': 'Macon, GA'},
'1478741':{'en': 'Macon, GA'},
'1614221':{'en': 'Columbus, OH'},
'1614220':{'en': 'Columbus, OH'},
'1614223':{'en': 'Columbus, OH'},
'1450429':{'en': 'Beauharnois, QC'},
'1509216':{'en': 'Spokane, WA'},
'1450937':{'en': 'Laval, QC'},
'1450424':{'en': 'Vaudreuil-Dorion, QC'},
'1450427':{'en': 'Sainte-Martine, QC'},
'1450934':{'en': 'Laval, QC'},
'1450933':{'en': 'Laval, QC'},
'1450932':{'en': 'Repentigny, QC'},
'1501280':{'en': 'Little Rock, AR'},
'1615254':{'en': 'Nashville, TN'},
'1585563':{'en': 'Rochester, NY'},
'1416724':{'en': 'Scarborough, ON'},
'1530283':{'en': 'Quincy, CA'},
'1510397':{'en': 'Hayward, CA'},
'1450687':{'en': 'Chomedey, QC'},
'1450686':{'en': 'Chomedey, QC'},
'1414831':{'en': 'Milwaukee, WI'},
'1563823':{'en': 'Davenport, IA'},
'1520868':{'en': 'Florence, AZ'},
'1608249':{'en': 'Madison, WI'},
'1608246':{'en': 'Madison, WI'},
'1607967':{'en': 'Bainbridge, NY'},
'1608244':{'en': 'Madison, WI'},
'1607965':{'en': 'Edmeston, NY'},
'1416544':{'en': 'Toronto, ON'},
'1608243':{'en': 'Madison, WI'},
'1608240':{'en': 'Madison, WI'},
'1608241':{'en': 'Madison, WI'},
'1585697':{'en': 'Rochester, NY'},
'1518581':{'en': 'Saratoga Springs, NY'},
'1509234':{'en': 'Connell, WA'},
'1605528':{'en': 'Hartford, SD'},
'1615868':{'en': 'Madison, TN'},
'1504471':{'en': 'Kenner, LA'},
'1615865':{'en': 'Madison, TN'},
'1615867':{'en': 'Murfreesboro, TN'},
'1615860':{'en': 'Madison, TN'},
'1615862':{'en': 'Nashville, TN'},
'1418392':{'en': 'New Richmond, QC'},
'1418397':{'en': 'Saint-Joseph-de-Beauce, QC'},
'1414764':{'en': 'Oak Creek, WI'},
'1414763':{'en': 'Milwaukee, WI'},
'1414760':{'en': 'Milwaukee, WI'},
'1414768':{'en': 'Oak Creek, WI'},
'1541973':{'en': 'Medford, OR'},
'1604929':{'en': 'North Vancouver, BC'},
'1604922':{'en': 'West Vancouver, BC'},
'1604921':{'en': 'West Vancouver, BC'},
'1604926':{'en': 'West Vancouver, BC'},
'1604925':{'en': 'West Vancouver, BC'},
'1604924':{'en': 'North Vancouver, BC'},
'1614473':{'en': 'Columbus, OH'},
'1614475':{'en': 'Columbus, OH'},
'1574753':{'en': 'Logansport, IN'},
'1561393':{'en': 'Boca Raton, FL'},
'1614476':{'en': 'Columbus, OH'},
'1605928':{'en': 'Parkston, SD'},
'1502363':{'en': 'Louisville, KY'},
'1614263':{'en': 'Columbus, OH'},
'1423279':{'en': 'Blountville, TN'},
'1610782':{'en': 'Allentown, PA'},
'1610783':{'en': 'King of Prussia, PA'},
'1613478':{'en': 'Tweed, ON'},
'1432229':{'en': 'Presidio, TX'},
'1613473':{'en': 'Madoc, ON'},
'1613472':{'en': 'Marmora, ON'},
'1613475':{'en': 'Brighton, ON'},
'1613476':{'en': 'Picton, ON'},
'1612788':{'en': 'Minneapolis, MN'},
'1435946':{'en': 'Garden City, UT'},
'1614801':{'en': 'Grove City, OH'},
'1612781':{'en': 'Minneapolis, MN'},
'1480585':{'en': 'Scottsdale, AZ'},
'1614850':{'en': 'Hilliard, OH'},
'1516420':{'en': 'Farmingdale, NY'},
'1608873':{'en': 'Stoughton, WI'},
'1504818':{'en': 'New Orleans, LA'},
'1609838':{'en': 'Trenton, NJ'},
'1520721':{'en': 'Tucson, AZ'},
'1501821':{'en': 'Little Rock, AR'},
'1610872':{'en': 'Chester, PA'},
'1610873':{'en': 'Downingtown, PA'},
'1610874':{'en': 'Chester, PA'},
'1609835':{'en': 'Willingboro, NJ'},
'1573406':{'en': 'Hannibal, MO'},
'1613789':{'en': 'Ottawa, ON'},
'1540622':{'en': 'Front Royal, VA'},
'1540626':{'en': 'Pembroke, VA'},
'1540972':{'en': 'Locust Grove, VA'},
'1540977':{'en': 'Roanoke, VA'},
'1570278':{'en': 'Montrose, PA'},
'1610921':{'en': 'Reading, PA'},
'1570271':{'en': 'Danville, PA'},
'1570270':{'en': 'Wilkes-Barre, PA'},
'1570275':{'en': 'Danville, PA'},
'1612259':{'en': 'Minneapolis, MN'},
'1586784':{'en': 'Armada, MI'},
'1510498':{'en': 'Fremont, CA'},
'1434542':{'en': 'Charlotte Ct Hse, VA'},
'1510490':{'en': 'Fremont, CA'},
'1510494':{'en': 'Fremont, CA'},
'1514866':{'en': 'Montreal, QC'},
'1514861':{'en': 'Montreal, QC'},
'1412464':{'en': 'Homestead, PA'},
'1514868':{'en': 'Montreal, QC'},
'1612436':{'en': 'Minneapolis, MN'},
'1616954':{'en': 'Grand Rapids, MI'},
'1503792':{'en': 'Gervais, OR'},
'1616956':{'en': 'Grand Rapids, MI'},
'1616774':{'en': 'Grand Rapids, MI'},
'1616776':{'en': 'Grand Rapids, MI'},
'1608744':{'en': 'Cuba City, WI'},
'1616772':{'en': 'Zeeland, MI'},
'1510724':{'en': 'Pinole, CA'},
'1510728':{'en': 'Hayward, CA'},
'1519843':{'en': 'Fergus, ON'},
'1519842':{'en': 'Tillsonburg, ON'},
'1519846':{'en': 'Elora, ON'},
'1519845':{'en': 'Wyoming, ON'},
'1507896':{'en': 'Houston, MN'},
'1507895':{'en': 'La Crescent, MN'},
'1519848':{'en': 'Arthur, ON'},
'1507893':{'en': 'Winnebago, MN'},
'1570988':{'en': 'Sunbury, PA'},
'1610925':{'en': 'Kennett Square, PA'},
'1606473':{'en': 'Greenup, KY'},
'1561210':{'en': 'Boca Raton, FL'},
'1575935':{'en': 'Clovis, NM'},
'1410871':{'en': 'Westminster, MD'},
'1514398':{'en': 'Montreal, QC'},
'1612925':{'en': 'Minneapolis, MN'},
'1612926':{'en': 'Minneapolis, MN'},
'1612920':{'en': 'Minneapolis, MN'},
'1612922':{'en': 'Minneapolis, MN'},
'1514392':{'en': 'Montreal, QC'},
'1514393':{'en': 'Montreal, QC'},
'1514395':{'en': 'Montreal, QC'},
'1514396':{'en': 'Montreal, QC'},
'1514397':{'en': 'Montreal, QC'},
'1607773':{'en': 'Binghamton, NY'},
'1435723':{'en': 'Brigham City, UT'},
'1607771':{'en': 'Binghamton, NY'},
'1416398':{'en': 'North York, ON'},
'1435722':{'en': 'Roosevelt, UT'},
'1518458':{'en': 'Albany, NY'},
'1416391':{'en': 'North York, ON'},
'1416393':{'en': 'Toronto, ON'},
'1416392':{'en': 'Toronto, ON'},
'1512420':{'en': 'Austin, TX'},
'1609631':{'en': 'Trenton, NJ'},
'1519265':{'en': 'Guelph, ON'},
'1415379':{'en': 'San Francisco, CA'},
'1423869':{'en': 'Harrogate, TN'},
'1604580':{'en': 'Surrey, BC'},
'1423867':{'en': 'Chattanooga, TN'},
'1418253':{'en': u('Vall\u00e9e-Jonction, QC')},
'1415371':{'en': 'San Francisco, CA'},
'1423710':{'en': 'Chattanooga, TN'},
'1519268':{'en': 'Dorchester, ON'},
'1514642':{'en': 'Pointe-aux-Trembles, QC'},
'1423878':{'en': 'Bristol, TN'},
'1519271':{'en': 'Stratford, ON'},
'1530547':{'en': 'Palo Cedro, CA'},
'1530546':{'en': 'Kings Beach, CA'},
'1530544':{'en': 'South Lake Tahoe, CA'},
'1530543':{'en': 'South Lake Tahoe, CA'},
'1530542':{'en': 'South Lake Tahoe, CA'},
'1530541':{'en': 'South Lake Tahoe, CA'},
'1605734':{'en': 'Chamberlain, SD'},
'1509536':{'en': 'Spokane, WA'},
'1604589':{'en': 'Surrey, BC'},
'1509534':{'en': 'Spokane, WA'},
'1509535':{'en': 'Spokane, WA'},
'1509532':{'en': 'Spokane, WA'},
'1450741':{'en': 'Saint-Jean-sur-Richelieu, QC'},
'1450742':{'en': 'Sorel, QC'},
'1450743':{'en': 'Sorel, QC'},
'1603893':{'en': 'Salem, NH'},
'1450218':{'en': 'Vaudreuil-Dorion, QC'},
'1603891':{'en': 'Nashua, NH'},
'1603673':{'en': 'Milford, NH'},
'1603894':{'en': 'Salem, NH'},
'1603895':{'en': 'Raymond, NH'},
'1508775':{'en': 'Hyannis, MA'},
'1585232':{'en': 'Rochester, NY'},
'1508771':{'en': 'Hyannis, MA'},
'1508770':{'en': 'Worcester, MA'},
'1512392':{'en': 'San Marcos, TX'},
'1512393':{'en': 'San Marcos, TX'},
'1512391':{'en': 'Austin, TX'},
'1512396':{'en': 'San Marcos, TX'},
'1512394':{'en': 'Austin, TX'},
'1508778':{'en': 'Hyannis, MA'},
'1604231':{'en': 'Richmond, BC'},
'1580223':{'en': 'Ardmore, OK'},
'1419251':{'en': 'Toledo, OH'},
'1419253':{'en': 'Marengo, OH'},
'1416972':{'en': 'Toronto, ON'},
'1419255':{'en': 'Toledo, OH'},
'1416977':{'en': 'Toronto, ON'},
'1501562':{'en': 'Little Rock, AR'},
'1416979':{'en': 'Toronto, ON'},
'1419258':{'en': 'Antwerp, OH'},
'1540366':{'en': 'Roanoke, VA'},
'1615323':{'en': 'Portland, TN'},
'1501568':{'en': 'Little Rock, AR'},
'1540362':{'en': 'Roanoke, VA'},
'1479717':{'en': 'Springdale, AR'},
'1580227':{'en': 'Fairview, OK'},
'1479243':{'en': 'Mena, AR'},
'1606878':{'en': 'London, KY'},
'1563585':{'en': 'Dubuque, IA'},
'1563584':{'en': 'Dubuque, IA'},
'1563583':{'en': 'Dubuque, IA'},
'1563582':{'en': 'Dubuque, IA'},
'1573368':{'en': 'Rolla, MO'},
'1608221':{'en': 'Madison, WI'},
'1573364':{'en': 'Rolla, MO'},
'1573365':{'en': 'Lake Ozark, MO'},
'1414536':{'en': 'Milwaukee, WI'},
'1414535':{'en': 'Milwaukee, WI'},
'1563588':{'en': 'Dubuque, IA'},
'1608224':{'en': 'Madison, WI'},
'1561981':{'en': 'Boca Raton, FL'},
'1425837':{'en': 'Issaquah, WA'},
'1605399':{'en': 'Rapid City, SD'},
'1425831':{'en': 'North Bend, WA'},
'1561989':{'en': 'Boca Raton, FL'},
'1561988':{'en': 'Boca Raton, FL'},
'1419660':{'en': 'Norwalk, OH'},
'1605397':{'en': 'Groton, SD'},
'1419663':{'en': 'Norwalk, OH'},
'1601693':{'en': 'Meridian, MS'},
'1419668':{'en': 'Norwalk, OH'},
'1601631':{'en': 'Vicksburg, MS'},
'1601634':{'en': 'Vicksburg, MS'},
'1601635':{'en': 'Decatur, MS'},
'1601636':{'en': 'Vicksburg, MS'},
'1605996':{'en': 'Mitchell, SD'},
'1409423':{'en': 'Kirbyville, TX'},
'1503408':{'en': 'Portland, OR'},
'1507534':{'en': 'Plainview, MN'},
'1607664':{'en': 'Bath, NY'},
'1507536':{'en': 'Rochester, MN'},
'1507537':{'en': 'Marshall, MN'},
'1507247':{'en': 'Tyler, MN'},
'1507532':{'en': 'Marshall, MN'},
'1507533':{'en': 'Stewartville, MN'},
'1614497':{'en': 'Columbus, OH'},
'1610667':{'en': 'Bala Cynwyd, PA'},
'1614492':{'en': 'Columbus, OH'},
'1610660':{'en': 'Bala Cynwyd, PA'},
'1480917':{'en': 'Chandler, AZ'},
'1435864':{'en': 'Delta, UT'},
'1613646':{'en': 'Cobden, ON'},
'1617364':{'en': 'Hyde Park, MA'},
'1617367':{'en': 'Boston, MA'},
'1614297':{'en': 'Columbus, OH'},
'1605724':{'en': 'Armour, SD'},
'1605725':{'en': 'Aberdeen, SD'},
'1601477':{'en': 'Ellisville, MS'},
'1410638':{'en': 'Bel Air, MD'},
'1503548':{'en': 'Portland, OR'},
'1562986':{'en': 'Long Beach, CA'},
'1562987':{'en': 'Long Beach, CA'},
'1409769':{'en': 'Vidor, TX'},
'1519679':{'en': 'London, ON'},
'1409765':{'en': 'Galveston, TX'},
'1410632':{'en': 'Snow Hill, MD'},
'1410633':{'en': 'Baltimore, MD'},
'1410634':{'en': 'Ridgely, MD'},
'1410635':{'en': 'New Windsor, MD'},
'1503547':{'en': 'Hillsboro, OR'},
'1503546':{'en': 'Portland, OR'},
'1613594':{'en': 'Ottawa, ON'},
'1450774':{'en': 'Saint-Hyacinthe, QC'},
'1509545':{'en': 'Pasco, WA'},
'1516745':{'en': 'Garden City, NY'},
'1450776':{'en': 'Granby, QC'},
'1503892':{'en': 'Portland, OR'},
'1516897':{'en': 'Long Beach, NY'},
'1606364':{'en': 'Annville, KY'},
'1503897':{'en': 'Mill City, OR'},
'1613590':{'en': u('Orl\u00e9ans, ON')},
'1616896':{'en': 'Hudsonville, MI'},
'1503894':{'en': 'Portland, OR'},
'1613591':{'en': 'Kanata, ON'},
'1580470':{'en': 'Duncan, OK'},
'1607587':{'en': 'Alfred, NY'},
'1418538':{'en': 'Havre-Saint-Pierre, QC'},
'1418824':{'en': u('Ch\u00e2teau-Richer, QC')},
'1418827':{'en': u('Sainte-Anne-de-Beaupr\u00e9, QC')},
'1418534':{'en': 'Bonaventure, QC'},
'1519675':{'en': 'London, ON'},
'1602455':{'en': 'Phoenix, AZ'},
'1580497':{'en': 'Cheyenne, OK'},
'1580326':{'en': 'Hugo, OK'},
'1580327':{'en': 'Alva, OK'},
'1580492':{'en': 'Elgin, OK'},
'1580323':{'en': 'Clinton, OK'},
'1575748':{'en': 'Artesia, NM'},
'1508765':{'en': 'Southbridge, MA'},
'1575742':{'en': 'Clovis, NM'},
'1469232':{'en': 'Dallas, TX'},
'1570517':{'en': 'Stroudsburg, PA'},
'1575746':{'en': 'Artesia, NM'},
'1513351':{'en': 'Cincinnati, OH'},
'1513353':{'en': 'Cleves, OH'},
'1513352':{'en': 'Cincinnati, OH'},
'1513354':{'en': 'Cincinnati, OH'},
'1513357':{'en': 'Cincinnati, OH'},
'1508761':{'en': 'Attleboro, MA'},
'1440519':{'en': 'Solon, OH'},
'1501368':{'en': 'Searcy, AR'},
'1518729':{'en': 'Albany, NY'},
'1518725':{'en': 'Gloversville, NY'},
'1501362':{'en': 'Heber Springs, AR'},
'1417472':{'en': 'Granby, MO'},
'1434975':{'en': 'Charlottesville, VA'},
'1434974':{'en': 'Charlottesville, VA'},
'1517278':{'en': 'Coldwater, MI'},
'1517279':{'en': 'Coldwater, MI'},
'1434971':{'en': 'Charlottesville, VA'},
'1434970':{'en': 'Charlottesville, VA'},
'1434973':{'en': 'Charlottesville, VA'},
'1434972':{'en': 'Charlottesville, VA'},
'1517272':{'en': 'Lansing, MI'},
'1510553':{'en': 'Oakland, CA'},
'1434979':{'en': 'Charlottesville, VA'},
'1434978':{'en': 'Charlottesville, VA'},
'1616235':{'en': 'Grand Rapids, MI'},
'1616546':{'en': 'Holland, MI'},
'1616233':{'en': 'Grand Rapids, MI'},
'1603463':{'en': 'Deerfield, NH'},
'1603466':{'en': 'Gorham, NH'},
'1603465':{'en': 'Hollis, NH'},
'1603464':{'en': 'Hillsboro, NH'},
'1540869':{'en': 'Stephens City, VA'},
'1518589':{'en': 'Tannersville, NY'},
'1509235':{'en': 'Cheney, WA'},
'1518580':{'en': 'Saratoga Springs, NY'},
'1518583':{'en': 'Saratoga Springs, NY'},
'1518585':{'en': 'Ticonderoga, NY'},
'1518584':{'en': 'Saratoga Springs, NY'},
'1518587':{'en': 'Saratoga Springs, NY'},
'1509232':{'en': 'Spokane, WA'},
'1614491':{'en': 'Columbus, OH'},
'1603736':{'en': 'Epsom, NH'},
'1614754':{'en': 'Columbus, OH'},
'1416703':{'en': 'Toronto, ON'},
'1416701':{'en': 'Scarborough, ON'},
'1501791':{'en': 'N Little Rock, AR'},
'1501796':{'en': 'Vilonia, AR'},
'1501794':{'en': 'Benton, AR'},
'1434202':{'en': 'Charlottesville, VA'},
'1434200':{'en': 'Lynchburg, VA'},
'1517852':{'en': 'Nashville, MI'},
'1517851':{'en': 'Stockbridge, MI'},
'1478237':{'en': 'Swainsboro, GA'},
'1562938':{'en': 'Long Beach, CA'},
'1519986':{'en': 'Markdale, ON'},
'1519455':{'en': 'London, ON'},
'1519457':{'en': 'London, ON'},
'1519451':{'en': 'London, ON'},
'1478238':{'en': 'Macon, GA'},
'1519453':{'en': 'London, ON'},
'1603286':{'en': 'Tilton, NH'},
'1419394':{'en': 'St. Marys, OH'},
'1419396':{'en': 'Carey, OH'},
'1419399':{'en': 'Paulding, OH'},
'1608739':{'en': 'Muscoda, WI'},
'1509493':{'en': 'White Salmon, WA'},
'1509949':{'en': 'Yakima, WA'},
'1509946':{'en': 'Richland, WA'},
'1608222':{'en': 'Madison, WI'},
'1608223':{'en': 'Madison, WI'},
'1509943':{'en': 'Richland, WA'},
'1509942':{'en': 'Richland, WA'},
'1570586':{'en': 'Clarks Summit, PA'},
'1416966':{'en': 'Toronto, ON'},
'1508548':{'en': 'Falmouth, MA'},
'1608826':{'en': 'Madison, WI'},
'1615443':{'en': 'Lebanon, TN'},
'1519672':{'en': 'London, ON'},
'1519673':{'en': 'London, ON'},
'1508540':{'en': 'Falmouth, MA'},
'1508541':{'en': 'Franklin, MA'},
'1519676':{'en': 'Blenheim, ON'},
'1508543':{'en': 'Foxboro, MA'},
'1520408':{'en': 'Tucson, AZ'},
'1504456':{'en': 'Metairie, LA'},
'1419242':{'en': 'Toledo, OH'},
'1504454':{'en': 'Metairie, LA'},
'1504455':{'en': 'Metairie, LA'},
'1419243':{'en': 'Toledo, OH'},
'1615332':{'en': 'Nashville, TN'},
'1412281':{'en': 'Pittsburgh, PA'},
'1416961':{'en': 'Toronto, ON'},
'1412288':{'en': 'Pittsburgh, PA'},
'1520229':{'en': 'Tucson, AZ'},
'1520225':{'en': 'Tucson, AZ'},
'1604905':{'en': 'Whistler, BC'},
'1604904':{'en': 'North Vancouver, BC'},
'1613592':{'en': 'Kanata, ON'},
'1614799':{'en': 'Dublin, OH'},
'1614798':{'en': 'Dublin, OH'},
'1614794':{'en': 'Westerville, OH'},
'1614791':{'en': 'Dublin, OH'},
'1614793':{'en': 'Dublin, OH'},
'1614792':{'en': 'Dublin, OH'},
'1541998':{'en': 'Junction City, OR'},
'1541994':{'en': 'Lincoln City, OR'},
'1541995':{'en': 'Harrisburg, OR'},
'1541996':{'en': 'Lincoln City, OR'},
'1541997':{'en': 'Florence, OR'},
'1563852':{'en': 'Cascade, IA'},
'1615847':{'en': 'Old Hickory, TN'},
'1615848':{'en': 'Murfreesboro, TN'},
'1615849':{'en': 'Murfreesboro, TN'},
'1410289':{'en': 'Ocean City, MD'},
'1606889':{'en': 'Prestonsburg, KY'},
'1606886':{'en': 'Prestonsburg, KY'},
'1410280':{'en': 'Annapolis, MD'},
'1480615':{'en': 'Mesa, AZ'},
'1480614':{'en': 'Scottsdale, AZ'},
'1410287':{'en': 'North East, MD'},
'1480610':{'en': 'Mesa, AZ'},
'1559665':{'en': 'Chowchilla, CA'},
'1559664':{'en': 'Madera, CA'},
'1559662':{'en': 'Madera, CA'},
'1559661':{'en': 'Madera, CA'},
'1423296':{'en': 'Chattanooga, TN'},
'1506327':{'en': 'Minto, NB'},
'1506325':{'en': 'Woodstock, NB'},
'1573793':{'en': 'Iberia, MO'},
'1613264':{'en': 'Perth, ON'},
'1506328':{'en': 'Woodstock, NB'},
'1601288':{'en': 'Hattiesburg, MS'},
'1501803':{'en': 'Maumelle, AR'},
'1435789':{'en': 'Vernal, UT'},
'1440748':{'en': 'Grafton, OH'},
'1435787':{'en': 'Logan, UT'},
'1435781':{'en': 'Vernal, UT'},
'1605823':{'en': 'McLaughlin, SD'},
'1435783':{'en': 'Kamas, UT'},
'1559594':{'en': 'Exeter, CA'},
'1417888':{'en': 'Springfield, MO'},
'1417889':{'en': 'Springfield, MO'},
'1417886':{'en': 'Springfield, MO'},
'1417887':{'en': 'Springfield, MO'},
'1417885':{'en': 'Springfield, MO'},
'1417882':{'en': 'Springfield, MO'},
'1417883':{'en': 'Springfield, MO'},
'1417880':{'en': 'Springfield, MO'},
'1417881':{'en': 'Springfield, MO'},
'1425990':{'en': 'Bellevue, WA'},
'1573422':{'en': 'Vienna, MO'},
'1573426':{'en': 'Rolla, MO'},
'1530899':{'en': 'Chico, CA'},
'1530898':{'en': 'Chico, CA'},
'1530891':{'en': 'Chico, CA'},
'1530893':{'en': 'Chico, CA'},
'1530892':{'en': 'Chico, CA'},
'1530895':{'en': 'Chico, CA'},
'1530894':{'en': 'Chico, CA'},
'1530896':{'en': 'Chico, CA'},
'1417778':{'en': 'Alton, MO'},
'1484875':{'en': 'Exton, PA'},
'1561514':{'en': 'West Palm Beach, FL'},
'1417776':{'en': 'Seneca, MO'},
'1417777':{'en': 'Bolivar, MO'},
'1505476':{'en': 'Santa Fe, NM'},
'1419837':{'en': 'Perrysburg, OH'},
'1505474':{'en': 'Santa Fe, NM'},
'1505473':{'en': 'Santa Fe, NM'},
'1505471':{'en': 'Santa Fe, NM'},
'1505470':{'en': 'Santa Fe, NM'},
'1585467':{'en': 'Rochester, NY'},
'1415441':{'en': 'San Francisco, CA'},
'1609520':{'en': 'Princeton, NJ'},
'1412490':{'en': 'Pittsburgh, PA'},
'1514807':{'en': 'Montreal, QC'},
'1602257':{'en': 'Phoenix, AZ'},
'1602256':{'en': 'Phoenix, AZ'},
'1602255':{'en': 'Phoenix, AZ'},
'1602254':{'en': 'Phoenix, AZ'},
'1602253':{'en': 'Phoenix, AZ'},
'1602252':{'en': 'Phoenix, AZ'},
'1602251':{'en': 'Phoenix, AZ'},
'1516663':{'en': 'Mineola, NY'},
'1575532':{'en': 'Las Cruces, NM'},
'1616935':{'en': 'Grand Haven, MI'},
'1575534':{'en': 'Silver City, NM'},
'1479621':{'en': 'Rogers, AR'},
'1609522':{'en': 'Wildwood, NJ'},
'1541205':{'en': 'Klamath Falls, OR'},
'1541207':{'en': 'Corvallis, OR'},
'1425290':{'en': 'Everett, WA'},
'1519863':{'en': 'Norwich, ON'},
'1519862':{'en': 'Corunna, ON'},
'1413259':{'en': 'Amherst, MA'},
'1413256':{'en': 'Amherst, MA'},
'1413253':{'en': 'Amherst, MA'},
'1409246':{'en': 'Kountze, TX'},
'1562428':{'en': 'Long Beach, CA'},
'1575267':{'en': 'Hatch, NM'},
'1604463':{'en': 'Maple Ridge, BC'},
'1513834':{'en': 'Cincinnati, OH'},
'1513831':{'en': 'Milford, OH'},
'1450582':{'en': 'Repentigny, QC'},
'1450583':{'en': u('Verch\u00e8res, QC')},
'1517913':{'en': 'Lansing Charter Township, MI'},
'1450581':{'en': 'Repentigny, QC'},
'1450586':{'en': 'Lavaltrie, QC'},
'1450587':{'en': u('Contrec\u0153ur, QC')},
'1450585':{'en': 'Repentigny, QC'},
'1607754':{'en': 'Endicott, NY'},
'1607757':{'en': 'Endicott, NY'},
'1450589':{'en': 'L\'Assomption, QC'},
'1518449':{'en': 'Albany, NY'},
'1607753':{'en': 'Cortland, NY'},
'1519245':{'en': 'Strathroy, ON'},
'1604598':{'en': 'Surrey, BC'},
'1604599':{'en': 'Surrey, BC'},
'1604224':{'en': 'Vancouver, BC'},
'1604597':{'en': 'Surrey, BC'},
'1423843':{'en': 'Hixson, TN'},
'1423842':{'en': 'Hixson, TN'},
'1604592':{'en': 'Surrey, BC'},
'1512407':{'en': 'Austin, TX'},
'1423847':{'en': 'Hixson, TN'},
'1604591':{'en': 'Surrey, BC'},
'1601354':{'en': 'Jackson, MS'},
'1605983':{'en': 'Arlington, SD'},
'1519338':{'en': 'Harriston, ON'},
'1601602':{'en': 'Hattiesburg, MS'},
'1509755':{'en': 'Spokane, WA'},
'1604221':{'en': 'Vancouver, BC'},
'1603610':{'en': 'Portsmouth, NH'},
'1450763':{'en': 'Coteau-du-Lac, QC'},
'1508753':{'en': 'Worcester, MA'},
'1508752':{'en': 'Worcester, MA'},
'1508755':{'en': 'Worcester, MA'},
'1508754':{'en': 'Worcester, MA'},
'1508757':{'en': 'Worcester, MA'},
'1508756':{'en': 'Worcester, MA'},
'1508758':{'en': 'Mattapoisett, MA'},
'1508977':{'en': 'Taunton, MA'},
'1502331':{'en': 'Bardstown, KY'},
'1520881':{'en': 'Tucson, AZ'},
'1540344':{'en': 'Roanoke, VA'},
'1540345':{'en': 'Roanoke, VA'},
'1540342':{'en': 'Roanoke, VA'},
'1540343':{'en': 'Roanoke, VA'},
'1540341':{'en': 'Warrenton, VA'},
'1540349':{'en': 'Warrenton, VA'},
'1615309':{'en': 'Brentwood, TN'},
'1419238':{'en': 'Van Wert, OH'},
'1501589':{'en': 'Quitman, AR'},
'1501588':{'en': 'Little Rock, AR'},
'1615301':{'en': 'Nashville, TN'},
'1419232':{'en': 'Van Wert, OH'},
'1615302':{'en': 'Spring Hill, TN'},
'1425235':{'en': 'Renton, WA'},
'1585226':{'en': 'Avon, NY'},
'1585227':{'en': 'Rochester, NY'},
'1585224':{'en': 'Rochester, NY'},
'1585225':{'en': 'Rochester, NY'},
'1585223':{'en': 'Fairport, NY'},
'1585229':{'en': 'Honeoye, NY'},
'1608324':{'en': 'Monroe, WI'},
'1518963':{'en': 'Willsboro, NY'},
'1559274':{'en': 'Fresno, CA'},
'1559275':{'en': 'Fresno, CA'},
'1559276':{'en': 'Fresno, CA'},
'1559277':{'en': 'Fresno, CA'},
'1573308':{'en': 'Rolla, MO'},
'1608326':{'en': 'Prairie du Chien, WI'},
'1573302':{'en': 'Osage Beach, MO'},
'1608323':{'en': 'Arcadia, WI'},
'1515573':{'en': 'Fort Dodge, IA'},
'1515576':{'en': 'Fort Dodge, IA'},
'1608965':{'en': 'Shullsburg, WI'},
'1515574':{'en': 'Fort Dodge, IA'},
'1510429':{'en': 'Union City, CA'},
'1562438':{'en': 'Long Beach, CA'},
'1562439':{'en': 'Long Beach, CA'},
'1604647':{'en': 'Vancouver, BC'},
'1562434':{'en': 'Long Beach, CA'},
'1562343':{'en': 'Long Beach, CA'},
'1562436':{'en': 'Long Beach, CA'},
'1562437':{'en': 'Long Beach, CA'},
'1562432':{'en': 'Long Beach, CA'},
'1562433':{'en': 'Long Beach, CA'},
'1601346':{'en': 'Jackson, MS'},
'1573796':{'en': 'California, MO'},
'1608329':{'en': 'Monroe, WI'},
'1604643':{'en': 'Vancouver, BC'},
'1604864':{'en': 'Abbotsford, BC'},
'1503435':{'en': 'McMinnville, OR'},
'1419647':{'en': 'Spencerville, OH'},
'1503429':{'en': 'Vernonia, OR'},
'1480288':{'en': 'Apache Junction, AZ'},
'1503436':{'en': 'Cannon Beach, OR'},
'1559587':{'en': 'Hanford, CA'},
'1559584':{'en': 'Hanford, CA'},
'1559585':{'en': 'Hanford, CA'},
'1559582':{'en': 'Hanford, CA'},
'1559583':{'en': 'Hanford, CA'},
'1541839':{'en': 'Canyonville, OR'},
'1559589':{'en': 'Hanford, CA'},
'1613628':{'en': 'Eganville, ON'},
'1610701':{'en': 'West Chester, PA'},
'1510351':{'en': 'San Leandro, CA'},
'1613622':{'en': 'Arnprior, ON'},
'1613623':{'en': 'Arnprior, ON'},
'1410612':{'en': 'Edgewood, MD'},
'1409747':{'en': 'Galveston, TX'},
'1409744':{'en': 'Galveston, TX'},
'1503520':{'en': 'Beaverton, OR'},
'1503526':{'en': 'Beaverton, OR'},
'1410614':{'en': 'Baltimore, MD'},
'1503524':{'en': 'Beaverton, OR'},
'1503528':{'en': 'Portland, OR'},
'1410349':{'en': 'Annapolis, MD'},
'1574658':{'en': 'Milford, IN'},
'1423337':{'en': 'Sweetwater, TN'},
'1585964':{'en': 'Hamlin, NY'},
'1423334':{'en': 'Decatur, TN'},
'1423332':{'en': 'Soddy-Daisy, TN'},
'1423339':{'en': 'Cleveland, TN'},
'1423338':{'en': 'Benton, TN'},
'1417967':{'en': 'Houston, MO'},
'1417962':{'en': 'Cabool, MO'},
'1604303':{'en': 'Richmond, BC'},
'1480425':{'en': 'Scottsdale, AZ'},
'1480421':{'en': 'Scottsdale, AZ'},
'1480423':{'en': 'Scottsdale, AZ'},
'1606349':{'en': 'Salyersville, KY'},
'1516876':{'en': 'Westbury, NY'},
'1516872':{'en': 'Valley Stream, NY'},
'1609978':{'en': 'Manahawkin, NJ'},
'1415831':{'en': 'San Francisco, CA'},
'1415830':{'en': 'San Francisco, CA'},
'1415833':{'en': 'San Francisco, CA'},
'1440684':{'en': 'Cleveland, OH'},
'1415834':{'en': 'San Francisco, CA'},
'1415837':{'en': 'San Francisco, CA'},
'1415836':{'en': 'San Francisco, CA'},
'1613336':{'en': 'Northbrook, ON'},
'1613332':{'en': 'Bancroft, ON'},
'1612573':{'en': 'Minneapolis, MN'},
'1610853':{'en': 'Havertown, PA'},
'1540896':{'en': 'Broadway, VA'},
'1501340':{'en': 'Little Rock, AR'},
'1519969':{'en': 'Windsor, ON'},
'1513621':{'en': 'Cincinnati, OH'},
'1610856':{'en': 'Mohnton, PA'},
'1513624':{'en': 'Cincinnati, OH'},
'1610857':{'en': 'Parkesburg, PA'},
'1502921':{'en': 'Shepherdsville, KY'},
'1502690':{'en': 'Louisville, KY'},
'1417345':{'en': 'Buffalo, MO'},
'1417347':{'en': 'Joplin, MO'},
'1502695':{'en': 'Frankfort, KY'},
'1530642':{'en': 'Placerville, CA'},
'1613632':{'en': 'Hawkesbury, ON'},
'1540891':{'en': 'Fredericksburg, VA'},
'1434993':{'en': 'Concord, VA'},
'1434990':{'en': 'Ruckersville, VA'},
'1440743':{'en': 'Cleveland, OH'},
'1450974':{'en': 'Saint-Eustache, QC'},
'1603444':{'en': 'Littleton, NH'},
'1603447':{'en': 'Conway, NH'},
'1503556':{'en': 'Rainier, OR'},
'1410356':{'en': 'Owings Mills, MD'},
'1503554':{'en': 'Newberg, OR'},
'1469742':{'en': 'McKinney, TX'},
'1570538':{'en': 'Watsontown, PA'},
'1570539':{'en': 'Mt Pleasant Mls, PA'},
'1416760':{'en': 'Toronto, ON'},
'1416761':{'en': 'Toronto, ON'},
'1416762':{'en': 'Toronto, ON'},
'1416763':{'en': 'Toronto, ON'},
'1586573':{'en': 'Warren, MI'},
'1416766':{'en': 'Toronto, ON'},
'1416767':{'en': 'Toronto, ON'},
'1416769':{'en': 'Toronto, ON'},
'1580795':{'en': 'Madill, OK'},
'1505346':{'en': 'Albuquerque, NM'},
'1434220':{'en': 'Charlottesville, VA'},
'1519474':{'en': 'London, ON'},
'1414871':{'en': 'Milwaukee, WI'},
'1519472':{'en': 'London, ON'},
'1519473':{'en': 'London, ON'},
'1414875':{'en': 'Milwaukee, WI'},
'1412441':{'en': 'Pittsburgh, PA'},
'1502245':{'en': 'Louisville, KY'},
'1478254':{'en': 'Macon, GA'},
'1502244':{'en': 'Louisville, KY'},
'1417553':{'en': 'Joplin, MO'},
'1515964':{'en': 'Ankeny, IA'},
'1518306':{'en': 'Saratoga Springs, NY'},
'1607256':{'en': 'Ithaca, NY'},
'1515967':{'en': 'Altoona, IA'},
'1416588':{'en': 'Toronto, ON'},
'1515961':{'en': 'Indianola, IA'},
'1515962':{'en': 'Indianola, IA'},
'1515963':{'en': 'Ankeny, IA'},
'1608758':{'en': 'Janesville, WI'},
'1416585':{'en': 'Toronto, ON'},
'1563284':{'en': 'Walcott, IA'},
'1563285':{'en': 'Eldridge, IA'},
'1502240':{'en': 'Louisville, KY'},
'1509968':{'en': 'Ellensburg, WA'},
'1509962':{'en': 'Ellensburg, WA'},
'1509965':{'en': 'Yakima, WA'},
'1509967':{'en': 'West Richland, WA'},
'1509966':{'en': 'Yakima, WA'},
'1508567':{'en': 'Fall River, MA'},
'1519650':{'en': 'Cambridge, ON'},
'1519651':{'en': 'Cambridge, ON'},
'1519656':{'en': 'Wellesley, ON'},
'1519657':{'en': 'London, ON'},
'1415665':{'en': 'San Francisco, CA'},
'1519658':{'en': 'Cambridge, ON'},
'1519659':{'en': 'London, ON'},
'1601892':{'en': 'Crystal Springs, MS'},
'1415661':{'en': 'San Francisco, CA'},
'1504436':{'en': 'Westwego, LA'},
'1415585':{'en': 'San Francisco, CA'},
'1415584':{'en': 'San Francisco, CA'},
'1415239':{'en': 'San Francisco, CA'},
'1415586':{'en': 'San Francisco, CA'},
'1514564':{'en': 'Montreal, QC'},
'1508695':{'en': 'North Attleborough, MA'},
'1508696':{'en': 'Vineyard Haven, MA'},
'1508697':{'en': 'Bridgewater, MA'},
'1508698':{'en': 'Foxboro, MA'},
'1508699':{'en': 'North Attleborough, MA'},
'1585289':{'en': 'Shortsville, NY'},
'1615329':{'en': 'Nashville, TN'},
'1414727':{'en': 'Milwaukee, WI'},
'1602':{'en': 'Arizona'},
'1574533':{'en': 'Goshen, IN'},
'1574537':{'en': 'Goshen, IN'},
'1574534':{'en': 'Goshen, IN'},
'1574535':{'en': 'Goshen, IN'},
'1512218':{'en': 'Round Rock, TX'},
'1609404':{'en': 'Galloway, NJ'},
'1559834':{'en': 'Fowler, CA'},
'1615792':{'en': 'Ashland City, TN'},
'1615793':{'en': 'La Vergne, TN'},
'1615790':{'en': 'Franklin, TN'},
'1615791':{'en': 'Franklin, TN'},
'1615824':{'en': 'Hendersonville, TN'},
'1614235':{'en': 'Columbus, OH'},
'1615794':{'en': 'Franklin, TN'},
'1615799':{'en': 'Fairview, TN'},
'1480632':{'en': 'Gilbert, AZ'},
'1559641':{'en': 'Oakhurst, CA'},
'1530527':{'en': 'Red Bluff, CA'},
'1559645':{'en': 'Madera, CA'},
'1559646':{'en': 'Parlier, CA'},
'1506344':{'en': u('Lam\u00e8que, NB')},
'1613433':{'en': 'Renfrew, ON'},
'1613432':{'en': 'Renfrew, ON'},
'1520207':{'en': 'Tucson, AZ'},
'1520751':{'en': 'Tucson, AZ'},
'1520750':{'en': 'Tucson, AZ'},
'1610526':{'en': 'Bryn Mawr, PA'},
'1610527':{'en': 'Bryn Mawr, PA'},
'1610524':{'en': 'Exton, PA'},
'1610525':{'en': 'Bryn Mawr, PA'},
'1610520':{'en': 'Bryn Mawr, PA'},
'1616957':{'en': 'Grand Rapids, MI'},
'1561289':{'en': 'Boca Raton, FL'},
'1605229':{'en': 'Aberdeen, SD'},
'1540665':{'en': 'Winchester, VA'},
'1419584':{'en': 'Celina, OH'},
'1540667':{'en': 'Winchester, VA'},
'1419586':{'en': 'Celina, OH'},
'1540661':{'en': 'Orange, VA'},
'1443736':{'en': 'Salisbury, MD'},
'1540663':{'en': 'King George, VA'},
'1540662':{'en': 'Winchester, VA'},
'1573443':{'en': 'Columbia, MO'},
'1573442':{'en': 'Columbia, MO'},
'1573441':{'en': 'Columbia, MO'},
'1419589':{'en': 'Mansfield, OH'},
'1573446':{'en': 'Columbia, MO'},
'1573445':{'en': 'Columbia, MO'},
'1606573':{'en': 'Harlan, KY'},
'1614449':{'en': 'Columbus, OH'},
'1417753':{'en': 'Rogersville, MO'},
'1417759':{'en': 'Fair Grove, MO'},
'1425644':{'en': 'Bellevue, WA'},
'1425646':{'en': 'Bellevue, WA'},
'1425641':{'en': 'Bellevue, WA'},
'1425640':{'en': 'Edmonds, WA'},
'1425643':{'en': 'Bellevue, WA'},
'1573582':{'en': 'Mexico, MO'},
'1425649':{'en': 'Bellevue, WA'},
'1505450':{'en': 'Albuquerque, NM'},
'1505453':{'en': 'Albuquerque, NM'},
'1505452':{'en': 'Albuquerque, NM'},
'1505455':{'en': 'Santa Fe, NM'},
'1505454':{'en': 'Las Vegas, NM'},
'1505459':{'en': 'Albuquerque, NM'},
'1425277':{'en': 'Renton, WA'},
'1573581':{'en': 'Mexico, MO'},
'1469916':{'en': 'Dallas, TX'},
'1606756':{'en': 'Augusta, KY'},
'1516466':{'en': 'Great Neck, NY'},
'1410947':{'en': 'Baltimore, MD'},
'1612746':{'en': 'Minneapolis, MN'},
'1606759':{'en': 'Maysville, KY'},
'1602973':{'en': 'Phoenix, AZ'},
'1517483':{'en': 'Lansing, MI'},
'1517482':{'en': 'Lansing, MI'},
'1517485':{'en': 'Lansing, MI'},
'1517484':{'en': 'Lansing, MI'},
'1517487':{'en': 'Lansing, MI'},
'1517486':{'en': 'Blissfield, MI'},
'1517337':{'en': 'East Lansing, MI'},
'1517336':{'en': 'East Lansing, MI'},
'1479394':{'en': 'Mena, AR'},
'1517333':{'en': 'East Lansing, MI'},
'1517332':{'en': 'East Lansing, MI'},
'1510451':{'en': 'Oakland, CA'},
'1479935':{'en': 'Fayetteville, AR'},
'1519565':{'en': 'Bayfield, ON'},
'1425502':{'en': 'Bellevue, WA'},
'1609987':{'en': 'Princeton, NJ'},
'1602279':{'en': 'Phoenix, AZ'},
'1602278':{'en': 'Phoenix, AZ'},
'1602271':{'en': 'Phoenix, AZ'},
'1602273':{'en': 'Phoenix, AZ'},
'1419832':{'en': 'Grand Rapids, OH'},
'1602275':{'en': 'Phoenix, AZ'},
'1602274':{'en': 'Phoenix, AZ'},
'1574256':{'en': 'Mishawaka, IN'},
'1602276':{'en': 'Phoenix, AZ'},
'1418524':{'en': 'Quebec City, QC'},
'1534':{'en': 'Wisconsin'},
'1531':{'en': 'Nebraska'},
'1418833':{'en': 'Levis, QC'},
'1516682':{'en': 'Syosset, NY'},
'1450677':{'en': 'Longueuil, QC'},
'1479648':{'en': 'Fort Smith, AR'},
'1479649':{'en': 'Fort Smith, AR'},
'1609989':{'en': 'Trenton, NJ'},
'1479641':{'en': 'Atkins, AR'},
'1479646':{'en': 'Fort Smith, AR'},
'1570491':{'en': 'Matamoras, PA'},
'1570494':{'en': 'Williamsport, PA'},
'1570945':{'en': 'Factoryville, PA'},
'1418835':{'en': 'Levis, QC'},
'1541222':{'en': 'Springfield, OR'},
'1570942':{'en': 'Nicholson, PA'},
'1570941':{'en': 'Scranton, PA'},
'1409267':{'en': 'Anahuac, TX'},
'1518686':{'en': 'Hoosick Falls, NY'},
'1518689':{'en': 'Albany, NY'},
'1412731':{'en': 'Pittsburgh, PA'},
'1412586':{'en': 'Pittsburgh, PA'},
'1519389':{'en': 'Port Elgin, ON'},
'1616667':{'en': 'Jenison, MI'},
'1515448':{'en': 'Eagle Grove, IA'},
'1585567':{'en': 'Fillmore, NY'},
'1530528':{'en': 'Red Bluff, CA'},
'1616669':{'en': 'Hudsonville, MI'},
'1410896':{'en': 'Delmar, MD'},
'1410897':{'en': 'Annapolis, MD'},
'1603588':{'en': 'Antrim, NH'},
'1603589':{'en': 'Nashua, NH'},
'1502485':{'en': 'Louisville, KY'},
'1502484':{'en': 'Owenton, KY'},
'1450569':{'en': u('Saint-J\u00e9r\u00f4me, QC')},
'1603580':{'en': 'Exeter, NH'},
'1450565':{'en': u('Saint-J\u00e9r\u00f4me, QC')},
'1518464':{'en': 'Albany, NY'},
'1518465':{'en': 'Albany, NY'},
'1518462':{'en': 'Albany, NY'},
'1518463':{'en': 'Albany, NY'},
'1502489':{'en': 'Louisville, KY'},
'1519227':{'en': 'Lucan, ON'},
'1580224':{'en': 'Ardmore, OK'},
'1603632':{'en': 'Enfield, NH'},
'1515887':{'en': 'West Bend, IA'},
'1515885':{'en': 'Bancroft, IA'},
'1603635':{'en': 'Pelham, NH'},
'1615740':{'en': 'Dickson, TN'},
'1501614':{'en': 'Little Rock, AR'},
'1509573':{'en': 'Yakima, WA'},
'1509576':{'en': 'Yakima, WA'},
'1509574':{'en': 'Yakima, WA'},
'1509575':{'en': 'Yakima, WA'},
'1508229':{'en': 'Marlborough, MA'},
'1508228':{'en': 'Nantucket, MA'},
'1508732':{'en': 'Plymouth, MA'},
'1508223':{'en': 'Attleboro, MA'},
'1508730':{'en': 'Fall River, MA'},
'1508224':{'en': 'Plymouth, MA'},
'1508226':{'en': 'Attleboro, MA'},
'1416934':{'en': 'Toronto, ON'},
'1615361':{'en': 'Nashville, TN'},
'1580226':{'en': 'Ardmore, OK'},
'1615367':{'en': 'Nashville, TN'},
'1615366':{'en': 'Nashville, TN'},
'1419213':{'en': 'Toledo, OH'},
'1416932':{'en': 'Toronto, ON'},
'1601982':{'en': 'Jackson, MS'},
'1601981':{'en': 'Jackson, MS'},
'1574642':{'en': 'Goshen, IN'},
'1601987':{'en': 'Jackson, MS'},
'1601984':{'en': 'Jackson, MS'},
'1601985':{'en': 'Ridgeland, MS'},
'1520439':{'en': 'Sierra Vista, AZ'},
'1520432':{'en': 'Bisbee, AZ'},
'1585241':{'en': 'Rochester, NY'},
'1423821':{'en': 'Chattanooga, TN'},
'1585243':{'en': 'Geneseo, NY'},
'1585244':{'en': 'Rochester, NY'},
'1601764':{'en': 'Bay Springs, MS'},
'1423825':{'en': 'Chattanooga, TN'},
'1412635':{'en': 'Pittsburgh, PA'},
'1585248':{'en': 'Pittsford, NY'},
'1609368':{'en': 'Stone Harbor, NJ'},
'1480515':{'en': 'Phoenix, AZ'},
'1573323':{'en': 'Van Buren, MO'},
'1573324':{'en': 'Bowling Green, MO'},
'1573329':{'en': 'Fort Leonard Wood, MO'},
'1573859':{'en': 'Belle, MO'},
'1520696':{'en': 'Tucson, AZ'},
'1515225':{'en': 'West Des Moines, IA'},
'1515224':{'en': 'West Des Moines, IA'},
'1515223':{'en': 'West Des Moines, IA'},
'1515222':{'en': 'West Des Moines, IA'},
'1515221':{'en': 'West Des Moines, IA'},
'1609924':{'en': 'Princeton, NJ'},
'1603229':{'en': 'Concord, NH'},
'1601545':{'en': 'Hattiesburg, MS'},
'1410987':{'en': 'Millersville, MD'},
'1507754':{'en': 'Grand Meadow, MN'},
'1605331':{'en': 'Sioux Falls, SD'},
'1605330':{'en': 'Sioux Falls, SD'},
'1605333':{'en': 'Sioux Falls, SD'},
'1605332':{'en': 'Sioux Falls, SD'},
'1505662':{'en': 'Los Alamos, NM'},
'1605334':{'en': 'Sioux Falls, SD'},
'1505660':{'en': 'Santa Fe, NM'},
'1505661':{'en': 'Los Alamos, NM'},
'1601366':{'en': 'Jackson, MS'},
'1605338':{'en': 'Sioux Falls, SD'},
'1601364':{'en': 'Jackson, MS'},
'1601362':{'en': 'Jackson, MS'},
'1608280':{'en': 'Madison, WI'},
'1507287':{'en': 'Rochester, MN'},
'1507284':{'en': 'Rochester, MN'},
'1507285':{'en': 'Rochester, MN'},
'1507282':{'en': 'Rochester, MN'},
'1507283':{'en': 'Luverne, MN'},
'1507280':{'en': 'Rochester, MN'},
'1507281':{'en': 'Rochester, MN'},
'1603225':{'en': 'Concord, NH'},
'1602258':{'en': 'Phoenix, AZ'},
'1503445':{'en': 'Portland, OR'},
'1507288':{'en': 'Rochester, MN'},
'1507289':{'en': 'Rochester, MN'},
'1559252':{'en': 'Fresno, CA'},
'1559253':{'en': 'Fresno, CA'},
'1541812':{'en': 'Albany, OR'},
'1559256':{'en': 'Fresno, CA'},
'1603227':{'en': 'Concord, NH'},
'1559255':{'en': 'Fresno, CA'},
'1606845':{'en': 'Flemingsburg, KY'},
'1505837':{'en': 'Albuquerque, NM'},
'1512928':{'en': 'Austin, TX'},
'1505598':{'en': 'Kirtland, NM'},
'1501374':{'en': 'Little Rock, AR'},
'1409724':{'en': 'Nederland, TX'},
'1518734':{'en': 'Windham, NY'},
'1410368':{'en': 'Baltimore, MD'},
'1503505':{'en': 'Portland, OR'},
'1410367':{'en': 'Baltimore, MD'},
'1410362':{'en': 'Baltimore, MD'},
'1410363':{'en': 'Owings Mills, MD'},
'1410360':{'en': 'Pasadena, MD'},
'1423317':{'en': 'Morristown, TN'},
'1423318':{'en': 'Morristown, TN'},
'1573674':{'en': 'Licking, MO'},
'1510444':{'en': 'Oakland, CA'},
'1614985':{'en': 'Columbus, OH'},
'1606329':{'en': 'Ashland, KY'},
'1610954':{'en': 'Bethlehem, PA'},
'1415856':{'en': 'San Francisco, CA'},
'1606327':{'en': 'Ashland, KY'},
'1606326':{'en': 'Ashland, KY'},
'1606325':{'en': 'Ashland, KY'},
'1606324':{'en': 'Ashland, KY'},
'1580362':{'en': 'Newkirk, OK'},
'1580363':{'en': 'Blackwell, OK'},
'1609951':{'en': 'Princeton, NJ'},
'1580369':{'en': 'Davis, OK'},
'1609953':{'en': 'Medford, NJ'},
'1510445':{'en': 'Fremont, CA'},
'1604801':{'en': 'Vancouver, BC'},
'1585671':{'en': 'Webster, NY'},
'1613354':{'en': 'Greater Napanee, ON'},
'1506622':{'en': 'Nelson-Miramichi, NB'},
'1513641':{'en': 'Cincinnati, OH'},
'1561496':{'en': 'Delray Beach, FL'},
'1561495':{'en': 'Delray Beach, FL'},
'1502671':{'en': 'Louisville, KY'},
'1561499':{'en': 'Delray Beach, FL'},
'1561498':{'en': 'Delray Beach, FL'},
'1479890':{'en': 'Russellville, AR'},
'1479899':{'en': 'Rogers, AR'},
'1603471':{'en': 'Bedford, NH'},
'1607869':{'en': 'Ovid, NY'},
'1615712':{'en': 'Nashville, TN'},
'1570552':{'en': 'Kingston, PA'},
'1570558':{'en': 'Scranton, PA'},
'1571208':{'en': 'Manassas, VA'},
'1586558':{'en': 'Warren, MI'},
'1607498':{'en': 'Roscoe, NY'},
'1510665':{'en': 'Berkeley, CA'},
'1510666':{'en': 'Berkeley, CA'},
'1510667':{'en': 'San Leandro, CA'},
'1510663':{'en': 'Oakland, CA'},
'1510668':{'en': 'Fremont, CA'},
'1541659':{'en': 'Grants Pass, OR'},
'1434243':{'en': 'Charlottesville, VA'},
'1425316':{'en': 'Everett, WA'},
'1425313':{'en': 'Issaquah, WA'},
'1434246':{'en': 'Stony Creek, VA'},
'1434245':{'en': 'Charlottesville, VA'},
'1434244':{'en': 'Charlottesville, VA'},
'1616583':{'en': 'Byron Center, MI'},
'1478272':{'en': 'Dublin, GA'},
'1478277':{'en': 'Dublin, GA'},
'1478274':{'en': 'Dublin, GA'},
'1478275':{'en': 'Dublin, GA'},
'1603938':{'en': 'Bradford, NH'},
'1541654':{'en': 'Eugene, OR'},
'1518325':{'en': 'Hillsdale, NY'},
'1518324':{'en': 'Plattsburgh, NY'},
'1518326':{'en': 'Troy, NY'},
'1518329':{'en': 'Copake, NY'},
'1541653':{'en': 'Eugene, OR'},
'1607274':{'en': 'Ithaca, NY'},
'1603935':{'en': 'Manchester, NH'},
'1603934':{'en': 'Franklin, NH'},
'1608775':{'en': 'La Crosse, WI'},
'1519353':{'en': 'Paisley, ON'},
'1410234':{'en': 'Baltimore, MD'},
'1410235':{'en': 'Baltimore, MD'},
'1410230':{'en': 'Baltimore, MD'},
'1574722':{'en': 'Logansport, IN'},
'1504945':{'en': 'New Orleans, LA'},
'1509633':{'en': 'Grand Coulee, WA'},
'1503299':{'en': 'Portland, OR'},
'1409670':{'en': 'Orange, TX'},
'1503295':{'en': 'Portland, OR'},
'1503294':{'en': 'Portland, OR'},
'1503297':{'en': 'Portland, OR'},
'1503296':{'en': 'Portland, OR'},
'1503291':{'en': 'Portland, OR'},
'1503293':{'en': 'Portland, OR'},
'1503292':{'en': 'Portland, OR'},
'1585589':{'en': 'Albion, NY'},
'1412931':{'en': 'Pittsburgh, PA'},
'1415217':{'en': 'San Francisco, CA'},
'1609683':{'en': 'Princeton, NJ'},
'1514543':{'en': 'Montreal, QC'},
'1410549':{'en': 'Sykesville, MD'},
'1514544':{'en': 'Montreal, QC'},
'1563732':{'en': 'Wilton, IA'},
'1504947':{'en': 'New Orleans, LA'},
'1585723':{'en': 'Rochester, NY'},
'1585720':{'en': 'Rochester, NY'},
'1585728':{'en': 'Wayland, NY'},
'1519357':{'en': 'Wingham, ON'},
'1530244':{'en': 'Redding, CA'},
'1512231':{'en': 'Austin, TX'},
'1512237':{'en': 'Smithville, TX'},
'1512236':{'en': 'Austin, TX'},
'1585341':{'en': 'Rochester, NY'},
'1432570':{'en': 'Midland, TX'},
'1504412':{'en': 'New Orleans, LA'},
'1504941':{'en': 'New Orleans, LA'},
'1585345':{'en': 'Batavia, NY'},
'1615776':{'en': 'Nolensville, TN'},
'1615777':{'en': 'Nashville, TN'},
'1559229':{'en': 'Fresno, CA'},
'1615771':{'en': 'Franklin, TN'},
'1615773':{'en': 'Mount Juliet, TN'},
'1616977':{'en': 'Grand Rapids, MI'},
'1562602':{'en': 'Paramount, CA'},
'1614445':{'en': 'Columbus, OH'},
'1520318':{'en': 'Tucson, AZ'},
'1504942':{'en': 'New Orleans, LA'},
'1559623':{'en': 'Visalia, CA'},
'1559622':{'en': 'Visalia, CA'},
'1559627':{'en': 'Visalia, CA'},
'1559626':{'en': 'Orange Cove, CA'},
'1559625':{'en': 'Visalia, CA'},
'1559624':{'en': 'Visalia, CA'},
'1573735':{'en': 'Monroe City, MO'},
'1504457':{'en': 'Metairie, LA'},
'1520770':{'en': 'Tucson, AZ'},
'1504943':{'en': 'New Orleans, LA'},
'1520777':{'en': 'Tucson, AZ'},
'1570887':{'en': 'Sayre, PA'},
'1610543':{'en': 'Springfield, PA'},
'1610544':{'en': 'Springfield, PA'},
'1601796':{'en': 'Lumberton, MS'},
'1601795':{'en': 'Poplarville, MS'},
'1601794':{'en': 'Purvis, MS'},
'1609689':{'en': 'Trenton, NJ'},
'1601792':{'en': 'Prentiss, MS'},
'1561265':{'en': 'Delray Beach, FL'},
'1561266':{'en': 'Delray Beach, FL'},
'1573468':{'en': 'Sullivan, MO'},
'1601799':{'en': 'Picayune, MS'},
'1408629':{'en': 'San Jose, CA'},
'1540689':{'en': 'Harrisonburg, VA'},
'1419568':{'en': 'Waynesfield, OH'},
'1540687':{'en': 'Middleburg, VA'},
'1419562':{'en': 'Bucyrus, OH'},
'1510895':{'en': 'San Leandro, CA'},
'1480874':{'en': 'Scottsdale, AZ'},
'1510893':{'en': 'Oakland, CA'},
'1510891':{'en': 'Oakland, CA'},
'1480654':{'en': 'Mesa, AZ'},
'1601425':{'en': 'Laurel, MS'},
'1601426':{'en': 'Laurel, MS'},
'1601428':{'en': 'Laurel, MS'},
'1601857':{'en': 'Raymond, MS'},
'1612766':{'en': 'South 7th Street, Minneapolis, MN'},
'1410796':{'en': 'Elkridge, MD'},
'1410795':{'en': 'Sykesville, MD'},
'1505438':{'en': 'Santa Fe, NM'},
'1505433':{'en': 'Albuquerque, NM'},
'1614645':{'en': 'Columbus, OH'},
'1516338':{'en': 'Westbury, NY'},
'1570775':{'en': 'Hawley, PA'},
'1516334':{'en': 'Westbury, NY'},
'1516441':{'en': 'Great Neck, NY'},
'1610898':{'en': 'Reading, PA'},
'1516333':{'en': 'Westbury, NY'},
'1434525':{'en': 'Forest, VA'},
'1510471':{'en': 'Union City, CA'},
'1434528':{'en': 'Lynchburg, VA'},
'1510475':{'en': 'Union City, CA'},
'1616281':{'en': 'Grand Rapids, MI'},
'1510477':{'en': 'Union City, CA'},
'1517316':{'en': 'Lansing, MI'},
'1602212':{'en': 'Phoenix, AZ'},
'1602216':{'en': 'Phoenix, AZ'},
'1602218':{'en': 'Phoenix, AZ'},
'1541791':{'en': 'Albany, OR'},
'1410420':{'en': 'Bel Air, MD'},
'1612492':{'en': 'Minneapolis, MN'},
'1410424':{'en': 'Glen Burnie, MD'},
'1410426':{'en': 'Baltimore, MD'},
'1519':{'en': 'Ontario'},
'1518':{'en': 'New York'},
'1515':{'en': 'Iowa'},
'1514':{'en': 'Quebec'},
'1517':{'en': 'Michigan'},
'1516':{'en': 'New York'},
'1510':{'en': 'California'},
'1513':{'en': 'Ohio'},
'1512':{'en': 'Texas'},
'1508857':{'en': 'Brockton, MA'},
'1480513':{'en': 'Scottsdale, AZ'},
'1570969':{'en': 'Scranton, PA'},
'1570961':{'en': 'Scranton, PA'},
'1541242':{'en': 'Eugene, OR'},
'1575445':{'en': 'Raton, NM'},
'1541245':{'en': 'Medford, OR'},
'1541247':{'en': 'Gold Beach, OR'},
'1440473':{'en': 'Cleveland, OH'},
'1409287':{'en': 'Sour Lake, TX'},
'1513785':{'en': 'Hamilton, OH'},
'1409283':{'en': 'Woodville, TX'},
'1518446':{'en': 'Albany, NY'},
'1435438':{'en': 'Beaver, UT'},
'1606464':{'en': 'Beattyville, KY'},
'1518447':{'en': 'Albany, NY'},
'1518668':{'en': 'Lake George, NY'},
'1518664':{'en': 'Mechanicville, NY'},
'1518661':{'en': 'Mayfield, NY'},
'1607758':{'en': 'Cortland, NY'},
'1514376':{'en': 'Montreal, QC'},
'1514374':{'en': 'Montreal, QC'},
'1580237':{'en': 'Enid, OK'},
'1504821':{'en': 'New Orleans, LA'},
'1616642':{'en': 'Saranac, MI'},
'1606862':{'en': 'London, KY'},
'1570374':{'en': 'Selinsgrove, PA'},
'1450546':{'en': 'Acton Vale, QC'},
'1586493':{'en': 'Mount Clemens, MI'},
'1586498':{'en': 'Saint Clair Shores, MI'},
'1513871':{'en': 'Cincinnati, OH'},
'1513872':{'en': 'Cincinnati, OH'},
'1513875':{'en': 'Fayetteville, OH'},
'1450548':{'en': 'Roxton Falls, QC'},
'1510783':{'en': 'Hayward, CA'},
'1510782':{'en': 'Hayward, CA'},
'1510780':{'en': 'Hayward, CA'},
'1510787':{'en': 'Crockett, CA'},
'1479667':{'en': 'Ozark, AR'},
'1510785':{'en': 'Hayward, CA'},
'1510784':{'en': 'Hayward, CA'},
'1559791':{'en': 'Porterville, CA'},
'1608741':{'en': 'Janesville, WI'},
'1416485':{'en': 'Toronto, ON'},
'1416484':{'en': 'Toronto, ON'},
'1416487':{'en': 'Toronto, ON'},
'1416486':{'en': 'Toronto, ON'},
'1416481':{'en': 'Toronto, ON'},
'1416480':{'en': 'Toronto, ON'},
'1416483':{'en': 'Toronto, ON'},
'1416482':{'en': 'Toronto, ON'},
'1604228':{'en': 'Vancouver, BC'},
'1416489':{'en': 'Toronto, ON'},
'1416488':{'en': 'Toronto, ON'},
'1608745':{'en': 'Portage, WI'},
'1603293':{'en': 'Gilford, NH'},
'1604596':{'en': 'Surrey, BC'},
'1414933':{'en': 'Milwaukee, WI'},
'1609345':{'en': 'Atlantic City, NJ'},
'1604594':{'en': 'Surrey, BC'},
'1563742':{'en': 'Bettendorf, IA'},
'1603298':{'en': 'West Lebanon, NH'},
'1505954':{'en': 'Santa Fe, NM'},
'1505955':{'en': 'Santa Fe, NM'},
'1423844':{'en': 'Bristol, TN'},
'1416261':{'en': 'Scarborough, ON'},
'1416260':{'en': 'Toronto, ON'},
'1503362':{'en': 'Salem, OR'},
'1416265':{'en': 'Scarborough, ON'},
'1416264':{'en': 'Scarborough, ON'},
'1416267':{'en': 'Scarborough, ON'},
'1416266':{'en': 'Scarborough, ON'},
'1416269':{'en': 'Scarborough, ON'},
'1606864':{'en': 'London, KY'},
'1586948':{'en': 'Chesterfield, MI'},
'1586949':{'en': 'Chesterfield, MI'},
'1540318':{'en': 'Stafford, VA'},
'1479273':{'en': 'Bentonville, AR'},
'1520908':{'en': 'Tucson, AZ'},
'1615342':{'en': 'Nashville, TN'},
'1480812':{'en': 'Chandler, AZ'},
'1519204':{'en': 'London, ON'},
'1585268':{'en': 'Belmont, NY'},
'1519754':{'en': 'Brantford, ON'},
'1519753':{'en': 'Brantford, ON'},
'1519752':{'en': 'Brantford, ON'},
'1519751':{'en': 'Brantford, ON'},
'1519750':{'en': 'Brantford, ON'},
'1415682':{'en': 'San Francisco, CA'},
'1585263':{'en': 'Rochester, NY'},
'1415681':{'en': 'San Francisco, CA'},
'1585266':{'en': 'Rochester, NY'},
'1519759':{'en': 'Brantford, ON'},
'1519758':{'en': 'Brantford, ON'},
'1604232':{'en': 'Richmond, BC'},
'1573876':{'en': 'Columbia, MO'},
'1573874':{'en': 'Columbia, MO'},
'1573875':{'en': 'Columbia, MO'},
'1573696':{'en': 'Hallsville, MO'},
'1573873':{'en': 'Camdenton, MO'},
'1573695':{'en': 'Steele, MO'},
'1608437':{'en': 'Mount Horeb, WI'},
'1509689':{'en': 'Brewster, WA'},
'1507776':{'en': 'Truman, MN'},
'1507775':{'en': 'Byron, MN'},
'1508717':{'en': 'New Bedford, MA'},
'1508240':{'en': 'Orleans, MA'},
'1508248':{'en': 'Charlton, MA'},
'1605353':{'en': 'Huron, SD'},
'1505609':{'en': 'Farmington, NM'},
'1601304':{'en': 'Natchez, MS'},
'1605356':{'en': 'Elk Point, SD'},
'1605355':{'en': 'Rapid City, SD'},
'1503463':{'en': 'Keizer, OR'},
'1503460':{'en': 'Portland, OR'},
'1503467':{'en': 'Portland, OR'},
'1609463':{'en': 'Cape May Ct Hse, NJ'},
'1503469':{'en': 'Beaverton, OR'},
'1507553':{'en': 'Wells, MN'},
'1604886':{'en': 'Gibsons, BC'},
'1610399':{'en': 'West Chester, PA'},
'1604881':{'en': 'Langley, BC'},
'1604882':{'en': 'Langley, BC'},
'1604883':{'en': 'Madeira Park, BC'},
'1610395':{'en': 'Allentown, PA'},
'1614340':{'en': 'Columbus, OH'},
'1530566':{'en': 'Chico, CA'},
'1604888':{'en': 'Langley, BC'},
'1614433':{'en': 'Columbus, OH'},
'1541878':{'en': 'Shady Cove, OR'},
'1518398':{'en': 'Pine Plains, NY'},
'1610923':{'en': 'Easton, PA'},
'1540316':{'en': 'Warrenton, VA'},
'1410309':{'en': 'Columbia, MD'},
'1504903':{'en': 'New Orleans, LA'},
'1610250':{'en': 'Easton, PA'},
'1508866':{'en': 'Carver, MA'},
'1508865':{'en': 'Millbury, MA'},
'1423378':{'en': 'Kingsport, TN'},
'1508862':{'en': 'Hyannis, MA'},
'1508860':{'en': 'Worcester, MA'},
'1610253':{'en': 'Easton, PA'},
'1508869':{'en': 'Boylston, MA'},
'1432385':{'en': 'Odessa, TX'},
'1432381':{'en': 'Odessa, TX'},
'1561929':{'en': 'Boca Raton, FL'},
'1561924':{'en': 'Pahokee, FL'},
'1561921':{'en': 'Delray Beach, FL'},
'1610929':{'en': 'Reading, PA'},
'1610258':{'en': 'Easton, PA'},
'1610971':{'en': 'Wayne, PA'},
'1610970':{'en': 'Pottstown, PA'},
'1610973':{'en': 'Allentown, PA'},
'1602449':{'en': 'Phoenix, AZ'},
'1610975':{'en': 'Wayne, PA'},
'1415878':{'en': 'Novato, CA'},
'1480460':{'en': 'Phoenix, AZ'},
'1480461':{'en': 'Mesa, AZ'},
'1440646':{'en': 'Cleveland, OH'},
'1440647':{'en': 'Wellington, OH'},
'1480464':{'en': 'Mesa, AZ'},
'1502732':{'en': 'Carrollton, KY'},
'1580439':{'en': 'Comanche, OK'},
'1580436':{'en': 'Ada, OK'},
'1602442':{'en': 'Phoenix, AZ'},
'1602443':{'en': 'Phoenix, AZ'},
'1602441':{'en': 'Phoenix, AZ'},
'1513661':{'en': 'Cincinnati, OH'},
'1513662':{'en': 'Cincinnati, OH'},
'1519538':{'en': 'Meaford, ON'},
'1508979':{'en': 'New Bedford, MA'},
'1417659':{'en': 'Joplin, MO'},
'1517788':{'en': 'Jackson, MI'},
'1517789':{'en': 'Jackson, MI'},
'1616819':{'en': 'Grand Rapids, MI'},
'1517782':{'en': 'Jackson, MI'},
'1517783':{'en': 'Jackson, MI'},
'1517780':{'en': 'Jackson, MI'},
'1517787':{'en': 'Jackson, MI'},
'1517784':{'en': 'Jackson, MI'},
'1419794':{'en': 'Maumee, OH'},
'1419797':{'en': 'Port Clinton, OH'},
'1541496':{'en': 'Glide, OR'},
'1419798':{'en': 'Lakeside Marblhd, OH'},
'1450771':{'en': 'Saint-Hyacinthe, QC'},
'1530758':{'en': 'Davis, CA'},
'1530759':{'en': 'Davis, CA'},
'1530752':{'en': 'Davis, CA'},
'1530753':{'en': 'Davis, CA'},
'1530750':{'en': 'Davis, CA'},
'1530751':{'en': 'Yuba City, CA'},
'1530756':{'en': 'Davis, CA'},
'1530757':{'en': 'Davis, CA'},
'1530755':{'en': 'Yuba City, CA'},
'1479876':{'en': 'Bella Vista, AR'},
'1479872':{'en': 'Springdale, AR'},
'1561748':{'en': 'Jupiter, FL'},
'1540347':{'en': 'Warrenton, VA'},
'1561743':{'en': 'Jupiter, FL'},
'1561742':{'en': 'Boynton Beach, FL'},
'1561741':{'en': 'Jupiter, FL'},
'1561740':{'en': 'Boynton Beach, FL'},
'1561747':{'en': 'Jupiter, FL'},
'1561746':{'en': 'Jupiter, FL'},
'1561745':{'en': 'Jupiter, FL'},
'1561744':{'en': 'Jupiter, FL'},
'1585786':{'en': 'Warsaw, NY'},
'1571223':{'en': 'Ashburn, VA'},
'1434263':{'en': 'Lovingston, VA'},
'1510649':{'en': 'Berkeley, CA'},
'1510647':{'en': 'Berkeley, CA'},
'1510644':{'en': 'Berkeley, CA'},
'1510317':{'en': 'San Leandro, CA'},
'1510642':{'en': 'Berkeley, CA'},
'1425339':{'en': 'Everett, WA'},
'1505384':{'en': 'Estancia, NM'},
'1519438':{'en': 'London, ON'},
'1519439':{'en': 'London, ON'},
'1519928':{'en': 'Grand Valley, ON'},
'1602530':{'en': 'Phoenix, AZ'},
'1519432':{'en': 'London, ON'},
'1519433':{'en': 'London, ON'},
'1425333':{'en': 'Carnation, WA'},
'1519927':{'en': 'Caledon, ON'},
'1425335':{'en': 'Lake Stevens, WA'},
'1425334':{'en': 'Lake Stevens, WA'},
'1519434':{'en': 'London, ON'},
'1519923':{'en': 'Dundalk, ON'},
'1503925':{'en': 'Sherwood, OR'},
'1573471':{'en': 'Sikeston, MO'},
'1509382':{'en': 'Dayton, WA'},
'1509928':{'en': 'Spokane Valley, WA'},
'1509925':{'en': 'Ellensburg, WA'},
'1509924':{'en': 'Spokane Valley, WA'},
'1509927':{'en': 'Spokane Valley, WA'},
'1509926':{'en': 'Spokane Valley, WA'},
'1509921':{'en': 'Spokane Valley, WA'},
'1518346':{'en': 'Schenectady, NY'},
'1509922':{'en': 'Spokane Valley, WA'},
'1519696':{'en': 'New Dundee, ON'},
'1519692':{'en': 'Thamesville, ON'},
'1519690':{'en': 'London, ON'},
'1609625':{'en': 'Mays Landing, NJ'},
'1519698':{'en': 'Linwood, ON'},
'1519699':{'en': 'St. Clements, ON'},
'1508528':{'en': 'Franklin, MA'},
'1508529':{'en': 'Upton, MA'},
'1508520':{'en': 'Franklin, MA'},
'1520417':{'en': 'Sierra Vista, AZ'},
'1413536':{'en': 'Holyoke, MA'},
'1413534':{'en': 'Holyoke, MA'},
'1413532':{'en': 'Holyoke, MA'},
'1413533':{'en': 'Holyoke, MA'},
'1413539':{'en': 'Holyoke, MA'},
'1412777':{'en': 'McKees Rocks, PA'},
'1509659':{'en': 'Ritzville, WA'},
'1412771':{'en': 'McKees Rocks, PA'},
'1519885':{'en': 'Waterloo, ON'},
'1602482':{'en': 'Phoenix, AZ'},
'1514529':{'en': 'Montreal, QC'},
'1514528':{'en': 'Montreal, QC'},
'1514523':{'en': 'Montreal, QC'},
'1514522':{'en': 'Montreal, QC'},
'1514521':{'en': 'Montreal, QC'},
'1530926':{'en': 'Mount Shasta, CA'},
'1514527':{'en': 'Montreal, QC'},
'1514526':{'en': 'Montreal, QC'},
'1478836':{'en': 'Roberta, GA'},
'1514524':{'en': 'Montreal, QC'},
'1603775':{'en': 'Exeter, NH'},
'1603774':{'en': 'Dunbarton, NH'},
'1603773':{'en': 'Exeter, NH'},
'1603772':{'en': 'Exeter, NH'},
'1563244':{'en': 'Clinton, IA'},
'1563245':{'en': 'Elkader, IA'},
'1563242':{'en': 'Clinton, IA'},
'1563243':{'en': 'Clinton, IA'},
'1604746':{'en': 'Abbotsford, BC'},
'1562599':{'en': 'Long Beach, CA'},
'1512250':{'en': 'Austin, TX'},
'1604742':{'en': 'Vancouver, BC'},
'1512255':{'en': 'Round Rock, TX'},
'1604740':{'en': 'Sechelt, BC'},
'1562591':{'en': 'Long Beach, CA'},
'1512258':{'en': 'Austin, TX'},
'1562597':{'en': 'Long Beach, CA'},
'1562595':{'en': 'Long Beach, CA'},
'1508384':{'en': 'Wrentham, MA'},
'1508385':{'en': 'Dennis, MA'},
'1508383':{'en': 'Framingham, MA'},
'1508381':{'en': 'Milford, MA'},
'1432558':{'en': 'Crane, TX'},
'1615754':{'en': 'Mount Juliet, TN'},
'1615750':{'en': 'Nashville, TN'},
'1432550':{'en': 'Odessa, TX'},
'1432552':{'en': 'Odessa, TX'},
'1615758':{'en': 'Mount Juliet, TN'},
'1520579':{'en': 'Tucson, AZ'},
'1520578':{'en': 'Tucson, AZ'},
'1520577':{'en': 'Tucson, AZ'},
'1520575':{'en': 'Tucson, AZ'},
'1520574':{'en': 'Tucson, AZ'},
'1520573':{'en': 'Tucson, AZ'},
'1520572':{'en': 'Tucson, AZ'},
'1520571':{'en': 'Tucson, AZ'},
'1559353':{'en': 'Madera, CA'},
'1559734':{'en': 'Visalia, CA'},
'1506832':{'en': 'Hampton, NB'},
'1616994':{'en': 'Holland, MI'},
'1412928':{'en': 'Pittsburgh, PA'},
'1616997':{'en': 'Coopersville, MI'},
'1610826':{'en': 'Palmerton, PA'},
'1574862':{'en': 'Wakarusa, IN'},
'1559271':{'en': 'Fresno, CA'},
'1561244':{'en': 'Boynton Beach, FL'},
'1561245':{'en': 'Boca Raton, FL'},
'1561242':{'en': 'West Palm Beach, FL'},
'1561243':{'en': 'Delray Beach, FL'},
'1561241':{'en': 'Boca Raton, FL'},
'1417532':{'en': 'Lebanon, MO'},
'1417533':{'en': 'Lebanon, MO'},
'1602841':{'en': 'Phoenix, AZ'},
'1417820':{'en': 'Springfield, MO'},
'1417823':{'en': 'Springfield, MO'},
'1574831':{'en': 'New Paris, IN'},
'1414328':{'en': 'Milwaukee, WI'},
'1414329':{'en': 'Milwaukee, WI'},
'1414327':{'en': 'Milwaukee, WI'},
'1418337':{'en': 'Saint-Raymond, QC'},
'1573483':{'en': 'Bloomsdale, MO'},
'1573481':{'en': 'Sikeston, MO'},
'1414321':{'en': 'Milwaukee, WI'},
'1419542':{'en': 'Hicksville, OH'},
'1419547':{'en': 'Clyde, OH'},
'1562624':{'en': 'Long Beach, CA'},
'1610705':{'en': 'Pottstown, PA'},
'1480855':{'en': 'Chandler, AZ'},
'1480854':{'en': 'Mesa, AZ'},
'1480857':{'en': 'Chandler, AZ'},
'1562622':{'en': 'Downey, CA'},
'1480671':{'en': 'Apache Junction, AZ'},
'1617282':{'en': 'Dorchester, MA'},
'1617284':{'en': 'Somerville, MA'},
'1617288':{'en': 'Dorchester, MA'},
'1419893':{'en': 'Maumee, OH'},
'1425688':{'en': 'Bellevue, WA'},
'1419891':{'en': 'Maumee, OH'},
'1419897':{'en': 'Maumee, OH'},
'1615383':{'en': 'Nashville, TN'},
'1416654':{'en': 'Toronto, ON'},
'1419898':{'en': 'Oak Harbor, OH'},
'1601446':{'en': 'Natchez, MS'},
'1425687':{'en': 'Renton, WA'},
'1469952':{'en': 'McKinney, TX'},
'1606796':{'en': 'Vanceburg, KY'},
'1574287':{'en': 'South Bend, IN'},
'1416656':{'en': 'Toronto, ON'},
'1574282':{'en': 'South Bend, IN'},
'1574283':{'en': 'South Bend, IN'},
'1574288':{'en': 'South Bend, IN'},
'1574289':{'en': 'South Bend, IN'},
'1610562':{'en': 'Hamburg, PA'},
'1610566':{'en': 'Media, PA'},
'1610565':{'en': 'Media, PA'},
'1614884':{'en': 'Columbus, OH'},
'1585453':{'en': 'Rochester, NY'},
'1614882':{'en': 'Westerville, OH'},
'1608685':{'en': 'Alma, WI'},
'1585454':{'en': 'Rochester, NY'},
'1602239':{'en': 'Phoenix, AZ'},
'1602235':{'en': 'Phoenix, AZ'},
'1602234':{'en': 'Phoenix, AZ'},
'1602230':{'en': 'Phoenix, AZ'},
'1602233':{'en': 'Phoenix, AZ'},
'1602232':{'en': 'Phoenix, AZ'},
'1410448':{'en': 'Baltimore, MD'},
'1503719':{'en': 'Portland, OR'},
'1503717':{'en': 'Seaside, OR'},
'1418948':{'en': 'Quebec City, QC'},
'1410444':{'en': 'Baltimore, MD'},
'1579':{'en': 'Quebec'},
'1604874':{'en': 'Vancouver, BC'},
'1573':{'en': 'Missouri'},
'1571':{'en': 'Virginia'},
'1570':{'en': 'Pennsylvania'},
'1575':{'en': 'New Mexico'},
'1574':{'en': 'Indiana'},
'1541266':{'en': 'Coos Bay, OR'},
'1541267':{'en': 'Coos Bay, OR'},
'1541265':{'en': 'Newport, OR'},
'1541269':{'en': 'Coos Bay, OR'},
'1604877':{'en': 'Vancouver, BC'},
'1501244':{'en': 'Little Rock, AR'},
'1518647':{'en': 'Au Sable Forks, NY'},
'1501246':{'en': 'Little Rock, AR'},
'1518642':{'en': 'Granville, NY'},
'1518643':{'en': 'Peru, NY'},
'1440458':{'en': 'Elyria, OH'},
'1413236':{'en': 'Pittsfield, MA'},
'1518648':{'en': 'Indian Lake, NY'},
'1517373':{'en': 'Lansing, MI'},
'1517372':{'en': 'Lansing, MI'},
'1479463':{'en': 'Fayetteville, AR'},
'1479464':{'en': 'Bentonville, AR'},
'1517374':{'en': 'Lansing, MI'},
'1580668':{'en': 'Wilson, OK'},
'1580886':{'en': 'Canton, OK'},
'1602493':{'en': 'Phoenix, AZ'},
'1514313':{'en': 'Montreal, QC'},
'1602495':{'en': 'Phoenix, AZ'},
'1514315':{'en': 'Montreal, QC'},
'1570636':{'en': 'Freeland, PA'},
'1570639':{'en': 'Harveys Lake, PA'},
'1570638':{'en': 'Blossburg, PA'},
'1602944':{'en': 'Phoenix, AZ'},
'1478333':{'en': 'Warner Robins, GA'},
'1602942':{'en': 'Phoenix, AZ'},
'1604871':{'en': 'Vancouver, BC'},
'1478330':{'en': 'Macon, GA'},
'1513852':{'en': 'Cincinnati, OH'},
'1513851':{'en': 'Cincinnati, OH'},
'1562435':{'en': 'Long Beach, CA'},
'1513858':{'en': 'Fairfield, OH'},
'1518426':{'en': 'Albany, NY'},
'1518427':{'en': 'Albany, NY'},
'1615457':{'en': 'Nashville, TN'},
'1603547':{'en': 'Greenfield, NH'},
'1604870':{'en': 'Abbotsford, BC'},
'1603542':{'en': 'Claremont, NH'},
'1603543':{'en': 'Claremont, NH'},
'1602765':{'en': 'Phoenix, AZ'},
'1501653':{'en': 'Bryant, AR'},
'1562657':{'en': 'Downey, CA'},
'1416469':{'en': 'Toronto, ON'},
'1413499':{'en': 'Pittsfield, MA'},
'1416466':{'en': 'Toronto, ON'},
'1416465':{'en': 'Toronto, ON'},
'1416463':{'en': 'Toronto, ON'},
'1416462':{'en': 'Toronto, ON'},
'1416461':{'en': 'Toronto, ON'},
'1603319':{'en': 'Portsmouth, NH'},
'1450293':{'en': 'Farnham, QC'},
'1450297':{'en': 'Eastman, QC'},
'1519595':{'en': 'Milverton, ON'},
'1519596':{'en': 'Tobermory, ON'},
'1519599':{'en': 'Thornbury, ON'},
'1509725':{'en': 'Davenport, WA'},
'1574784':{'en': 'Lakeville, IN'},
'1416203':{'en': 'Toronto, ON'},
'1416201':{'en': 'Etobicoke, ON'},
'1608634':{'en': 'Westby, WI'},
'1416207':{'en': 'Etobicoke, ON'},
'1416204':{'en': 'Toronto, ON'},
'1519770':{'en': 'Brantford, ON'},
'1519773':{'en': 'Aylmer West, ON'},
'1604538':{'en': 'Surrey, BC'},
'1604539':{'en': 'Langley, BC'},
'1519776':{'en': 'Essex, ON'},
'1604534':{'en': 'Langley, BC'},
'1604535':{'en': 'Surrey, BC'},
'1604536':{'en': 'Surrey, BC'},
'1604241':{'en': 'Richmond, BC'},
'1604530':{'en': 'Langley, BC'},
'1604247':{'en': 'Richmond, BC'},
'1604244':{'en': 'Richmond, BC'},
'1604533':{'en': 'Langley, BC'},
'1573814':{'en': 'Columbia, MO'},
'1573815':{'en': 'Columbia, MO'},
'1504599':{'en': 'New Orleans, LA'},
'1573817':{'en': 'Columbia, MO'},
'1608989':{'en': 'Blair, WI'},
'1515263':{'en': 'Des Moines, IA'},
'1515262':{'en': 'Des Moines, IA'},
'1515267':{'en': 'West Des Moines, IA'},
'1515266':{'en': 'Des Moines, IA'},
'1515265':{'en': 'Des Moines, IA'},
'1515264':{'en': 'Des Moines, IA'},
'1604633':{'en': 'Vancouver, BC'},
'1410233':{'en': 'Baltimore, MD'},
'1616361':{'en': 'Grand Rapids, MI'},
'1508261':{'en': 'Mansfield, MA'},
'1604631':{'en': 'Vancouver, BC'},
'1520384':{'en': 'Willcox, AZ'},
'1505629':{'en': 'Santa Fe, NM'},
'1520382':{'en': 'Tucson, AZ'},
'1520383':{'en': 'Sells, AZ'},
'1440937':{'en': 'Avon, OH'},
'1505620':{'en': 'Albuquerque, NM'},
'1440933':{'en': 'Avon Lake, OH'},
'1440930':{'en': 'Avon Lake, OH'},
'1480990':{'en': 'Scottsdale, AZ'},
'1480991':{'en': 'Scottsdale, AZ'},
'1614414':{'en': 'Columbus, OH'},
'1480994':{'en': 'Scottsdale, AZ'},
'1480998':{'en': 'Scottsdale, AZ'},
'1409938':{'en': 'La Marque, TX'},
'1574453':{'en': 'Leesburg, IN'},
'1574457':{'en': 'Syracuse, IN'},
'1541855':{'en': 'Gold Hill, OR'},
'1559297':{'en': 'Clovis, CA'},
'1541857':{'en': 'Medford, OR'},
'1541850':{'en': 'Klamath Falls, OR'},
'1609588':{'en': 'Trenton, NJ'},
'1609586':{'en': 'Trenton, NJ'},
'1609587':{'en': 'Trenton, NJ'},
'1609584':{'en': 'Trenton, NJ'},
'1573783':{'en': 'Fredericktown, MO'},
'1541858':{'en': 'Medford, OR'},
'1559298':{'en': 'Clovis, CA'},
'1559299':{'en': 'Clovis, CA'},
'1410323':{'en': 'Baltimore, MD'},
'1410857':{'en': 'Westminster, MD'},
'1410327':{'en': 'Baltimore, MD'},
'1410325':{'en': 'Baltimore, MD'},
'1410328':{'en': 'Baltimore, MD'},
'1423357':{'en': 'Church Hill, TN'},
'1423422':{'en': 'Mosheim, TN'},
'1562904':{'en': 'Downey, CA'},
'1562906':{'en': 'Santa Fe Springs, CA'},
'1562907':{'en': 'Whittier, CA'},
'1562901':{'en': 'Long Beach, CA'},
'1562903':{'en': 'Santa Fe Springs, CA'},
'1508842':{'en': 'Shrewsbury, MA'},
'1508845':{'en': 'Shrewsbury, MA'},
'1502287':{'en': 'Louisville, KY'},
'1610685':{'en': 'Reading, PA'},
'1601854':{'en': 'Pelahatchie, MS'},
'1601855':{'en': 'Canton, MS'},
'1601856':{'en': 'Madison, MS'},
'1506992':{'en': 'Clair, NB'},
'1605371':{'en': 'Sioux Falls, SD'},
'1605373':{'en': 'Sioux Falls, SD'},
'1601853':{'en': 'Madison, MS'},
'1506446':{'en': 'Oromocto, NB'},
'1601859':{'en': 'Canton, MS'},
'1435627':{'en': 'St. George, UT'},
'1606672':{'en': 'Hyden, KY'},
'1480446':{'en': 'Tempe, AZ'},
'1435623':{'en': 'Nephi, UT'},
'1606677':{'en': 'Somerset, KY'},
'1606676':{'en': 'Somerset, KY'},
'1516767':{'en': 'Port Washington, NY'},
'1606678':{'en': 'Somerset, KY'},
'1443481':{'en': 'Annapolis, MD'},
'1516764':{'en': 'Rockville Centre, NY'},
'1435628':{'en': 'St. George, UT'},
'1610918':{'en': 'West Chester, PA'},
'1609919':{'en': 'Princeton, NJ'},
'1610913':{'en': 'Morgantown, PA'},
'1610917':{'en': 'Phoenixville, PA'},
'1540725':{'en': 'Roanoke, VA'},
'1540726':{'en': 'Narrows, VA'},
'1540727':{'en': 'Culpeper, VA'},
'1540720':{'en': 'Stafford, VA'},
'1540722':{'en': 'Winchester, VA'},
'1540723':{'en': 'Winchester, VA'},
'1506662':{'en': 'Grand Manan, NB'},
'1440593':{'en': 'Conneaut, OH'},
'1541552':{'en': 'Ashland, OR'},
'1440599':{'en': 'Conneaut, OH'},
'1417673':{'en': 'Webb City, MO'},
'1502633':{'en': 'Shelbyville, KY'},
'1502634':{'en': 'Louisville, KY'},
'1502635':{'en': 'Louisville, KY'},
'1502636':{'en': 'Louisville, KY'},
'1502637':{'en': 'Louisville, KY'},
'1417679':{'en': 'Gainesville, MO'},
'1417678':{'en': 'Aurora, MO'},
'1530673':{'en': 'Yuba City, CA'},
'1425746':{'en': 'Bellevue, WA'},
'1425747':{'en': 'Bellevue, WA'},
'1425741':{'en': 'Lynnwood, WA'},
'1425742':{'en': 'Lynnwood, WA'},
'1425743':{'en': 'Lynnwood, WA'},
'1608848':{'en': 'Verona, WI'},
'1479855':{'en': 'Bella Vista, AR'},
'1561768':{'en': 'Jupiter, FL'},
'1613938':{'en': 'Cornwall, ON'},
'1574656':{'en': 'North Liberty, IN'},
'1613931':{'en': 'Cornwall, ON'},
'1613932':{'en': 'Cornwall, ON'},
'1613933':{'en': 'Cornwall, ON'},
'1613936':{'en': 'Cornwall, ON'},
'1613937':{'en': 'Cornwall, ON'},
'1410347':{'en': 'Baltimore, MD'},
'1410341':{'en': 'Salisbury, MD'},
'1510336':{'en': 'Oakland, CA'},
'1510337':{'en': 'Alameda, CA'},
'1503525':{'en': 'Portland, OR'},
'1559738':{'en': 'Visalia, CA'},
'1409741':{'en': 'Galveston, TX'},
'1510339':{'en': 'Oakland, CA'},
'1425353':{'en': 'Everett, WA'},
'1425355':{'en': 'Everett, WA'},
'1510620':{'en': 'Richmond, CA'},
'1434286':{'en': 'Scottsville, VA'},
'1510623':{'en': 'Fremont, CA'},
'1510625':{'en': 'Oakland, CA'},
'1615376':{'en': 'Brentwood, TN'},
'1602553':{'en': 'Phoenix, AZ'},
'1505369':{'en': 'Albuquerque, NM'},
'1505368':{'en': 'Shiprock, NM'},
'1609585':{'en': 'Trenton, NJ'},
'1505363':{'en': 'Albuquerque, NM'},
'1508676':{'en': 'Fall River, MA'},
'1508677':{'en': 'Fall River, MA'},
'1559733':{'en': 'Visalia, CA'},
'1559732':{'en': 'Visalia, CA'},
'1508896':{'en': 'Brewster, MA'},
'1509413':{'en': 'Spokane, WA'},
'1508897':{'en': 'Brockton, MA'},
'1414258':{'en': 'Milwaukee, WI'},
'1502255':{'en': 'Bedford, KY'},
'1512491':{'en': 'Austin, TX'},
'1571248':{'en': 'Gainesville, VA'},
'1585538':{'en': 'Caledonia, NY'},
'1415258':{'en': 'San Rafael, CA'},
'1415529':{'en': 'San Francisco, CA'},
'1415255':{'en': 'San Francisco, CA'},
'1585546':{'en': 'Rochester, NY'},
'1415525':{'en': 'San Francisco, CA'},
'1415256':{'en': 'San Rafael, CA'},
'1415522':{'en': 'San Francisco, CA'},
'1415252':{'en': 'San Francisco, CA'},
'1514504':{'en': 'Montreal, QC'},
'1514507':{'en': 'Montreal, QC'},
'1559998':{'en': 'Lemoore, CA'},
'1514509':{'en': 'Montreal, QC'},
'1514508':{'en': 'Montreal, QC'},
'1559992':{'en': 'Corcoran, CA'},
'1563264':{'en': 'Muscatine, IA'},
'1563262':{'en': 'Muscatine, IA'},
'1563263':{'en': 'Muscatine, IA'},
'1432618':{'en': 'Midland, TX'},
'1540659':{'en': 'Stafford, VA'},
'1432617':{'en': 'Midland, TX'},
'1432614':{'en': 'Odessa, TX'},
'1450887':{'en': 'Lanoraie, QC'},
'1450886':{'en': 'St-Jean-de-Matha, QC'},
'1603752':{'en': 'Berlin, NH'},
'1603755':{'en': 'Farmington, NH'},
'1603756':{'en': 'Walpole, NH'},
'1603204':{'en': 'Nashua, NH'},
'1450889':{'en': u('St-F\u00e9lix-de-Valois, QC')},
'1585768':{'en': 'Le Roy, NY'},
'1512278':{'en': 'Manor, TX'},
'1604985':{'en': 'North Vancouver, BC'},
'1604984':{'en': 'North Vancouver, BC'},
'1604987':{'en': 'North Vancouver, BC'},
'1512276':{'en': 'Austin, TX'},
'1604980':{'en': 'North Vancouver, BC'},
'1512901':{'en': 'Austin, TX'},
'1512272':{'en': 'Manor, TX'},
'1416694':{'en': 'Toronto, ON'},
'1416695':{'en': 'Etobicoke, ON'},
'1615732':{'en': 'Nashville, TN'},
'1605589':{'en': 'Tyndall, SD'},
'1416690':{'en': 'Toronto, ON'},
'1416691':{'en': 'Toronto, ON'},
'1615736':{'en': 'Nashville, TN'},
'1416693':{'en': 'Toronto, ON'},
'1605582':{'en': 'Brandon, SD'},
'1416698':{'en': 'Toronto, ON'},
'1416699':{'en': 'Toronto, ON'},
'1605584':{'en': 'Lead, SD'},
'1509674':{'en': 'Cle Elum, WA'},
'1575355':{'en': 'Fort Sumner, NM'},
'1520805':{'en': 'Douglas, AZ'},
'1575356':{'en': 'Portales, NM'},
'1506850':{'en': 'Moncton, NB'},
'1506852':{'en': 'Moncton, NB'},
'1506853':{'en': 'Moncton, NB'},
'1506854':{'en': 'Moncton, NB'},
'1506855':{'en': 'Moncton, NB'},
'1506856':{'en': 'Moncton, NB'},
'1506857':{'en': 'Moncton, NB'},
'1506858':{'en': 'Moncton, NB'},
'1506859':{'en': 'Moncton, NB'},
'1432283':{'en': 'Van Horn, TX'},
'1515674':{'en': 'Colfax, IA'},
'1608845':{'en': 'Verona, WI'},
'1608846':{'en': 'DeForest, WI'},
'1608847':{'en': 'Mauston, WI'},
'1520731':{'en': 'Tucson, AZ'},
'1520733':{'en': 'Tucson, AZ'},
'1419427':{'en': 'Findlay, OH'},
'1419424':{'en': 'Findlay, OH'},
'1419425':{'en': 'Findlay, OH'},
'1419422':{'en': 'Findlay, OH'},
'1419423':{'en': 'Findlay, OH'},
'1419420':{'en': 'Findlay, OH'},
'1540536':{'en': 'Winchester, VA'},
'1574848':{'en': 'Bristol, IN'},
'1574842':{'en': 'Culver, IN'},
'1604853':{'en': 'Abbotsford, BC'},
'1561228':{'en': 'West Palm Beach, FL'},
'1419523':{'en': 'Ottawa, OH'},
'1419522':{'en': 'Mansfield, OH'},
'1419526':{'en': 'Mansfield, OH'},
'1419525':{'en': 'Mansfield, OH'},
'1419524':{'en': 'Mansfield, OH'},
'1414342':{'en': 'Milwaukee, WI'},
'1414344':{'en': 'Milwaukee, WI'},
'1414347':{'en': 'Milwaukee, WI'},
'1604852':{'en': 'Abbotsford, BC'},
'1606340':{'en': 'Monticello, KY'},
'1507457':{'en': 'Winona, MN'},
'1507455':{'en': 'Owatonna, MN'},
'1480838':{'en': 'Tempe, AZ'},
'1507453':{'en': 'Winona, MN'},
'1507452':{'en': 'Winona, MN'},
'1507451':{'en': 'Owatonna, MN'},
'1480833':{'en': 'Mesa, AZ'},
'1480832':{'en': 'Mesa, AZ'},
'1480830':{'en': 'Mesa, AZ'},
'1480837':{'en': 'Fountain Hills, AZ'},
'1480836':{'en': 'Fountain Hills, AZ'},
'1480835':{'en': 'Mesa, AZ'},
'1480834':{'en': 'Mesa, AZ'},
'1613584':{'en': 'Deep River, ON'},
'1506273':{'en': 'Perth-Andover, NB'},
'1613237':{'en': 'Ottawa, ON'},
'1613236':{'en': 'Ottawa, ON'},
'1613235':{'en': 'Ottawa, ON'},
'1613234':{'en': 'Ottawa, ON'},
'1601469':{'en': 'Forest, MS'},
'1574268':{'en': 'Warsaw, IN'},
'1613231':{'en': 'Ottawa, ON'},
'1613230':{'en': 'Ottawa, ON'},
'1574269':{'en': 'Warsaw, IN'},
'1570207':{'en': 'Scranton, PA'},
'1606348':{'en': 'Monticello, KY'},
'1612728':{'en': 'Minneapolis, MN'},
'1612729':{'en': 'Minneapolis, MN'},
'1612722':{'en': 'Minneapolis, MN'},
'1612721':{'en': 'Minneapolis, MN'},
'1612727':{'en': 'Minneapolis, MN'},
'1612724':{'en': 'Minneapolis, MN'},
'1480429':{'en': 'Scottsdale, AZ'},
'1501888':{'en': 'Little Rock, AR'},
'1501889':{'en': 'Perryville, AR'},
'1610588':{'en': 'Bangor, PA'},
'1610589':{'en': 'Womelsdorf, PA'},
'1501882':{'en': 'Beebe, AR'},
'1501884':{'en': 'Fairfield Bay, AR'},
'1570672':{'en': 'Elysburg, PA'},
'1410465':{'en': 'Ellicott City, MD'},
'1410464':{'en': 'Baltimore, MD'},
'1410467':{'en': 'Baltimore, MD'},
'1410466':{'en': 'Baltimore, MD'},
'1410461':{'en': 'Ellicott City, MD'},
'1410462':{'en': 'Baltimore, MD'},
'1503738':{'en': 'Seaside, OR'},
'1418692':{'en': 'Quebec City, QC'},
'1418693':{'en': 'Chicoutimi, QC'},
'1418690':{'en': 'Chicoutimi, QC'},
'1418696':{'en': 'Chicoutimi, QC'},
'1418694':{'en': 'Quebec City, QC'},
'1418695':{'en': u('Jonqui\u00e8re, QC')},
'1559':{'en': 'California'},
'1418698':{'en': 'Chicoutimi, QC'},
'1419825':{'en': 'Swanton, OH'},
'1614939':{'en': 'New Albany, OH'},
'1570385':{'en': 'Schuylkill Haven, PA'},
'1541289':{'en': 'Hermiston, OR'},
'1570387':{'en': 'Bloomsburg, PA'},
'1541284':{'en': 'Eugene, OR'},
'1415835':{'en': 'San Francisco, CA'},
'1541282':{'en': 'Medford, OR'},
'1570922':{'en': 'Millmont, PA'},
'1585889':{'en': 'Rochester, NY'},
'1609971':{'en': 'Forked River, NJ'},
'1573458':{'en': 'Rolla, MO'},
'1608676':{'en': 'Clinton, WI'},
'1518993':{'en': 'Fort Plain, NY'},
'1518622':{'en': 'Cairo, NY'},
'1518623':{'en': 'Warrensburg, NY'},
'1501268':{'en': 'Searcy, AR'},
'1435472':{'en': 'Helper, UT'},
'1435477':{'en': 'Parowan, UT'},
'1586727':{'en': 'Richmond, MI'},
'1479338':{'en': 'Rogers, AR'},
'1510438':{'en': 'Fremont, CA'},
'1479442':{'en': 'Fayetteville, AR'},
'1479443':{'en': 'Fayetteville, AR'},
'1510437':{'en': 'Oakland, CA'},
'1517424':{'en': 'Tecumseh, MI'},
'1517351':{'en': 'East Lansing, MI'},
'1479331':{'en': 'Dover, AR'},
'1517353':{'en': 'East Lansing, MI'},
'1479445':{'en': 'Fayetteville, AR'},
'1616356':{'en': 'Grand Rapids, MI'},
'1616355':{'en': 'Holland, MI'},
'1514339':{'en': 'Saint-Laurent, QC'},
'1514333':{'en': 'Saint-Laurent, QC'},
'1616608':{'en': 'Grand Rapids, MI'},
'1570655':{'en': 'Pittston, PA'},
'1514335':{'en': 'Saint-Laurent, QC'},
'1608785':{'en': 'La Crosse, WI'},
'1540885':{'en': 'Staunton, VA'},
'1513528':{'en': 'Cincinnati, OH'},
'1540886':{'en': 'Staunton, VA'},
'1513524':{'en': 'Oxford, OH'},
'1513522':{'en': 'Cincinnati, OH'},
'1513523':{'en': 'Oxford, OH'},
'1513521':{'en': 'Cincinnati, OH'},
'1602589':{'en': 'Phoenix, AZ'},
'1608783':{'en': 'Onalaska, WI'},
'1416449':{'en': 'North York, ON'},
'1603692':{'en': 'Somersworth, NH'},
'1501679':{'en': 'Greenbrier, AR'},
'1603695':{'en': 'Manchester, NH'},
'1416441':{'en': 'North York, ON'},
'1416440':{'en': 'Toronto, ON'},
'1501676':{'en': 'Lonoke, AR'},
'1416445':{'en': 'North York, ON'},
'1416447':{'en': 'North York, ON'},
'1412566':{'en': 'Pittsburgh, PA'},
'1510293':{'en': 'Hayward, CA'},
'1412562':{'en': 'Pittsburgh, PA'},
'1412563':{'en': 'Pittsburgh, PA'},
'1412561':{'en': 'Pittsburgh, PA'},
'1608782':{'en': 'La Crosse, WI'},
'1519579':{'en': 'Kitchener, ON'},
'1519578':{'en': 'Kitchener, ON'},
'1519576':{'en': 'Kitchener, ON'},
'1519571':{'en': 'Kitchener, ON'},
'1519570':{'en': 'Kitchener, ON'},
'1416225':{'en': 'North York, ON'},
'1416224':{'en': 'North York, ON'},
'1416227':{'en': 'North York, ON'},
'1416226':{'en': 'North York, ON'},
'1416221':{'en': 'North York, ON'},
'1416223':{'en': 'North York, ON'},
'1416222':{'en': 'North York, ON'},
'1416229':{'en': 'North York, ON'},
'1604572':{'en': 'Surrey, BC'},
'1509882':{'en': 'Grandview, WA'},
'1509886':{'en': 'East Wenatchee, WA'},
'1509884':{'en': 'East Wenatchee, WA'},
'1607687':{'en': 'Owego, NY'},
'1509888':{'en': 'Wenatchee, WA'},
'1563289':{'en': 'Le Claire, IA'},
'1604575':{'en': 'Surrey, BC'},
'1412692':{'en': 'Pittsburgh, PA'},
'1604513':{'en': 'Langley, BC'},
'1604510':{'en': 'Langley, BC'},
'1515245':{'en': 'Des Moines, IA'},
'1515244':{'en': 'Des Moines, IA'},
'1515247':{'en': 'Des Moines, IA'},
'1515246':{'en': 'Des Moines, IA'},
'1515241':{'en': 'Des Moines, IA'},
'1515243':{'en': 'Des Moines, IA'},
'1515242':{'en': 'Des Moines, IA'},
'1610366':{'en': 'Allentown, PA'},
'1513333':{'en': 'Cincinnati, OH'},
'1507234':{'en': 'Janesville, MN'},
'1507732':{'en': 'Zumbrota, MN'},
'1513336':{'en': 'Mason, OH'},
'1505998':{'en': 'Albuquerque, NM'},
'1505994':{'en': 'Rio Rancho, NM'},
'1505995':{'en': 'Santa Fe, NM'},
'1505992':{'en': 'Santa Fe, NM'},
'1440953':{'en': 'Willoughby, OH'},
'1610369':{'en': 'Boyertown, PA'},
'1409489':{'en': 'Jasper, TX'},
'1585377':{'en': 'Fairport, NY'},
'1415750':{'en': 'San Francisco, CA'},
'1415751':{'en': 'San Francisco, CA'},
'1415752':{'en': 'San Francisco, CA'},
'1415753':{'en': 'San Francisco, CA'},
'1415759':{'en': 'San Francisco, CA'},
'1519452':{'en': 'London, ON'},
'1602712':{'en': 'Phoenix, AZ'},
'1603726':{'en': 'Campton, NH'},
'1484476':{'en': 'Wynnewood, PA'},
'1562925':{'en': 'Bellflower, CA'},
'1574389':{'en': 'Elkhart, IN'},
'1562923':{'en': 'Downey, CA'},
'1562920':{'en': 'Bellflower, CA'},
'1410879':{'en': 'Bel Air, MD'},
'1410876':{'en': 'Westminster, MD'},
'1410877':{'en': 'Fallston, MD'},
'1606475':{'en': 'Grayson, KY'},
'1606474':{'en': 'Grayson, KY'},
'1410872':{'en': 'Columbia, MD'},
'1410695':{'en': 'Odenton, MD'},
'1609704':{'en': 'Hammonton, NJ'},
'1508482':{'en': 'Milford, MA'},
'1602714':{'en': 'Phoenix, AZ'},
'1512732':{'en': 'Austin, TX'},
'1508485':{'en': 'Marlborough, MA'},
'1561962':{'en': 'Boca Raton, FL'},
'1508829':{'en': 'Holden, MA'},
'1508828':{'en': 'Taunton, MA'},
'1508487':{'en': 'Provincetown, MA'},
'1508823':{'en': 'Taunton, MA'},
'1508822':{'en': 'Taunton, MA'},
'1508821':{'en': 'Taunton, MA'},
'1508820':{'en': 'Framingham, MA'},
'1508824':{'en': 'Taunton, MA'},
'1601878':{'en': 'Terry, MS'},
'1601879':{'en': 'Flora, MS'},
'1601876':{'en': 'Tylertown, MS'},
'1540904':{'en': 'Roanoke, VA'},
'1605394':{'en': 'Rapid City, SD'},
'1605393':{'en': 'Rapid City, SD'},
'1506466':{'en': 'Saint Stephen, NB'},
'1435640':{'en': 'Park City, UT'},
'1435865':{'en': 'Cedar City, UT'},
'1435867':{'en': 'Cedar City, UT'},
'1435644':{'en': 'Kanab, UT'},
'1435645':{'en': 'Park City, UT'},
'1610933':{'en': 'Phoenixville, PA'},
'1435647':{'en': 'Park City, UT'},
'1516293':{'en': 'Farmingdale, NY'},
'1435649':{'en': 'Park City, UT'},
'1480314':{'en': 'Scottsdale, AZ'},
'1480315':{'en': 'Scottsdale, AZ'},
'1480312':{'en': 'Scottsdale, AZ'},
'1614299':{'en': 'Columbus, OH'},
'1502775':{'en': 'Louisville, KY'},
'1502774':{'en': 'Louisville, KY'},
'1502776':{'en': 'Louisville, KY'},
'1559412':{'en': 'Fresno, CA'},
'1502772':{'en': 'Louisville, KY'},
'1417476':{'en': 'Pierce City, MO'},
'1417475':{'en': 'Noel, MO'},
'1502778':{'en': 'Louisville, KY'},
'1613548':{'en': 'Kingston, ON'},
'1614529':{'en': 'Hilliard, OH'},
'1506642':{'en': 'Saint John, NB'},
'1506648':{'en': 'Saint John, NB'},
'1613545':{'en': 'Kingston, ON'},
'1613544':{'en': 'Kingston, ON'},
'1614719':{'en': 'Columbus, OH'},
'1502618':{'en': 'Louisville, KY'},
'1502614':{'en': 'Louisville, KY'},
'1469522':{'en': 'Dallas, TX'},
'1520624':{'en': 'Tucson, AZ'},
'1479785':{'en': 'Fort Smith, AR'},
'1479784':{'en': 'Fort Smith, AR'},
'1479787':{'en': 'Gravette, AR'},
'1479783':{'en': 'Fort Smith, AR'},
'1479782':{'en': 'Fort Smith, AR'},
'1479839':{'en': 'West Fork, AR'},
'1580298':{'en': 'Antlers, OK'},
'1575824':{'en': 'Chaparral, NM'},
'1505203':{'en': 'Albuquerque, NM'},
'1503691':{'en': 'Tualatin, OR'},
'1503693':{'en': 'Hillsboro, OR'},
'1503692':{'en': 'Tualatin, OR'},
'1503695':{'en': 'Corbett, OR'},
'1615620':{'en': 'Nashville, TN'},
'1503697':{'en': 'Lake Oswego, OR'},
'1503699':{'en': 'Lake Oswego, OR'},
'1503698':{'en': 'Clackamas, OR'},
'1603448':{'en': 'Lebanon, NH'},
'1517655':{'en': 'Williamston, MI'},
'1510352':{'en': 'San Leandro, CA'},
'1510353':{'en': 'Fremont, CA'},
'1517651':{'en': 'Laingsburg, MI'},
'1510357':{'en': 'San Leandro, CA'},
'1580242':{'en': 'Enid, OK'},
'1541547':{'en': 'Yachats, OR'},
'1519962':{'en': 'Windsor, ON'},
'1519963':{'en': 'London, ON'},
'1519966':{'en': 'Windsor, ON'},
'1519967':{'en': 'Windsor, ON'},
'1425374':{'en': 'Everett, WA'},
'1425377':{'en': 'Lake Stevens, WA'},
'1425373':{'en': 'Bellevue, WA'},
'1541548':{'en': 'Redmond, OR'},
'1478788':{'en': 'Macon, GA'},
'1505341':{'en': 'Albuquerque, NM'},
'1478783':{'en': 'Hawkinsville, GA'},
'1505343':{'en': 'Albuquerque, NM'},
'1478781':{'en': 'Macon, GA'},
'1505345':{'en': 'Albuquerque, NM'},
'1505344':{'en': 'Albuquerque, NM'},
'1478784':{'en': 'Macon, GA'},
'1478785':{'en': 'Macon, GA'},
'1418486':{'en': 'Lambton, QC'},
'1418484':{'en': u('Saint-\u00c9phrem-de-Beauce, QC')},
'1418480':{'en': 'Alma, QC'},
'1503963':{'en': 'Portland, OR'},
'1415512':{'en': 'San Francisco, CA'},
'1503965':{'en': 'Pacific City, OR'},
'1415513':{'en': 'San Francisco, CA'},
'1503662':{'en': 'Yamhill, OR'},
'1607431':{'en': 'Oneonta, NY'},
'1607432':{'en': 'Oneonta, NY'},
'1607433':{'en': 'Oneonta, NY'},
'1413572':{'en': 'Westfield, MA'},
'1571261':{'en': 'Gainesville, VA'},
'1519383':{'en': 'Sarnia, ON'},
'1412221':{'en': 'Bridgeville, PA'},
'1412220':{'en': 'Bridgeville, PA'},
'1415503':{'en': 'San Francisco, CA'},
'1415502':{'en': 'San Francisco, CA'},
'1415504':{'en': 'San Francisco, CA'},
'1415507':{'en': 'San Rafael, CA'},
'1412734':{'en': 'Pittsburgh, PA'},
'1504347':{'en': 'Marrero, LA'},
'1530467':{'en': 'Etna, CA'},
'1504340':{'en': 'Marrero, LA'},
'1504341':{'en': 'Marrero, LA'},
'1530468':{'en': 'Fort Jones, CA'},
'1504348':{'en': 'Marrero, LA'},
'1504349':{'en': 'Marrero, LA'},
'1509473':{'en': 'Spokane, WA'},
'1603228':{'en': 'Concord, NH'},
'1509477':{'en': 'Spokane, WA'},
'1509476':{'en': 'Oroville, WA'},
'1509475':{'en': 'Spokane, WA'},
'1509474':{'en': 'Spokane, WA'},
'1603223':{'en': 'Concord, NH'},
'1450314':{'en': 'Laval, QC'},
'1518383':{'en': 'Clifton Park, NY'},
'1518382':{'en': 'Schenectady, NY'},
'1518381':{'en': 'Schenectady, NY'},
'1603226':{'en': 'Concord, NH'},
'1512929':{'en': 'Austin, TX'},
'1505836':{'en': 'Albuquerque, NM'},
'1604709':{'en': 'Vancouver, BC'},
'1604708':{'en': 'Vancouver, BC'},
'1505833':{'en': 'Albuquerque, NM'},
'1505832':{'en': 'Moriarty, NM'},
'1505831':{'en': 'Albuquerque, NM'},
'1505830':{'en': 'Albuquerque, NM'},
'1604703':{'en': 'Chilliwack, BC'},
'1604702':{'en': 'Chilliwack, BC'},
'1586758':{'en': 'Warren, MI'},
'1505839':{'en': 'Albuquerque, NM'},
'1512926':{'en': 'Austin, TX'},
'1408947':{'en': 'San Jose, CA'},
'1408946':{'en': 'Milpitas, CA'},
'1408945':{'en': 'Milpitas, CA'},
'1408942':{'en': 'Milpitas, CA'},
'1408941':{'en': 'Milpitas, CA'},
'1586756':{'en': 'Warren, MI'},
'1573729':{'en': 'Salem, MO'},
'1520531':{'en': 'Tucson, AZ'},
'1586754':{'en': 'Warren, MI'},
'1615248':{'en': 'Nashville, TN'},
'1615244':{'en': 'Nashville, TN'},
'1615242':{'en': 'Nashville, TN'},
'1614459':{'en': 'Columbus, OH'},
'1509698':{'en': 'Selah, WA'},
'1509697':{'en': 'Selah, WA'},
'1586576':{'en': 'Warren, MI'},
'1540547':{'en': 'Culpeper, VA'},
'1540552':{'en': 'Blacksburg, VA'},
'1586574':{'en': 'Warren, MI'},
'1614453':{'en': 'Columbus, OH'},
'1573732':{'en': 'Bourbon, MO'},
'1506876':{'en': 'Saint-Louis de Kent, NB'},
'1573736':{'en': 'Crocker, MO'},
'1419448':{'en': 'Tiffin, OH'},
'1614451':{'en': 'Columbus, OH'},
'1608868':{'en': 'Milton, WI'},
'1423643':{'en': 'Chattanooga, TN'},
'1520287':{'en': 'Nogales, AZ'},
'1419443':{'en': 'Tiffin, OH'},
'1520281':{'en': 'Nogales, AZ'},
'1419445':{'en': 'Archbold, OH'},
'1419446':{'en': 'Archbold, OH'},
'1419447':{'en': 'Tiffin, OH'},
'1507694':{'en': 'Ivanhoe, MN'},
'1585742':{'en': 'Victor, NY'},
'1561208':{'en': 'Boca Raton, FL'},
'1414365':{'en': 'Milwaukee, WI'},
'1561200':{'en': 'Boynton Beach, FL'},
'1608819':{'en': 'Madison, WI'},
'1419502':{'en': 'Sandusky, OH'},
'1503361':{'en': 'Salem, OR'},
'1480814':{'en': 'Chandler, AZ'},
'1503363':{'en': 'Salem, OR'},
'1480816':{'en': 'Fountain Hills, AZ'},
'1503365':{'en': 'Salem, OR'},
'1503364':{'en': 'Salem, OR'},
'1503366':{'en': 'St. Helens, OR'},
'1503368':{'en': 'Nehalem, OR'},
'1507474':{'en': 'Winona, MN'},
'1610743':{'en': 'Reading, PA'},
'1610740':{'en': 'Allentown, PA'},
'1610746':{'en': 'Nazareth, PA'},
'1570748':{'en': 'Lock Haven, PA'},
'1601487':{'en': 'Jackson, MS'},
'1601485':{'en': 'Meridian, MS'},
'1601484':{'en': 'Meridian, MS'},
'1601483':{'en': 'Meridian, MS'},
'1601482':{'en': 'Meridian, MS'},
'1613216':{'en': 'Ottawa, ON'},
'1614621':{'en': 'Columbus, OH'},
'1435986':{'en': 'St. George, UT'},
'1417861':{'en': 'Springfield, MO'},
'1417862':{'en': 'Springfield, MO'},
'1417863':{'en': 'Springfield, MO'},
'1417864':{'en': 'Springfield, MO'},
'1417865':{'en': 'Springfield, MO'},
'1417866':{'en': 'Springfield, MO'},
'1417868':{'en': 'Springfield, MO'},
'1417869':{'en': 'Springfield, MO'},
'1530923':{'en': 'Yuba City, CA'},
'1541738':{'en': 'Corvallis, OR'},
'1414873':{'en': 'Milwaukee, WI'},
'1541734':{'en': 'Medford, OR'},
'1541736':{'en': 'Springfield, OR'},
'1541737':{'en': 'Corvallis, OR'},
'1541732':{'en': 'Medford, OR'},
'1480767':{'en': 'Scottsdale, AZ'},
'1606285':{'en': 'Martin, KY'},
'1606286':{'en': 'Olive Hill, KY'},
'1606287':{'en': 'McKee, KY'},
'1410488':{'en': 'Baltimore, MD'},
'1410486':{'en': 'Pikesville, MD'},
'1410485':{'en': 'Baltimore, MD'},
'1410484':{'en': 'Pikesville, MD'},
'1410483':{'en': 'Baltimore, MD'},
'1410482':{'en': 'Greensboro, MD'},
'1410480':{'en': 'Ellicott City, MD'},
'1418679':{'en': 'St-Felicien, QC'},
'1519471':{'en': 'London, ON'},
'1614865':{'en': 'Westerville, OH'},
'1418673':{'en': u('Saint-Honor\u00e9, QC')},
'1617247':{'en': 'Boston, MA'},
'1617242':{'en': 'Charlestown, MA'},
'1617243':{'en': 'Newton, MA'},
'1617241':{'en': 'Charlestown, MA'},
'1580596':{'en': 'Cherokee, OK'},
'1617248':{'en': 'Boston, MA'},
'1508645':{'en': 'Chilmark, MA'},
'1513729':{'en': 'Cincinnati, OH'},
'1516487':{'en': 'Great Neck, NY'},
'1513724':{'en': 'Williamsburg, OH'},
'1513727':{'en': 'Middletown, OH'},
'1513721':{'en': 'Cincinnati, OH'},
'1580625':{'en': 'Beaver, OK'},
'1479314':{'en': 'Fort Smith, AR'},
'1580623':{'en': 'Watonga, OK'},
'1580622':{'en': 'Sulphur, OK'},
'1501202':{'en': 'Little Rock, AR'},
'1501205':{'en': 'Conway, AR'},
'1501206':{'en': 'Heber Springs, AR'},
'1562948':{'en': 'Pico Rivera, CA'},
'1434582':{'en': 'Lynchburg, VA'},
'1603598':{'en': 'Nashua, NH'},
'1434589':{'en': 'Palmyra, VA'},
'1513896':{'en': 'Hamilton, OH'},
'1513897':{'en': 'Waynesville, OH'},
'1513894':{'en': 'Hamilton, OH'},
'1513895':{'en': 'Hamilton, OH'},
'1513892':{'en': 'Hamilton, OH'},
'1513893':{'en': 'Hamilton, OH'},
'1612302':{'en': 'Minneapolis, MN'},
'1513891':{'en': 'Cincinnati, OH'},
'1610489':{'en': 'Collegeville, PA'},
'1601553':{'en': 'Meridian, MS'},
'1513899':{'en': 'Morrow, OH'},
'1530671':{'en': 'Yuba City, CA'},
'1513541':{'en': 'Cincinnati, OH'},
'1513542':{'en': 'Cincinnati, OH'},
'1530674':{'en': 'Yuba City, CA'},
'1570348':{'en': 'Scranton, PA'},
'1502409':{'en': 'Louisville, KY'},
'1585413':{'en': 'Rochester, NY'},
'1530583':{'en': 'Tahoe City, CA'},
'1530582':{'en': 'Truckee, CA'},
'1530581':{'en': 'Tahoe City, CA'},
'1530587':{'en': 'Truckee, CA'},
'1515965':{'en': 'Ankeny, IA'},
'1530589':{'en': 'Oroville, CA'},
'1559783':{'en': 'Porterville, CA'},
'1608752':{'en': 'Janesville, WI'},
'1607257':{'en': 'Ithaca, NY'},
'1608754':{'en': 'Janesville, WI'},
'1608755':{'en': 'Janesville, WI'},
'1434324':{'en': 'Hurt, VA'},
'1423392':{'en': 'Kingsport, TN'},
'1608204':{'en': 'Madison, WI'},
'1608205':{'en': 'Stoughton, WI'},
'1570675':{'en': 'Dallas, PA'},
'1570674':{'en': 'Dallas, PA'},
'1570673':{'en': 'Canton, PA'},
'1478374':{'en': 'Eastman, GA'},
'1575289':{'en': 'Cuba, NM'},
'1425493':{'en': 'Mukilteo, WA'},
'1425497':{'en': 'Redmond, WA'},
'1419298':{'en': 'Edgerton, OH'},
'1413637':{'en': 'Lenox, MA'},
'1419294':{'en': 'Upper Sandusky, OH'},
'1419291':{'en': 'Toledo, OH'},
'1419293':{'en': 'McComb, OH'},
'1604214':{'en': 'Richmond, BC'},
'1509868':{'en': 'Spokane, WA'},
'1509865':{'en': 'Toppenish, WA'},
'1509863':{'en': 'Spokane, WA'},
'1519737':{'en': 'Maidstone, ON'},
'1519736':{'en': 'Amherstburg, ON'},
'1604574':{'en': 'Surrey, BC'},
'1480804':{'en': 'Tempe, AZ'},
'1519733':{'en': 'Kingsville, ON'},
'1519738':{'en': 'Harrow, ON'},
'1613728':{'en': 'Ottawa, ON'},
'1478994':{'en': 'Forsyth, GA'},
'1478992':{'en': 'Forsyth, GA'},
'1517423':{'en': 'Tecumseh, MI'},
'1519653':{'en': 'Cambridge, ON'},
'1510523':{'en': 'Alameda, CA'},
'1603626':{'en': 'Manchester, NH'},
'1604392':{'en': 'Chilliwack, BC'},
'1423648':{'en': 'Chattanooga, TN'},
'1415776':{'en': 'San Francisco, CA'},
'1415777':{'en': 'San Francisco, CA'},
'1415775':{'en': 'San Francisco, CA'},
'1415772':{'en': 'San Francisco, CA'},
'1415773':{'en': 'San Francisco, CA'},
'1415771':{'en': 'San Francisco, CA'},
'1541899':{'en': 'Jacksonville, OR'},
'1519655':{'en': 'Tavistock, ON'},
'1541895':{'en': 'Creswell, OR'},
'1541466':{'en': 'Brownsville, OR'},
'1563547':{'en': 'Cresco, IA'},
'1605627':{'en': 'Volga, SD'},
'1605626':{'en': 'Aberdeen, SD'},
'1605624':{'en': 'Vermillion, SD'},
'1605622':{'en': 'Aberdeen, SD'},
'1410819':{'en': 'Easton, MD'},
'1562942':{'en': 'Pico Rivera, CA'},
'1604696':{'en': 'Vancouver, BC'},
'1610481':{'en': 'Allentown, PA'},
'1562945':{'en': 'Whittier, CA'},
'1562946':{'en': 'Santa Fe Springs, CA'},
'1562947':{'en': 'Whittier, CA'},
'1410810':{'en': 'Chestertown, MD'},
'1562949':{'en': 'Pico Rivera, CA'},
'1410814':{'en': 'Baltimore, MD'},
'1610488':{'en': 'Bernville, PA'},
'1606456':{'en': 'Phelps, KY'},
'1559784':{'en': 'Porterville, CA'},
'1423468':{'en': 'Chattanooga, TN'},
'1559781':{'en': 'Porterville, CA'},
'1559782':{'en': 'Porterville, CA'},
'1512719':{'en': 'Austin, TX'},
'1512715':{'en': 'Burnet, TX'},
'1559788':{'en': 'Porterville, CA'},
'1423396':{'en': 'Ooltewah, TN'},
'1561948':{'en': 'Boca Raton, FL'},
'1440974':{'en': 'Mentor, OH'},
'1440975':{'en': 'Willoughby, OH'},
'1540994':{'en': 'Pulaski, VA'},
'1601815':{'en': 'Jackson, MS'},
'1610261':{'en': 'Northampton, PA'},
'1610262':{'en': 'Northampton, PA'},
'1610265':{'en': 'King of Prussia, PA'},
'1610269':{'en': 'Downingtown, PA'},
'1610268':{'en': 'Avondale, PA'},
'1435843':{'en': 'Tooele, UT'},
'1614901':{'en': 'Westerville, OH'},
'1580458':{'en': 'Fort Sill, OK'},
'1559438':{'en': 'Fresno, CA'},
'1559439':{'en': 'Fresno, CA'},
'1417451':{'en': 'Neosho, MO'},
'1559437':{'en': 'Fresno, CA'},
'1559434':{'en': 'Fresno, CA'},
'1559435':{'en': 'Fresno, CA'},
'1417455':{'en': 'Neosho, MO'},
'1559433':{'en': 'Fresno, CA'},
'1559431':{'en': 'Fresno, CA'},
'1613688':{'en': 'Ottawa, ON'},
'1613680':{'en': 'Ottawa, ON'},
'1613687':{'en': 'Petawawa, ON'},
'1617253':{'en': 'Cambridge, MA'},
'1417637':{'en': 'Greenfield, MO'},
'1602305':{'en': 'Phoenix, AZ'},
'1616828':{'en': 'Grand Rapids, MI'},
'1559436':{'en': 'Fresno, CA'},
'1602307':{'en': 'Phoenix, AZ'},
'1561417':{'en': 'Boca Raton, FL'},
'1561416':{'en': 'Boca Raton, FL'},
'1415884':{'en': 'Novato, CA'},
'1559432':{'en': 'Fresno, CA'},
'1605845':{'en': 'Mobridge, SD'},
'1480484':{'en': 'Scottsdale, AZ'},
'1480483':{'en': 'Scottsdale, AZ'},
'1606633':{'en': 'Whitesburg, KY'},
'1480481':{'en': 'Scottsdale, AZ'},
'1443444':{'en': 'Baltimore, MD'},
'1606638':{'en': 'Louisa, KY'},
'1502326':{'en': 'Louisville, KY'},
'1541385':{'en': 'Bend, OR'},
'1541384':{'en': 'Condon, OR'},
'1541387':{'en': 'Hood River, OR'},
'1541386':{'en': 'Hood River, OR'},
'1541383':{'en': 'Bend, OR'},
'1541382':{'en': 'Bend, OR'},
'1541389':{'en': 'Bend, OR'},
'1541388':{'en': 'Bend, OR'},
'1505228':{'en': 'Albuquerque, NM'},
'1505224':{'en': 'Albuquerque, NM'},
'1505220':{'en': 'Albuquerque, NM'},
'1450':{'en': 'Quebec'},
'1513398':{'en': 'Mason, OH'},
'1458':{'en': 'Oregon'},
'1443664':{'en': 'Ocean City, MD'},
'1502899':{'en': 'Louisville, KY'},
'1415587':{'en': 'San Francisco, CA'},
'1517676':{'en': 'Mason, MI'},
'1502891':{'en': 'Louisville, KY'},
'1502893':{'en': 'Louisville, KY'},
'1502894':{'en': 'Louisville, KY'},
'1502895':{'en': 'Louisville, KY'},
'1502896':{'en': 'Louisville, KY'},
'1502897':{'en': 'Louisville, KY'},
'1505323':{'en': 'Albuquerque, NM'},
'1570883':{'en': 'Pittston, PA'},
'1505321':{'en': 'Albuquerque, NM'},
'1505320':{'en': 'Farmington, NM'},
'1505327':{'en': 'Farmington, NM'},
'1505326':{'en': 'Farmington, NM'},
'1505325':{'en': 'Farmington, NM'},
'1505324':{'en': 'Farmington, NM'},
'1519942':{'en': 'Orangeville, ON'},
'1519940':{'en': 'Orangeville, ON'},
'1519941':{'en': 'Orangeville, ON'},
'1519946':{'en': 'Windsor, ON'},
'1519944':{'en': 'Windsor, ON'},
'1519945':{'en': 'Windsor, ON'},
'1503945':{'en': 'Salem, OR'},
'1503946':{'en': 'Portland, OR'},
'1503943':{'en': 'Portland, OR'},
'1415945':{'en': 'Corte Madera, CA'},
'1508693':{'en': 'Vineyard Haven, MA'},
'1514279':{'en': 'Montreal, QC'},
'1514278':{'en': 'Montreal, QC'},
'1514277':{'en': 'Montreal, QC'},
'1514276':{'en': 'Montreal, QC'},
'1514274':{'en': 'Montreal, QC'},
'1514273':{'en': 'Montreal, QC'},
'1514272':{'en': 'Montreal, QC'},
'1514271':{'en': 'Montreal, QC'},
'1514270':{'en': 'Montreal, QC'},
'1513977':{'en': 'Cincinnati, OH'},
'1608687':{'en': 'Fountain City, WI'},
'1520426':{'en': 'Casa Grande, AZ'},
'1520421':{'en': 'Casa Grande, AZ'},
'1432652':{'en': 'McCamey, TX'},
'1520423':{'en': 'Casa Grande, AZ'},
'1504322':{'en': 'New Orleans, LA'},
'1412624':{'en': 'Pittsburgh, PA'},
'1504328':{'en': 'Marrero, LA'},
'1440366':{'en': 'Elyria, OH'},
'1440365':{'en': 'Elyria, OH'},
'1509459':{'en': 'Spokane, WA'},
'1509458':{'en': 'Spokane, WA'},
'1509328':{'en': 'Spokane, WA'},
'1509327':{'en': 'Spokane, WA'},
'1509454':{'en': 'Yakima, WA'},
'1509457':{'en': 'Yakima, WA'},
'1450332':{'en': 'Longueuil, QC'},
'1509323':{'en': 'Spokane, WA'},
'1509453':{'en': 'Yakima, WA'},
'1509452':{'en': 'Yakima, WA'},
'1508324':{'en': 'Fall River, MA'},
'1508497':{'en': 'Hopkinton, MA'},
'1508495':{'en': 'Falmouth, MA'},
'1604982':{'en': 'North Vancouver, BC'},
'1615264':{'en': 'Hendersonville, TN'},
'1615262':{'en': 'Nashville, TN'},
'1615261':{'en': 'Franklin, TN'},
'1615269':{'en': 'Nashville, TN'},
'1520515':{'en': 'Sierra Vista, AZ'},
'1520514':{'en': 'Tucson, AZ'},
'1520512':{'en': 'Tucson, AZ'},
'1412243':{'en': 'Pittsburgh, PA'},
'1412242':{'en': 'Pittsburgh, PA'},
'1415561':{'en': 'San Francisco, CA'},
'1412247':{'en': 'Pittsburgh, PA'},
'1412246':{'en': 'Pittsburgh, PA'},
'1415565':{'en': 'San Francisco, CA'},
'1415564':{'en': 'San Francisco, CA'},
'1573751':{'en': 'Jefferson City, MO'},
'1573756':{'en': 'Farmington, MO'},
'1573754':{'en': 'Louisiana, MO'},
'1573759':{'en': 'Dixon, MO'},
'1419462':{'en': 'Galion, OH'},
'1603863':{'en': 'Newport, NH'},
'1603862':{'en': 'Durham, NH'},
'1419465':{'en': 'Monroeville, OH'},
'1540574':{'en': 'Harrisonburg, VA'},
'1419468':{'en': 'Galion, OH'},
'1603868':{'en': 'Durham, NH'},
'1484664':{'en': 'Allentown, PA'},
'1480778':{'en': 'Scottsdale, AZ'},
'1609818':{'en': 'Pennington, NJ'},
'1608807':{'en': 'Madison, WI'},
'1512943':{'en': 'Georgetown, TX'},
'1574825':{'en': 'Middlebury, IN'},
'1562570':{'en': 'Long Beach, CA'},
'1414389':{'en': 'Milwaukee, WI'},
'1414384':{'en': 'Milwaukee, WI'},
'1414385':{'en': 'Milwaukee, WI'},
'1425957':{'en': 'Bellevue, WA'},
'1561883':{'en': 'Boca Raton, FL'},
'1601713':{'en': 'Jackson, MS'},
'1414383':{'en': 'Milwaukee, WI'},
'1571434':{'en': 'Sterling, VA'},
'1415387':{'en': 'San Francisco, CA'},
'1415386':{'en': 'San Francisco, CA'},
'1606849':{'en': 'Flemingsburg, KY'},
'1415383':{'en': 'Mill Valley, CA'},
'1415382':{'en': 'Novato, CA'},
'1415381':{'en': 'Mill Valley, CA'},
'1415380':{'en': 'Mill Valley, CA'},
'1606843':{'en': 'East Bernstadt, KY'},
'1510814':{'en': 'Alameda, CA'},
'1415389':{'en': 'Mill Valley, CA'},
'1415388':{'en': 'Mill Valley, CA'},
'1559846':{'en': 'Kerman, CA'},
'1559841':{'en': 'Shaver Lake, CA'},
'1559840':{'en': 'Fresno, CA'},
'1506235':{'en': 'Saint-Quentin, NB'},
'1410544':{'en': 'Severna Park, MD'},
'1410719':{'en': 'Catonsville, MD'},
'1410715':{'en': 'Columbia, MD'},
'1580588':{'en': 'Apache, OK'},
'1512365':{'en': 'Taylor, TX'},
'1615834':{'en': 'Nashville, TN'},
'1418736':{'en': 'Le Bic, QC'},
'1417848':{'en': 'Springfield, MO'},
'1530332':{'en': 'Chico, CA'},
'1417847':{'en': 'Cassville, MO'},
'1417845':{'en': 'Anderson, MO'},
'1503772':{'en': 'Portland, OR'},
'1503771':{'en': 'Portland, OR'},
'1503777':{'en': 'Portland, OR'},
'1503774':{'en': 'Portland, OR'},
'1503775':{'en': 'Portland, OR'},
'1518834':{'en': 'Keeseville, NY'},
'1613273':{'en': 'Westport, ON'},
'1434832':{'en': 'Lynchburg, VA'},
'1613270':{'en': 'Kanata, ON'},
'1617225':{'en': 'Cambridge, MA'},
'1434836':{'en': 'Danville, VA'},
'1617227':{'en': 'Boston, MA'},
'1613279':{'en': 'Sharbot Lake, ON'},
'1520682':{'en': 'Marana, AZ'},
'1501954':{'en': 'Little Rock, AR'},
'1501955':{'en': 'N Little Rock, AR'},
'1501221':{'en': 'Little Rock, AR'},
'1501227':{'en': 'Little Rock, AR'},
'1501224':{'en': 'Little Rock, AR'},
'1501225':{'en': 'Little Rock, AR'},
'1501228':{'en': 'Little Rock, AR'},
'1517467':{'en': 'Onsted, MI'},
'1562408':{'en': 'Paramount, CA'},
'1575885':{'en': 'Carlsbad, NM'},
'1615822':{'en': 'Hendersonville, TN'},
'1575556':{'en': 'Las Cruces, NM'},
'1408776':{'en': 'Morgan Hill, CA'},
'1408777':{'en': 'Cupertino, CA'},
'1408773':{'en': 'Sunnyvale, CA'},
'1408778':{'en': 'Morgan Hill, CA'},
'1408779':{'en': 'Morgan Hill, CA'},
'1615797':{'en': 'White Bluff, TN'},
'1513563':{'en': 'Cincinnati, OH'},
'1513561':{'en': 'Cincinnati, OH'},
'1615826':{'en': 'Hendersonville, TN'},
'1519351':{'en': 'Chatham, ON'},
'1518481':{'en': 'Malone, NY'},
'1518482':{'en': 'Albany, NY'},
'1518483':{'en': 'Malone, NY'},
'1518487':{'en': 'Albany, NY'},
'1603522':{'en': 'Sanbornville, NH'},
'1518489':{'en': 'Albany, NY'},
'1603526':{'en': 'New London, NH'},
'1603527':{'en': 'Laconia, NH'},
'1603524':{'en': 'Laconia, NH'},
'1502429':{'en': 'Louisville, KY'},
'1561620':{'en': 'Boca Raton, FL'},
'1502423':{'en': 'Louisville, KY'},
'1519354':{'en': 'Chatham, ON'},
'1502425':{'en': 'Louisville, KY'},
'1501945':{'en': 'N Little Rock, AR'},
'1502426':{'en': 'Louisville, KY'},
'1419927':{'en': 'Sycamore, OH'},
'1604408':{'en': 'Vancouver, BC'},
'1419925':{'en': 'Maria Stein, OH'},
'1419924':{'en': 'West Unity, OH'},
'1570474':{'en': 'Mountain Top, PA'},
'1419929':{'en': 'New London, OH'},
'1519358':{'en': 'Chatham, ON'},
'1416408':{'en': 'Toronto, ON'},
'1413436':{'en': 'Warren, MA'},
'1416406':{'en': 'Toronto, ON'},
'1519533':{'en': 'Woodstock, ON'},
'1519537':{'en': 'Woodstock, ON'},
'1519534':{'en': 'Wiarton, ON'},
'1519539':{'en': 'Woodstock, ON'},
'1412521':{'en': 'Pittsburgh, PA'},
'1602381':{'en': 'Phoenix, AZ'},
'1602382':{'en': 'Phoenix, AZ'},
'1602439':{'en': 'Glendale, AZ'},
'1570698':{'en': 'Lake Ariel, PA'},
'1602437':{'en': 'Phoenix, AZ'},
'1509734':{'en': 'Kennewick, WA'},
'1602926':{'en': 'Phoenix, AZ'},
'1570693':{'en': 'Wyoming, PA'},
'1602923':{'en': 'Phoenix, AZ'},
'1518220':{'en': 'Latham, NY'},
'1509843':{'en': 'Pomeroy, WA'},
'1607359':{'en': 'Addison, NY'},
'1608654':{'en': 'Cashton, WI'},
'1603382':{'en': 'Plaistow, NH'},
'1603383':{'en': 'Jackson, NH'},
'1509738':{'en': 'Kettle Falls, WA'},
'1604558':{'en': 'Vancouver, BC'},
'1519284':{'en': 'St. Marys, ON'},
'1519287':{'en': 'Glencoe, ON'},
'1604556':{'en': 'Abbotsford, BC'},
'1604557':{'en': 'Abbotsford, BC'},
'1501776':{'en': 'Benton, AR'},
'1515289':{'en': 'Ankeny, IA'},
'1515288':{'en': 'Des Moines, IA'},
'1515281':{'en': 'Des Moines, IA'},
'1515280':{'en': 'Des Moines, IA'},
'1515283':{'en': 'Des Moines, IA'},
'1515282':{'en': 'Des Moines, IA'},
'1515285':{'en': 'Des Moines, IA'},
'1515284':{'en': 'Des Moines, IA'},
'1515287':{'en': 'Des Moines, IA'},
'1515286':{'en': 'Des Moines, IA'},
'1602462':{'en': 'Phoenix, AZ'},
'1412383':{'en': 'Pittsburgh, PA'},
'1412380':{'en': 'Monroeville, PA'},
'1412381':{'en': 'Pittsburgh, PA'},
'1514484':{'en': 'Montreal, QC'},
'1514485':{'en': 'Montreal, QC'},
'1514486':{'en': 'Montreal, QC'},
'1514487':{'en': 'Montreal, QC'},
'1508799':{'en': 'Worcester, MA'},
'1514481':{'en': 'Montreal, QC'},
'1514482':{'en': 'Montreal, QC'},
'1514483':{'en': 'Montreal, QC'},
'1508795':{'en': 'Worcester, MA'},
'1508797':{'en': 'Worcester, MA'},
'1508791':{'en': 'Worcester, MA'},
'1514489':{'en': 'Montreal, QC'},
'1508793':{'en': 'Worcester, MA'},
'1508792':{'en': 'Worcester, MA'},
'1607539':{'en': 'Brooktondale, NY'},
'1575439':{'en': 'Alamogordo, NM'},
'1615341':{'en': 'Nashville, TN'},
'1409994':{'en': 'Buna, TX'},
'1585338':{'en': 'Rochester, NY'},
'1512556':{'en': 'Lampasas, TX'},
'1609292':{'en': 'Trenton, NJ'},
'1423664':{'en': 'Chattanooga, TN'},
'1585336':{'en': 'Rochester, NY'},
'1609523':{'en': 'Wildwood, NJ'},
'1514738':{'en': 'Montreal, QC'},
'1514739':{'en': 'Montreal, QC'},
'1514736':{'en': 'Montreal, QC'},
'1514737':{'en': 'Montreal, QC'},
'1514735':{'en': 'Montreal, QC'},
'1514733':{'en': 'Montreal, QC'},
'1514731':{'en': 'Montreal, QC'},
'1501767':{'en': 'Hot Springs, AR'},
'1501764':{'en': 'Conway, AR'},
'1563568':{'en': 'Waukon, IA'},
'1501760':{'en': 'Hot Springs, AR'},
'1530666':{'en': 'Woodland, CA'},
'1423915':{'en': 'Johnson City, TN'},
'1423913':{'en': 'Jonesborough, TN'},
'1610469':{'en': 'Pottstown, PA'},
'1423442':{'en': 'Madisonville, TN'},
'1610466':{'en': 'Coatesville, PA'},
'1562216':{'en': 'Long Beach, CA'},
'1562961':{'en': 'Long Beach, CA'},
'1512778':{'en': 'Liberty Hill, TX'},
'1612332':{'en': 'Minneapolis, MN'},
'1502228':{'en': 'Prospect, KY'},
'1502227':{'en': 'Frankfort, KY'},
'1502226':{'en': 'Frankfort, KY'},
'1502225':{'en': 'La Grange, KY'},
'1502223':{'en': 'Frankfort, KY'},
'1502222':{'en': 'La Grange, KY'},
'1609747':{'en': 'Burlington Township, NJ'},
'1601833':{'en': 'Brookhaven, MS'},
'1601384':{'en': 'Meadville, MS'},
'1601835':{'en': 'Brookhaven, MS'},
'1601389':{'en': 'Philadelphia, MS'},
'1540298':{'en': 'Elkton, VA'},
'1520896':{'en': 'Oracle, AZ'},
'1440998':{'en': 'Ashtabula, OH'},
'1504689':{'en': 'Lafitte, LA'},
'1440997':{'en': 'Ashtabula, OH'},
'1440992':{'en': 'Ashtabula, OH'},
'1440993':{'en': 'Ashtabula, OH'},
'1610208':{'en': 'Reading, PA'},
'1507334':{'en': 'Faribault, MN'},
'1507332':{'en': 'Faribault, MN'},
'1507333':{'en': 'Faribault, MN'},
'1414447':{'en': 'Milwaukee, WI'},
'1559459':{'en': 'Fresno, CA'},
'1414445':{'en': 'Milwaukee, WI'},
'1414444':{'en': 'Milwaukee, WI'},
'1414443':{'en': 'Milwaukee, WI'},
'1414442':{'en': 'Milwaukee, WI'},
'1559450':{'en': 'Fresno, CA'},
'1559452':{'en': 'Fresno, CA'},
'1559453':{'en': 'Fresno, CA'},
'1559454':{'en': 'Fresno, CA'},
'1559455':{'en': 'Fresno, CA'},
'1414449':{'en': 'Milwaukee, WI'},
'1559457':{'en': 'Fresno, CA'},
'1573568':{'en': 'Bloomfield, MO'},
'1540743':{'en': 'Luray, VA'},
'1540740':{'en': 'New Market, VA'},
'1540741':{'en': 'Fredericksburg, VA'},
'1540745':{'en': 'Floyd, VA'},
'1573564':{'en': 'Montgomery City, MO'},
'1506684':{'en': 'Dalhousie, NB'},
'1606433':{'en': 'Pikeville, KY'},
'1410833':{'en': 'Reisterstown, MD'},
'1410383':{'en': 'Baltimore, MD'},
'1410836':{'en': 'Bel Air, MD'},
'1410837':{'en': 'Baltimore, MD'},
'1410386':{'en': 'Westminster, MD'},
'1410835':{'en': 'Pittsville, MD'},
'1410838':{'en': 'Bel Air, MD'},
'1541564':{'en': 'Hermiston, OR'},
'1541567':{'en': 'Hermiston, OR'},
'1605867':{'en': 'Pine Ridge, SD'},
'1601528':{'en': 'Wiggins, MS'},
'1570888':{'en': 'Sayre, PA'},
'1505798':{'en': 'Albuquerque, NM'},
'1505796':{'en': 'Albuquerque, NM'},
'1505797':{'en': 'Albuquerque, NM'},
'1505795':{'en': 'Santa Fe, NM'},
'1505792':{'en': 'Albuquerque, NM'},
'1480350':{'en': 'Tempe, AZ'},
'1480357':{'en': 'Mesa, AZ'},
'1480354':{'en': 'Mesa, AZ'},
'1614921':{'en': 'Hilliard, OH'},
'1516705':{'en': 'Rockville Centre, NY'},
'1516256':{'en': 'Valley Stream, NY'},
'1480358':{'en': 'Mesa, AZ'},
'1603532':{'en': 'Jaffrey, NH'},
'1541367':{'en': 'Sweet Home, OR'},
'1505248':{'en': 'Albuquerque, NM'},
'1505249':{'en': 'Albuquerque, NM'},
'1410526':{'en': 'Reisterstown, MD'},
'1410521':{'en': 'Randallstown, MD'},
'1443643':{'en': 'Bel Air, MD'},
'1410523':{'en': 'Baltimore, MD'},
'1505242':{'en': 'Albuquerque, NM'},
'1505243':{'en': 'Albuquerque, NM'},
'1505244':{'en': 'Albuquerque, NM'},
'1505246':{'en': 'Albuquerque, NM'},
'1505247':{'en': 'Albuquerque, NM'},
'1470':{'en': 'Georgia'},
'1475':{'en': 'Connecticut'},
'1409737':{'en': 'Galveston, TX'},
'1478':{'en': 'Georgia'},
'1479':{'en': 'Arkansas'},
'1410374':{'en': 'Hampstead, MD'},
'1409735':{'en': 'Bridge City, TX'},
'1410379':{'en': 'Elkridge, MD'},
'1570868':{'en': 'Mountain Top, PA'},
'1505304':{'en': 'Albuquerque, NM'},
'1541506':{'en': 'The Dalles, OR'},
'1541505':{'en': 'Eugene, OR'},
'1541504':{'en': 'Redmond, OR'},
'1409347':{'en': 'Beaumont, TX'},
'1580927':{'en': 'Coalgate, OK'},
'1415929':{'en': 'San Francisco, CA'},
'1415928':{'en': 'San Francisco, CA'},
'1580922':{'en': 'Seiling, OK'},
'1580920':{'en': 'Durant, OK'},
'1580921':{'en': 'Laverne, OK'},
'1415923':{'en': 'San Francisco, CA'},
'1415922':{'en': 'San Francisco, CA'},
'1415921':{'en': 'San Francisco, CA'},
'1415920':{'en': 'San Francisco, CA'},
'1415927':{'en': 'Corte Madera, CA'},
'1415925':{'en': 'Greenbrae, CA'},
'1415924':{'en': 'Corte Madera, CA'},
'1573449':{'en': 'Columbia, MO'},
'1514259':{'en': 'Montreal, QC'},
'1616786':{'en': 'Holland, MI'},
'1514251':{'en': 'Montreal, QC'},
'1514253':{'en': 'Montreal, QC'},
'1514252':{'en': 'Montreal, QC'},
'1514255':{'en': 'Montreal, QC'},
'1514254':{'en': 'Montreal, QC'},
'1514257':{'en': 'Montreal, QC'},
'1514256':{'en': 'Montreal, QC'},
'1440204':{'en': 'Lorain, OH'},
'1440205':{'en': 'Mentor, OH'},
'1440209':{'en': 'Mentor, OH'},
'1507483':{'en': 'Adrian, MN'},
'1608287':{'en': 'Madison, WI'},
'1530335':{'en': 'Burney, CA'},
'1614527':{'en': 'Hilliard, OH'},
'1604815':{'en': 'Squamish, BC'},
'1573447':{'en': 'Columbia, MO'},
'1512485':{'en': 'Austin, TX'},
'1601798':{'en': 'Picayune, MS'},
'1614523':{'en': 'Westerville, OH'},
'1423775':{'en': 'Dayton, TN'},
'1450357':{'en': 'Saint-Jean-sur-Richelieu, QC'},
'1504302':{'en': 'New Orleans, LA'},
'1450359':{'en': 'Saint-Jean-sur-Richelieu, QC'},
'1504301':{'en': 'New Orleans, LA'},
'1504304':{'en': 'New Orleans, LA'},
'1504305':{'en': 'Kenner, LA'},
'1509301':{'en': 'Walla Walla, WA'},
'1415641':{'en': 'San Francisco, CA'},
'1614525':{'en': 'Columbus, OH'},
'1505873':{'en': 'Albuquerque, NM'},
'1505872':{'en': 'Albuquerque, NM'},
'1505877':{'en': 'Albuquerque, NM'},
'1416364':{'en': 'Toronto, ON'},
'1416365':{'en': 'Toronto, ON'},
'1416366':{'en': 'Toronto, ON'},
'1416367':{'en': 'Toronto, ON'},
'1416360':{'en': 'Toronto, ON'},
'1416361':{'en': 'Toronto, ON'},
'1416362':{'en': 'Toronto, ON'},
'1416363':{'en': 'Toronto, ON'},
'1416368':{'en': 'Toronto, ON'},
'1416369':{'en': 'Toronto, ON'},
'1425264':{'en': 'Renton, WA'},
'1412269':{'en': 'Coraopolis, PA'},
'1425261':{'en': 'Everett, WA'},
'1412264':{'en': 'Coraopolis, PA'},
'1415546':{'en': 'San Francisco, CA'},
'1412261':{'en': 'Pittsburgh, PA'},
'1415543':{'en': 'San Francisco, CA'},
'1412262':{'en': 'Coraopolis, PA'},
'1573778':{'en': 'Poplar Bluff, MO'},
'1573775':{'en': 'Steelville, MO'},
'1573774':{'en': 'Waynesville, MO'},
'1573777':{'en': 'Columbia, MO'},
'1573776':{'en': 'Poplar Bluff, MO'},
'1608822':{'en': 'Fennimore, WI'},
'1520792':{'en': 'Tucson, AZ'},
'1520791':{'en': 'Tucson, AZ'},
'1520790':{'en': 'Tucson, AZ'},
'1520797':{'en': 'Tucson, AZ'},
'1608827':{'en': 'Madison, WI'},
'1520795':{'en': 'Tucson, AZ'},
'1608825':{'en': 'Sun Prairie, WI'},
'1419485':{'en': 'Montpelier, OH'},
'1608828':{'en': 'Madison, WI'},
'1520798':{'en': 'Tucson, AZ'},
'1419483':{'en': 'Bellevue, OH'},
'1585621':{'en': 'Rochester, NY'},
'1508303':{'en': 'Marlborough, MA'},
'1607387':{'en': 'Trumansburg, NY'},
'1585787':{'en': 'Webster, NY'},
'1508309':{'en': 'Framingham, MA'},
'1440834':{'en': 'Burton, OH'},
'1585624':{'en': 'Honeoye Falls, NY'},
'1601731':{'en': 'Columbia, MS'},
'1601732':{'en': 'Morton, MS'},
'1601735':{'en': 'Waynesboro, MS'},
'1440838':{'en': 'Cleveland, OH'},
'1503325':{'en': 'Astoria, OR'},
'1503324':{'en': 'Banks, OR'},
'1519542':{'en': 'Sarnia, ON'},
'1510839':{'en': 'Oakland, CA'},
'1507434':{'en': 'Austin, MN'},
'1507437':{'en': 'Austin, MN'},
'1418285':{'en': 'Donnacona, QC'},
'1418287':{'en': 'Fermont, QC'},
'1418286':{'en': 'Portneuf, QC'},
'1510832':{'en': 'Oakland, CA'},
'1510835':{'en': 'Oakland, CA'},
'1510834':{'en': 'Oakland, CA'},
'1510836':{'en': 'Oakland, CA'},
'1559688':{'en': 'Tulare, CA'},
'1559867':{'en': 'Riverdale, CA'},
'1559685':{'en': 'Tulare, CA'},
'1559684':{'en': 'Tulare, CA'},
'1559687':{'en': 'Tulare, CA'},
'1559686':{'en': 'Tulare, CA'},
'1559683':{'en': 'Oakhurst, CA'},
'1410730':{'en': 'Columbia, MD'},
'1574206':{'en': 'Elkhart, IN'},
'1410732':{'en': 'Baltimore, MD'},
'1512341':{'en': 'Round Rock, TX'},
'1512340':{'en': 'Austin, TX'},
'1418759':{'en': 'Maria, QC'},
'1512342':{'en': 'Austin, TX'},
'1512345':{'en': 'Austin, TX'},
'1512344':{'en': 'Austin, TX'},
'1512347':{'en': 'Austin, TX'},
'1512346':{'en': 'Austin, TX'},
'1512349':{'en': 'Austin, TX'},
'1418756':{'en': 'Causapscal, QC'},
'1610694':{'en': 'Bethlehem, PA'},
'1610696':{'en': 'West Chester, PA'},
'1423746':{'en': 'Athens, TN'},
'1610691':{'en': 'Bethlehem, PA'},
'1610692':{'en': 'West Chester, PA'},
'1610693':{'en': 'Robesonia, PA'},
'1480726':{'en': 'Chandler, AZ'},
'1518853':{'en': 'Fonda, NY'},
'1518854':{'en': 'Salem, NY'},
'1613258':{'en': 'Kemptville, ON'},
'1506743':{'en': 'Bouctouche, NB'},
'1613254':{'en': 'Kanata, ON'},
'1613257':{'en': 'Carleton Place, ON'},
'1613256':{'en': 'Almonte, ON'},
'1613523':{'en': 'Ottawa, ON'},
'1434817':{'en': 'Charlottesville, VA'},
'1613253':{'en': 'Carleton Place, ON'},
'1513761':{'en': 'Cincinnati, OH'},
'1513762':{'en': 'Cincinnati, OH'},
'1608661':{'en': 'Madison, WI'},
'1513769':{'en': 'Cincinnati, OH'},
'1419289':{'en': 'Ashland, OH'},
'1501978':{'en': 'Little Rock, AR'},
'1501977':{'en': 'Morrilton, AR'},
'1501975':{'en': 'Little Rock, AR'},
'1517448':{'en': 'Hudson, MI'},
'1614291':{'en': 'Columbus, OH'},
'1541770':{'en': 'Medford, OR'},
'1541772':{'en': 'Medford, OR'},
'1541773':{'en': 'Medford, OR'},
'1541774':{'en': 'Medford, OR'},
'1541776':{'en': 'Medford, OR'},
'1541779':{'en': 'Medford, OR'},
'1612348':{'en': 'Minneapolis, MN'},
'1612349':{'en': 'Minneapolis, MN'},
'1419281':{'en': 'Ashland, OH'},
'1606754':{'en': 'Elkhorn City, KY'},
'1540829':{'en': 'Culpeper, VA'},
'1540828':{'en': 'Bridgewater, VA'},
'1513584':{'en': 'Cincinnati, OH'},
'1513585':{'en': 'Cincinnati, OH'},
'1540825':{'en': 'Culpeper, VA'},
'1612343':{'en': 'Minneapolis, MN'},
'1540822':{'en': 'Lovettsville, VA'},
'1530633':{'en': 'Wheatland, CA'},
'1419287':{'en': 'Pemberville, OH'},
'1502447':{'en': 'Louisville, KY'},
'1502449':{'en': 'Louisville, KY'},
'1502448':{'en': 'Louisville, KY'},
'1520690':{'en': 'Tucson, AZ'},
'1570459':{'en': 'Hazleton, PA'},
'1570458':{'en': 'Millville, PA'},
'1570327':{'en': 'Williamsport, PA'},
'1570326':{'en': 'Williamsport, PA'},
'1570325':{'en': 'Jim Thorpe, PA'},
'1563578':{'en': 'Sumner, IA'},
'1570323':{'en': 'Williamsport, PA'},
'1570322':{'en': 'Williamsport, PA'},
'1570321':{'en': 'Williamsport, PA'},
'1570320':{'en': 'Williamsport, PA'},
'1510583':{'en': 'Hayward, CA'},
'1510238':{'en': 'Oakland, CA'},
'1510237':{'en': 'Richmond, CA'},
'1510236':{'en': 'Richmond, CA'},
'1510235':{'en': 'Richmond, CA'},
'1510234':{'en': 'Richmond, CA'},
'1510233':{'en': 'Richmond, CA'},
'1510232':{'en': 'Richmond, CA'},
'1510231':{'en': 'Richmond, CA'},
'1434369':{'en': 'Altavista, VA'},
'1517339':{'en': 'Haslett, MI'},
'1425454':{'en': 'Bellevue, WA'},
'1425455':{'en': 'Bellevue, WA'},
'1425450':{'en': 'Bellevue, WA'},
'1425451':{'en': 'Bellevue, WA'},
'1425452':{'en': 'Bellevue, WA'},
'1425453':{'en': 'Bellevue, WA'},
'1616335':{'en': 'Holland, MI'},
'1616846':{'en': 'Grand Haven, MI'},
'1616336':{'en': 'Grand Rapids, MI'},
'1514938':{'en': 'Montreal, QC'},
'1514939':{'en': 'Montreal, QC'},
'1514934':{'en': 'Montreal, QC'},
'1514935':{'en': 'Montreal, QC'},
'1514937':{'en': 'Montreal, QC'},
'1478405':{'en': 'Macon, GA'},
'1514931':{'en': 'Montreal, QC'},
'1514932':{'en': 'Montreal, QC'},
'1514933':{'en': 'Montreal, QC'},
'1509826':{'en': 'Omak, WA'},
'1479936':{'en': 'Rogers, AR'},
'1615386':{'en': 'Nashville, TN'},
'1607337':{'en': 'Norwich, NY'},
'1607336':{'en': 'Norwich, NY'},
'1510452':{'en': 'Oakland, CA'},
'1615435':{'en': 'Franklin, TN'},
'1602674':{'en': 'Phoenix, AZ'},
'1615365':{'en': 'Nashville, TN'},
'1602678':{'en': 'Phoenix, AZ'},
'1614836':{'en': 'Groveport, OH'},
'1613489':{'en': 'North Gower, ON'},
'1435586':{'en': 'Cedar City, UT'},
'1415482':{'en': 'San Rafael, CA'},
'1604542':{'en': 'Surrey, BC'},
'1415485':{'en': 'San Rafael, CA'},
'1415487':{'en': 'San Francisco, CA'},
'1432756':{'en': 'Stanton, TX'},
'1614389':{'en': 'Dublin, OH'},
'1432758':{'en': 'Seminole, TX'},
'1416283':{'en': 'Scarborough, ON'},
'1416282':{'en': 'Scarborough, ON'},
'1416281':{'en': 'Scarborough, ON'},
'1416287':{'en': 'Scarborough, ON'},
'1416286':{'en': 'Scarborough, ON'},
'1416284':{'en': 'Scarborough, ON'},
'1416289':{'en': 'Scarborough, ON'},
'1416288':{'en': 'Scarborough, ON'},
'1603529':{'en': 'Weare, NH'},
'1604826':{'en': 'Mission, BC'},
'1604824':{'en': 'Chilliwack, BC'},
'1415731':{'en': 'San Francisco, CA'},
'1604822':{'en': 'Vancouver, BC'},
'1604823':{'en': 'Chilliwack, BC'},
'1604820':{'en': 'Mission, BC'},
'1604821':{'en': 'Richmond, BC'},
'1585319':{'en': 'Rochester, NY'},
'1509455':{'en': 'Spokane, WA'},
'1509326':{'en': 'Spokane, WA'},
'1509325':{'en': 'Spokane, WA'},
'1514759':{'en': 'Montreal, QC'},
'1509456':{'en': 'Spokane, WA'},
'1573896':{'en': 'Holts Summit, MO'},
'1573897':{'en': 'Linn, MO'},
'1514750':{'en': 'Montreal, QC'},
'1605669':{'en': 'Murdo, SD'},
'1605668':{'en': 'Yankton, SD'},
'1501745':{'en': 'Clinton, AR'},
'1562728':{'en': 'Long Beach, CA'},
'1602272':{'en': 'Phoenix, AZ'},
'1512756':{'en': 'Burnet, TX'},
'1512754':{'en': 'San Marcos, TX'},
'1512759':{'en': 'Hutto, TX'},
'1610444':{'en': 'Kennett Square, PA'},
'1541563':{'en': 'Waldport, OR'},
'1610446':{'en': 'Havertown, PA'},
'1414286':{'en': 'Milwaukee, WI'},
'1414281':{'en': 'Milwaukee, WI'},
'1602277':{'en': 'Phoenix, AZ'},
'1414282':{'en': 'Milwaukee, WI'},
'1414289':{'en': 'Milwaukee, WI'},
'1414288':{'en': 'Milwaukee, WI'},
'1419347':{'en': 'Shelby, OH'},
'1615547':{'en': 'Lebanon, TN'},
'1419342':{'en': 'Shelby, OH'},
'1508325':{'en': 'Nantucket, MA'},
'1520300':{'en': 'Tucson, AZ'},
'1507359':{'en': 'New Ulm, MN'},
'1559478':{'en': 'Fresno, CA'},
'1530':{'en': 'California'},
'1507354':{'en': 'New Ulm, MN'},
'1614252':{'en': 'Columbus, OH'},
'1507356':{'en': 'Pine Island, MN'},
'1507357':{'en': 'Le Center, MN'},
'1414461':{'en': 'Milwaukee, WI'},
'1414463':{'en': 'Milwaukee, WI'},
'1414462':{'en': 'Milwaukee, WI'},
'1573546':{'en': 'Ironton, MO'},
'1414464':{'en': 'Milwaukee, WI'},
'1414466':{'en': 'Milwaukee, WI'},
'1573238':{'en': 'Marble Hill, MO'},
'1616':{'en': 'Michigan'},
'1539':{'en': 'Oklahoma'},
'1540932':{'en': 'Fishersville, VA'},
'1561451':{'en': 'Boca Raton, FL'},
'1561450':{'en': 'Delray Beach, FL'},
'1561455':{'en': 'Delray Beach, FL'},
'1419734':{'en': 'Port Clinton, OH'},
'1419732':{'en': 'Port Clinton, OH'},
'1605886':{'en': 'Watertown, SD'},
'1601502':{'en': 'Jackson, MS'},
'1605882':{'en': 'Watertown, SD'},
'1419738':{'en': 'Wapakoneta, OH'},
'1419739':{'en': 'Wapakoneta, OH'},
'1520836':{'en': 'Casa Grande, AZ'},
'1610225':{'en': 'Wayne, PA'},
'1610992':{'en': 'King of Prussia, PA'},
'1614766':{'en': 'Dublin, OH'},
'1614760':{'en': 'Dublin, OH'},
'1614761':{'en': 'Dublin, OH'},
'1614947':{'en': 'Columbus, OH'},
'1610998':{'en': 'Oxford, PA'},
'1517589':{'en': 'Leslie, MI'},
'1613756':{'en': 'Barry\'s Bay, ON'},
'1613757':{'en': 'Killaloe, ON'},
'1617414':{'en': 'Boston, MA'},
'1514495':{'en': 'Montreal, QC'},
'1505262':{'en': 'Albuquerque, NM'},
'1505263':{'en': 'Albuquerque, NM'},
'1505260':{'en': 'Albuquerque, NM'},
'1505261':{'en': 'Albuquerque, NM'},
'1505266':{'en': 'Albuquerque, NM'},
'1505265':{'en': 'Albuquerque, NM'},
'1541341':{'en': 'Eugene, OR'},
'1505268':{'en': 'Albuquerque, NM'},
'1505269':{'en': 'Albuquerque, NM'},
'1541345':{'en': 'Eugene, OR'},
'1541344':{'en': 'Eugene, OR'},
'1541347':{'en': 'Bandon, OR'},
'1541346':{'en': 'Eugene, OR'},
'1615650':{'en': 'Nashville, TN'},
'1503636':{'en': 'Lake Oswego, OR'},
'1503635':{'en': 'Lake Oswego, OR'},
'1410502':{'en': 'Baltimore, MD'},
'1503631':{'en': 'Oregon City, OR'},
'1503630':{'en': 'Estacada, OR'},
'1418':{'en': 'Quebec'},
'1419':{'en': 'Ohio'},
'1410':{'en': 'Maryland'},
'1412':{'en': 'Pennsylvania'},
'1413':{'en': 'Massachusetts'},
'1414':{'en': 'Wisconsin'},
'1415':{'en': 'California'},
'1416':{'en': 'Ontario'},
'1417':{'en': 'Missouri'},
'1541526':{'en': 'Redmond, OR'},
'1541520':{'en': 'Eugene, OR'},
'1541523':{'en': 'Baker City, OR'},
'1575838':{'en': 'Socorro, NM'},
'1503988':{'en': 'Portland, OR'},
'1435772':{'en': 'Springdale, UT'},
'1503981':{'en': 'Woodburn, OR'},
'1503982':{'en': 'Woodburn, OR'},
'1503985':{'en': 'Gaston, OR'},
'1412241':{'en': 'Pittsburgh, PA'},
'1580765':{'en': 'Ponca City, OK'},
'1509932':{'en': 'Mattawa, WA'},
'1575461':{'en': 'Tucumcari, NM'},
'1479725':{'en': 'Springdale, AR'},
'1609883':{'en': 'Ewing Township, NJ'},
'1415567':{'en': 'San Francisco, CA'},
'1415566':{'en': 'San Francisco, CA'},
'1509533':{'en': 'Spokane, WA'},
'1412244':{'en': 'Pittsburgh, PA'},
'1513247':{'en': 'Cincinnati, OH'},
'1513934':{'en': 'Lebanon, OH'},
'1513245':{'en': 'Cincinnati, OH'},
'1513244':{'en': 'Cincinnati, OH'},
'1513931':{'en': 'Cincinnati, OH'},
'1513242':{'en': 'Cincinnati, OH'},
'1513241':{'en': 'Cincinnati, OH'},
'1513932':{'en': 'Lebanon, OH'},
'1513939':{'en': 'Fairfield, OH'},
'1513248':{'en': 'Milford, OH'},
'1586598':{'en': 'Chesterfield, MI'},
'1502859':{'en': 'Lawrenceburg, KY'},
'1502589':{'en': 'Louisville, KY'},
'1502587':{'en': 'Louisville, KY'},
'1502584':{'en': 'Louisville, KY'},
'1502585':{'en': 'Louisville, KY'},
'1502582':{'en': 'Louisville, KY'},
'1502583':{'en': 'Louisville, KY'},
'1502852':{'en': 'Louisville, KY'},
'1502581':{'en': 'Louisville, KY'},
'1432697':{'en': 'Midland, TX'},
'1432694':{'en': 'Midland, TX'},
'1478892':{'en': 'Hawkinsville, GA'},
'1432699':{'en': 'Midland, TX'},
'1440323':{'en': 'Elyria, OH'},
'1440322':{'en': 'Elyria, OH'},
'1440327':{'en': 'North Ridgeville, OH'},
'1440324':{'en': 'Elyria, OH'},
'1616451':{'en': 'Grand Rapids, MI'},
'1440329':{'en': 'Elyria, OH'},
'1616453':{'en': 'Grand Rapids, MI'},
'1616454':{'en': 'Grand Rapids, MI'},
'1616455':{'en': 'Grand Rapids, MI'},
'1616456':{'en': 'Grand Rapids, MI'},
'1616457':{'en': 'Jenison, MI'},
'1509363':{'en': 'Spokane, WA'},
'1515989':{'en': 'Carlisle, IA'},
'1450379':{'en': 'Saint-Paul-d\'Abbotsford, QC'},
'1450378':{'en': 'Granby, QC'},
'1450375':{'en': 'Granby, QC'},
'1450377':{'en': 'Salaberry-de-Valleyfield, QC'},
'1515981':{'en': 'Norwalk, IA'},
'1450371':{'en': 'Salaberry-de-Valleyfield, QC'},
'1515987':{'en': 'Waukee, IA'},
'1450373':{'en': 'Salaberry-de-Valleyfield, QC'},
'1450372':{'en': 'Granby, QC'},
'1585254':{'en': 'Rochester, NY'},
'1408927':{'en': 'San Jose, CA'},
'1408926':{'en': 'San Jose, CA'},
'1408920':{'en': 'San Jose, CA'},
'1408923':{'en': 'San Jose, CA'},
'1408929':{'en': 'San Jose, CA'},
'1608592':{'en': 'Lodi, WI'},
'1615228':{'en': 'Nashville, TN'},
'1416348':{'en': 'Toronto, ON'},
'1615222':{'en': 'Nashville, TN'},
'1416615':{'en': 'Scarborough, ON'},
'1615220':{'en': 'Smyrna, TN'},
'1615221':{'en': 'Brentwood, TN'},
'1615226':{'en': 'Nashville, TN'},
'1615227':{'en': 'Nashville, TN'},
'1416340':{'en': 'Toronto, ON'},
'1615225':{'en': 'Murfreesboro, TN'},
'1519894':{'en': 'Kitchener, ON'},
'1519895':{'en': 'Kitchener, ON'},
'1519896':{'en': 'Kitchener, ON'},
'1541885':{'en': 'Klamath Falls, OR'},
'1519893':{'en': 'Kitchener, ON'},
'1541882':{'en': 'Klamath Falls, OR'},
'1604455':{'en': 'Langley, BC'},
'1604454':{'en': 'Burnaby, BC'},
'1604451':{'en': 'Burnaby, BC'},
'1541883':{'en': 'Klamath Falls, OR'},
'1605279':{'en': 'Wall, SD'},
'1605274':{'en': 'Sioux Falls, SD'},
'1605275':{'en': 'Sioux Falls, SD'},
'1609538':{'en': 'Ewing Township, NJ'},
'1605271':{'en': 'Sioux Falls, SD'},
'1509586':{'en': 'Kennewick, WA'},
'1509585':{'en': 'Kennewick, WA'},
'1509582':{'en': 'Kennewick, WA'},
'1608378':{'en': 'Warrens, WI'},
'1603823':{'en': 'Franconia, NH'},
'1603821':{'en': 'Nashua, NH'},
'1608375':{'en': 'Boscobel, WI'},
'1608372':{'en': 'Tomah, WI'},
'1585321':{'en': 'Rochester, NY'},
'1509588':{'en': 'Benton City, WA'},
'1507637':{'en': 'Redwood Falls, MN'},
'1507634':{'en': 'Kasson, MN'},
'1562531':{'en': 'Paramount, CA'},
'1505857':{'en': 'Albuquerque, NM'},
'1505856':{'en': 'Albuquerque, NM'},
'1541888':{'en': 'Coos Bay, OR'},
'1508366':{'en': 'Westborough, MA'},
'1508368':{'en': 'Worcester, MA'},
'1609530':{'en': 'Ewing Township, NJ'},
'1505858':{'en': 'Albuquerque, NM'},
'1606256':{'en': 'Mount Vernon, KY'},
'1440816':{'en': 'Cleveland, OH'},
'1615952':{'en': 'Kingston Springs, TN'},
'1615953':{'en': 'Nashville, TN'},
'1614464':{'en': 'Columbus, OH'},
'1412821':{'en': 'Pittsburgh, PA'},
'1409745':{'en': 'Orange, TX'},
'1616662':{'en': 'Hudsonville, MI'},
'1410752':{'en': 'Baltimore, MD'},
'1410751':{'en': 'Westminster, MD'},
'1410974':{'en': 'Annapolis, MD'},
'1410757':{'en': 'Annapolis, MD'},
'1410756':{'en': 'Taneytown, MD'},
'1410754':{'en': 'Federalsburg, MD'},
'1410758':{'en': 'Centreville, MD'},
'1418775':{'en': 'Mont-Joli, QC'},
'1418774':{'en': 'Beauceville, QC'},
'1508984':{'en': 'New Bedford, MA'},
'1508985':{'en': 'New Bedford, MA'},
'1512329':{'en': 'Austin, TX'},
'1512328':{'en': 'Austin, TX'},
'1609348':{'en': 'Atlantic City, NJ'},
'1512323':{'en': 'Austin, TX'},
'1512322':{'en': 'Austin, TX'},
'1512321':{'en': 'Bastrop, TX'},
'1512320':{'en': 'Austin, TX'},
'1512327':{'en': 'Austin, TX'},
'1512326':{'en': 'Austin, TX'},
'1512324':{'en': 'Austin, TX'},
'1601758':{'en': 'Sumrall, MS'},
'1484884':{'en': 'Bethlehem, PA'},
'1409740':{'en': 'Galveston, TX'},
'1518873':{'en': 'Elizabethtown, NY'},
'1570287':{'en': 'Kingston, PA'},
'1418614':{'en': 'Quebec City, QC'},
'1602996':{'en': 'Phoenix, AZ'},
'1435713':{'en': 'Logan, UT'},
'1614876':{'en': 'Hilliard, OH'},
'1540465':{'en': 'Strasburg, VA'},
'1540464':{'en': 'Lexington, VA'},
'1540463':{'en': 'Lexington, VA'},
'1614870':{'en': 'Columbus, OH'},
'1613507':{'en': 'Kingston, ON'},
'1540468':{'en': 'Monterey, VA'},
'1513742':{'en': 'Cincinnati, OH'},
'1513741':{'en': 'Cincinnati, OH'},
'1513745':{'en': 'Cincinnati, OH'},
'1580688':{'en': 'Hollis, OK'},
'1501916':{'en': 'Little Rock, AR'},
'1425883':{'en': 'Redmond, WA'},
'1425882':{'en': 'Redmond, WA'},
'1425881':{'en': 'Redmond, WA'},
'1614878':{'en': 'Columbus, OH'},
'1425889':{'en': 'Kirkland, WA'},
'1425888':{'en': 'North Bend, WA'},
'1408738':{'en': 'Sunnyvale, CA'},
'1419690':{'en': 'Oregon, OH'},
'1541758':{'en': 'Corvallis, OR'},
'1419692':{'en': 'Delphos, OH'},
'1419695':{'en': 'Delphos, OH'},
'1419697':{'en': 'Oregon, OH'},
'1419696':{'en': 'Oregon, OH'},
'1408730':{'en': 'Sunnyvale, CA'},
'1419698':{'en': 'Oregon, OH'},
'1408732':{'en': 'Sunnyvale, CA'},
'1408733':{'en': 'Sunnyvale, CA'},
'1408734':{'en': 'Sunnyvale, CA'},
'1408735':{'en': 'Sunnyvale, CA'},
'1408736':{'en': 'Sunnyvale, CA'},
'1408737':{'en': 'Sunnyvale, CA'},
'1434696':{'en': 'Victoria, VA'},
'1603585':{'en': 'Fitzwilliam, NH'},
'1450562':{'en': 'Lachute, QC'},
'1609347':{'en': 'Atlantic City, NJ'},
'1562218':{'en': 'Long Beach, CA'},
'1434432':{'en': 'Chatham, VA'},
'1509972':{'en': 'Yakima, WA'},
'1434348':{'en': 'Emporia, VA'},
'1602470':{'en': 'Phoenix, AZ'},
'1503844':{'en': 'Hillsboro, OR'},
'1503845':{'en': 'Mount Angel, OR'},
'1503846':{'en': 'Hillsboro, OR'},
'1503841':{'en': 'Portland, OR'},
'1503842':{'en': 'Tillamook, OR'},
'1503843':{'en': 'Sheridan, OR'},
'1616685':{'en': 'Grand Rapids, MI'},
'1616868':{'en': 'Alto, MI'},
'1616681':{'en': 'Dorr, MI'},
'1616682':{'en': 'Ada, MI'},
'1518268':{'en': 'Troy, NY'},
'1450491':{'en': 'Saint-Eustache, QC'},
'1450492':{'en': 'Terrebonne, QC'},
'1518263':{'en': 'Hunter, NY'},
'1518266':{'en': 'Troy, NY'},
'1509773':{'en': 'Goldendale, WA'},
'1519793':{'en': 'Lion\'s Head, ON'},
'1519797':{'en': 'Southampton, ON'},
'1519794':{'en': 'Chatsworth, ON'},
'1510818':{'en': 'Fremont, CA'},
'1609343':{'en': 'Atlantic City, NJ'},
'1603366':{'en': 'Laconia, NH'},
'1585482':{'en': 'Rochester, NY'},
'1516796':{'en': 'Levittown, NY'},
'1510248':{'en': 'Fremont, CA'},
'1574294':{'en': 'Elkhart, IN'},
'1478289':{'en': 'Swainsboro, GA'},
'1613567':{'en': 'Ottawa, ON'},
'1612813':{'en': 'Minneapolis, MN'},
'1516797':{'en': 'Massapequa, NY'},
'1540289':{'en': 'McGaheysville, VA'},
'1510534':{'en': 'Oakland, CA'},
'1540288':{'en': 'Stafford, VA'},
'1607319':{'en': 'Ithaca, NY'},
'1604664':{'en': 'Burnaby, BC'},
'1604665':{'en': 'Vancouver, BC'},
'1604666':{'en': 'Vancouver, BC'},
'1423629':{'en': 'Chattanooga, TN'},
'1512515':{'en': 'Liberty Hill, TX'},
'1604662':{'en': 'Vancouver, BC'},
'1604847':{'en': 'Chilliwack, BC'},
'1423625':{'en': 'Newport, TN'},
'1423624':{'en': 'Chattanooga, TN'},
'1585663':{'en': 'Rochester, NY'},
'1423623':{'en': 'Newport, TN'},
'1423622':{'en': 'Chattanooga, TN'},
'1604689':{'en': 'Vancouver, BC'},
'1510532':{'en': 'Oakland, CA'},
'1603636':{'en': 'Groveton, NH'},
'1510245':{'en': 'Hercules, CA'},
'1605649':{'en': 'Selby, SD'},
'1605644':{'en': 'Spearfish, SD'},
'1605647':{'en': 'Lennox, SD'},
'1586977':{'en': 'Sterling Heights, MI'},
'1614851':{'en': 'Columbus, OH'},
'1605642':{'en': 'Spearfish, SD'},
'1501729':{'en': 'Judsonia, AR'},
'1504534':{'en': 'Venice, LA'},
'1501724':{'en': 'Bald Knob, AR'},
'1508647':{'en': 'Natick, MA'},
'1508646':{'en': 'Fall River, MA'},
'1502261':{'en': 'Louisville, KY'},
'1508644':{'en': 'Assonet, MA'},
'1502267':{'en': 'Louisville, KY'},
'1502266':{'en': 'Louisville, KY'},
'1423485':{'en': 'Chattanooga, TN'},
'1423487':{'en': 'Cosby, TN'},
'1423954':{'en': 'Chattanooga, TN'},
'1540980':{'en': 'Pulaski, VA'},
'1540981':{'en': 'Roanoke, VA'},
'1414266':{'en': 'Wauwatosa, WI'},
'1414265':{'en': 'Milwaukee, WI'},
'1414264':{'en': 'Milwaukee, WI'},
'1414263':{'en': 'Milwaukee, WI'},
'1540982':{'en': 'Roanoke, VA'},
'1520326':{'en': 'Tucson, AZ'},
'1520327':{'en': 'Tucson, AZ'},
'1515795':{'en': 'Madrid, IA'},
'1520325':{'en': 'Tucson, AZ'},
'1520322':{'en': 'Tucson, AZ'},
'1520323':{'en': 'Tucson, AZ'},
'1520320':{'en': 'Tucson, AZ'},
'1520321':{'en': 'Tucson, AZ'},
'1540254':{'en': 'Buchanan, VA'},
'1615567':{'en': 'Franklin, TN'},
'1615563':{'en': 'Woodbury, TN'},
'1608788':{'en': 'La Crosse, WI'},
'1610277':{'en': 'Norristown, PA'},
'1559498':{'en': 'Fresno, CA'},
'1559499':{'en': 'Fresno, CA'},
'1503571':{'en': 'Clackamas, OR'},
'1559495':{'en': 'Fresno, CA'},
'1559497':{'en': 'Fresno, CA'},
'1559490':{'en': 'Fresno, CA'},
'1559492':{'en': 'Fresno, CA'},
'1540786':{'en': 'Fredericksburg, VA'},
'1540785':{'en': 'Fredericksburg, VA'},
'1435835':{'en': 'Manti, UT'},
'1616836':{'en': 'Holland, MI'},
'1573214':{'en': 'Columbia, MO'},
'1540788':{'en': 'Catlett, VA'},
'1616837':{'en': 'Coopersville, MI'},
'1610429':{'en': 'West Chester, PA'},
'1506395':{'en': 'Tracadie-Sheila, NB'},
'1506393':{'en': 'Tracadie-Sheila, NB'},
'1506392':{'en': 'Florenceville, NB'},
'1561477':{'en': 'Boca Raton, FL'},
'1561471':{'en': 'West Palm Beach, FL'},
'1561470':{'en': 'Boca Raton, FL'},
'1419756':{'en': 'Mansfield, OH'},
'1480396':{'en': 'Mesa, AZ'},
'1480391':{'en': 'Scottsdale, AZ'},
'1507372':{'en': 'Worthington, MN'},
'1507373':{'en': 'Albert Lea, MN'},
'1507376':{'en': 'Worthington, MN'},
'1507377':{'en': 'Albert Lea, MN'},
'1507374':{'en': 'Dodge Center, MN'},
'1507375':{'en': 'Saint James, MN'},
'1614210':{'en': 'Dublin, OH'},
'1541323':{'en': 'Bend, OR'},
'1541322':{'en': 'Bend, OR'},
'1508222':{'en': 'Attleboro, MA'},
'1541327':{'en': 'Jefferson, OR'},
'1613774':{'en': 'Winchester, ON'},
'1613771':{'en': 'Belleville, ON'},
'1505285':{'en': 'Grants, NM'},
'1505287':{'en': 'Grants, NM'},
'1505280':{'en': 'Albuquerque, NM'},
'1503618':{'en': 'Gresham, OR'},
'1434':{'en': 'Virginia'},
'1435':{'en': 'Utah'},
'1432':{'en': 'Texas'},
'1430':{'en': 'Texas'},
'1431':{'en': 'Manitoba'},
'1503612':{'en': 'Tualatin, OR'},
'1503615':{'en': 'Hillsboro, OR'},
'1438':{'en': 'Quebec'},
'1615360':{'en': 'Nashville, TN'},
'1570820':{'en': 'Wilkes-Barre, PA'},
'1570821':{'en': 'Wilkes-Barre, PA'},
'1570822':{'en': 'Wilkes-Barre, PA'},
'1570823':{'en': 'Wilkes-Barre, PA'},
'1570824':{'en': 'Wilkes-Barre, PA'},
'1570825':{'en': 'Wilkes-Barre, PA'},
'1570826':{'en': 'Wilkes-Barre, PA'},
'1570828':{'en': 'Dingmans Ferry, PA'},
'1570829':{'en': 'Wilkes-Barre, PA'},
'1530378':{'en': 'Anderson, CA'},
'1409386':{'en': 'Silsbee, TX'},
'1409384':{'en': 'Jasper, TX'},
'1409385':{'en': 'Silsbee, TX'},
'1513481':{'en': 'Cincinnati, OH'},
'1409383':{'en': 'Jasper, TX'},
'1513489':{'en': 'Cincinnati, OH'},
'1504883':{'en': 'Metairie, LA'},
'1504885':{'en': 'Metairie, LA'},
'1504887':{'en': 'Metairie, LA'},
'1504889':{'en': 'Metairie, LA'},
'1504888':{'en': 'Metairie, LA'},
'1435755':{'en': 'Logan, UT'},
'1435752':{'en': 'Logan, UT'},
'1435753':{'en': 'Logan, UT'},
'1435750':{'en': 'Logan, UT'},
'1479709':{'en': 'Fort Smith, AR'},
'1479705':{'en': 'Clarksville, AR'},
'1479254':{'en': 'Bentonville, AR'},
'1479253':{'en': 'Eureka Springs, AR'},
'1479251':{'en': 'Fayetteville, AR'},
'1410396':{'en': 'Baltimore, MD'},
'1602864':{'en': 'Phoenix, AZ'},
'1602865':{'en': 'Glendale, AZ'},
'1602866':{'en': 'Phoenix, AZ'},
'1602867':{'en': 'Phoenix, AZ'},
'1602861':{'en': 'Phoenix, AZ'},
'1602863':{'en': 'Phoenix, AZ'},
'1502875':{'en': 'Frankfort, KY'},
'1440244':{'en': 'Lorain, OH'},
'1440245':{'en': 'Lorain, OH'},
'1440247':{'en': 'Chagrin Falls, OH'},
'1510683':{'en': 'Fremont, CA'},
'1616475':{'en': 'Grand Rapids, MI'},
'1413863':{'en': 'Turners Falls, MA'},
'1450829':{'en': 'Ormstown, QC'},
'1509349':{'en': 'Warden, WA'},
'1604207':{'en': 'Richmond, BC'},
'1509346':{'en': 'Royal City, WA'},
'1509340':{'en': 'Spokane, WA'},
'1604205':{'en': 'Burnaby, BC'},
'1416636':{'en': 'North York, ON'},
'1416635':{'en': 'North York, ON'},
'1416633':{'en': 'North York, ON'},
'1416630':{'en': 'North York, ON'},
'1416631':{'en': 'North York, ON'},
'1585247':{'en': 'Rochester, NY'},
'1416638':{'en': 'North York, ON'},
'1541549':{'en': 'Sisters, OR'},
'1607786':{'en': 'Endicott, NY'},
'1416321':{'en': 'Scarborough, ON'},
'1416322':{'en': 'Toronto, ON'},
'1416323':{'en': 'Toronto, ON'},
'1416324':{'en': 'Toronto, ON'},
'1585872':{'en': 'Webster, NY'},
'1425228':{'en': 'Renton, WA'},
'1519304':{'en': 'Brantford, ON'},
'1425222':{'en': 'Fall City, WA'},
'1604472':{'en': 'Port Coquitlam, BC'},
'1425227':{'en': 'Renton, WA'},
'1425226':{'en': 'Renton, WA'},
'1604477':{'en': 'Maple Ridge, BC'},
'1604476':{'en': 'Maple Ridge, BC'},
'1563933':{'en': 'Strawberry Point, IA'},
'1563421':{'en': 'Davenport, IA'},
'1563422':{'en': 'West Union, IA'},
'1563391':{'en': 'Davenport, IA'},
'1409892':{'en': 'Beaumont, TX'},
'1409896':{'en': 'Beaumont, TX'},
'1608310':{'en': 'Madison, WI'},
'1409898':{'en': 'Beaumont, TX'},
'1409899':{'en': 'Beaumont, TX'},
'1608314':{'en': 'Janesville, WI'},
'1507964':{'en': 'Arlington, MN'},
'1508349':{'en': 'Wellfleet, MA'},
'1508435':{'en': 'Hopkinton, MA'},
'1508436':{'en': 'Brockton, MA'},
'1508430':{'en': 'Harwich, MA'},
'1508347':{'en': 'Sturbridge, MA'},
'1440878':{'en': 'Strongsville, OH'},
'1440877':{'en': 'Cleveland, OH'},
'1415677':{'en': 'San Francisco, CA'},
'1585295':{'en': 'Rochester, NY'},
'1415674':{'en': 'San Francisco, CA'},
'1415673':{'en': 'San Francisco, CA'},
'1480898':{'en': 'Mesa, AZ'},
'1415671':{'en': 'San Francisco, CA'},
'1412802':{'en': 'Pittsburgh, PA'},
'1480894':{'en': 'Tempe, AZ'},
'1480890':{'en': 'Mesa, AZ'},
'1608417':{'en': 'Madison, WI'},
'1520694':{'en': 'Tucson, AZ'},
'1605256':{'en': 'Madison, SD'},
'1414671':{'en': 'Milwaukee, WI'},
'1414672':{'en': 'Milwaukee, WI'},
'1610326':{'en': 'Pottstown, PA'},
'1605853':{'en': 'Miller, SD'},
'1410955':{'en': 'Baltimore, MD'},
'1410778':{'en': 'Chestertown, MD'},
'1410957':{'en': 'Pocomoke City, MD'},
'1410956':{'en': 'Edgewater, MD'},
'1410770':{'en': 'Easton, MD'},
'1410772':{'en': 'Columbia, MD'},
'1512306':{'en': 'Austin, TX'},
'1512301':{'en': 'Austin, TX'},
'1512303':{'en': 'Bastrop, TX'},
'1512302':{'en': 'Austin, TX'},
'1610327':{'en': 'Pottstown, PA'},
'1512308':{'en': 'Bastrop, TX'},
'1561865':{'en': 'Delray Beach, FL'},
'1613271':{'en': 'Kanata, ON'},
'1605432':{'en': 'Milbank, SD'},
'1601956':{'en': 'Jackson, MS'},
'1570455':{'en': 'Hazleton, PA'},
'1601776':{'en': 'Quitman, MS'},
'1559535':{'en': 'Terra Bella, CA'},
'1518891':{'en': 'Saranac Lake, NY'},
'1613563':{'en': 'Ottawa, ON'},
'1613562':{'en': 'Ottawa, ON'},
'1573663':{'en': 'Ellington, MO'},
'1613565':{'en': 'Ottawa, ON'},
'1609266':{'en': 'Brigantine, NJ'},
'1613569':{'en': 'Ottawa, ON'},
'1540443':{'en': 'Blacksburg, VA'},
'1540442':{'en': 'Harrisonburg, VA'},
'1540444':{'en': 'Salem, VA'},
'1501932':{'en': 'Conway, AR'},
'1616522':{'en': 'Ionia, MI'},
'1575443':{'en': 'Alamogordo, NM'},
'1417206':{'en': 'Joplin, MO'},
'1605925':{'en': 'Freeman, SD'},
'1614875':{'en': 'Grove City, OH'},
'1605923':{'en': 'Box Elder, SD'},
'1561391':{'en': 'Boca Raton, FL'},
'1561392':{'en': 'Boca Raton, FL'},
'1408719':{'en': 'Milpitas, CA'},
'1561394':{'en': 'Boca Raton, FL'},
'1561395':{'en': 'Boca Raton, FL'},
'1561640':{'en': 'West Palm Beach, FL'},
'1613384':{'en': 'Kingston, ON'},
'1613382':{'en': 'Gananoque, ON'},
'1604439':{'en': 'Burnaby, BC'},
'1613389':{'en': 'Kingston, ON'},
'1419947':{'en': 'Mount Gilead, OH'},
'1419946':{'en': 'Mount Gilead, OH'},
'1570366':{'en': 'Orwigsburg, PA'},
'1419943':{'en': 'Leipsic, OH'},
'1501223':{'en': 'Little Rock, AR'},
'1570368':{'en': 'Montoursville, PA'},
'1604560':{'en': 'Surrey, BC'},
'1604435':{'en': 'Burnaby, BC'},
'1610582':{'en': 'Birdsboro, PA'},
'1510273':{'en': 'Oakland, CA'},
'1510272':{'en': 'Oakland, CA'},
'1510271':{'en': 'Oakland, CA'},
'1603378':{'en': 'Plaistow, NH'},
'1518794':{'en': 'New Lebanon, NY'},
'1604430':{'en': 'Burnaby, BC'},
'1425413':{'en': 'Maple Valley, WA'},
'1605335':{'en': 'Sioux Falls, SD'},
'1605337':{'en': 'Platte, SD'},
'1450468':{'en': 'Longueuil, QC'},
'1478445':{'en': 'Milledgeville, GA'},
'1602454':{'en': 'Phoenix, AZ'},
'1602456':{'en': 'Phoenix, AZ'},
'1602323':{'en': 'Phoenix, AZ'},
'1540862':{'en': 'Clifton Forge, VA'},
'1540864':{'en': 'New Castle, VA'},
'1503864':{'en': 'Dayton, OR'},
'1540868':{'en': 'Stephens City, VA'},
'1616805':{'en': 'Grand Rapids, MI'},
'1503861':{'en': 'Warrenton, OR'},
'1505259':{'en': 'Albuquerque, NM'},
'1606432':{'en': 'Pikeville, KY'},
'1570587':{'en': 'Clarks Summit, PA'},
'1518563':{'en': 'Plattsburgh, NY'},
'1570585':{'en': 'Clarks Summit, PA'},
'1570584':{'en': 'Hughesville, PA'},
'1518562':{'en': 'Plattsburgh, NY'},
'1614873':{'en': 'Plain City, OH'},
'1518561':{'en': 'Plattsburgh, NY'},
'1518566':{'en': 'Plattsburgh, NY'},
'1413458':{'en': 'Williamstown, MA'},
'1413323':{'en': 'Belchertown, MA'},
'1413322':{'en': 'Holyoke, MA'},
'1585468':{'en': 'Nunda, NY'},
'1415444':{'en': 'San Rafael, CA'},
'1412325':{'en': 'Pittsburgh, PA'},
'1412494':{'en': 'Pittsburgh, PA'},
'1415447':{'en': 'San Francisco, CA'},
'1415440':{'en': 'San Francisco, CA'},
'1412321':{'en': 'Pittsburgh, PA'},
'1412322':{'en': 'Pittsburgh, PA'},
'1412323':{'en': 'Pittsburgh, PA'},
'1450242':{'en': 'Brome Lake, QC'},
'1505255':{'en': 'Albuquerque, NM'},
'1575537':{'en': 'Bayard, NM'},
'1575538':{'en': 'Silver City, NM'},
'1518243':{'en': 'Schenectady, NY'},
'1509754':{'en': 'Ephrata, WA'},
'1518537':{'en': 'Germantown, NY'},
'1603329':{'en': 'Hampstead, NH'},
'1518532':{'en': 'Schroon Lake, NY'},
'1509751':{'en': 'Clarkston, WA'},
'1603497':{'en': 'Goffstown, NH'},
'1509758':{'en': 'Clarkston, WA'},
'1603323':{'en': 'Tamworth, NH'},
'1604869':{'en': 'Hope, BC'},
'1609239':{'en': 'Burlington Township, NJ'},
'1606436':{'en': 'Hazard, KY'},
'1604646':{'en': 'Vancouver, BC'},
'1512533':{'en': 'Austin, TX'},
'1512821':{'en': 'Austin, TX'},
'1604640':{'en': 'Vancouver, BC'},
'1604641':{'en': 'Vancouver, BC'},
'1514798':{'en': 'Montreal, QC'},
'1614365':{'en': 'Columbus, OH'},
'1530233':{'en': 'Alturas, CA'},
'1530235':{'en': 'Dunsmuir, CA'},
'1614366':{'en': 'Columbus, OH'},
'1609748':{'en': 'Galloway, NJ'},
'1613422':{'en': 'Ottawa, ON'},
'1508660':{'en': 'Walpole, MA'},
'1508669':{'en': 'Dighton, MA'},
'1508668':{'en': 'Walpole, MA'},
'1508886':{'en': 'Rutland, MA'},
'1502241':{'en': 'Crestwood, KY'},
'1508880':{'en': 'Taunton, MA'},
'1432368':{'en': 'Odessa, TX'},
'1601894':{'en': 'Hazlehurst, MS'},
'1432362':{'en': 'Odessa, TX'},
'1432363':{'en': 'Odessa, TX'},
'1506372':{'en': 'Salisbury, NB'},
'1432366':{'en': 'Odessa, TX'},
'1432367':{'en': 'Odessa, TX'},
'1414247':{'en': 'Milwaukee, WI'},
'1416869':{'en': 'Toronto, ON'},
'1416868':{'en': 'Toronto, ON'},
'1520344':{'en': 'Tucson, AZ'},
'1416863':{'en': 'Toronto, ON'},
'1416862':{'en': 'Toronto, ON'},
'1416861':{'en': 'Toronto, ON'},
'1416860':{'en': 'Toronto, ON'},
'1416867':{'en': 'Toronto, ON'},
'1416866':{'en': 'Toronto, ON'},
'1416865':{'en': 'Toronto, ON'},
'1416864':{'en': 'Toronto, ON'},
'1559251':{'en': 'Fresno, CA'},
'1520741':{'en': 'Tucson, AZ'},
'1414421':{'en': 'Greendale, WI'},
'1414423':{'en': 'Greendale, WI'},
'1414422':{'en': 'Muskego, WI'},
'1504568':{'en': 'New Orleans, LA'},
'1573588':{'en': 'Shelbina, MO'},
'1504569':{'en': 'New Orleans, LA'},
'1573276':{'en': 'Malden, MO'},
'1503266':{'en': 'Canby, OR'},
'1410893':{'en': 'Bel Air, MD'},
'1503261':{'en': 'Portland, OR'},
'1503262':{'en': 'Portland, OR'},
'1503263':{'en': 'Canby, OR'},
'1508885':{'en': 'Spencer, MA'},
'1515440':{'en': 'West Des Moines, IA'},
'1603528':{'en': 'Laconia, NH'},
'1423975':{'en': 'Johnson City, TN'},
'1512794':{'en': 'Austin, TX'},
'1512795':{'en': 'Austin, TX'},
'1610409':{'en': 'Collegeville, PA'},
'1562272':{'en': 'Paramount, CA'},
'1610404':{'en': 'Birdsboro, PA'},
'1423979':{'en': 'Johnson City, TN'},
'1610402':{'en': 'Allentown, PA'},
'1530243':{'en': 'Redding, CA'},
'1601544':{'en': 'Hattiesburg, MS'},
'1425787':{'en': 'Lynnwood, WA'},
'1425788':{'en': 'Duvall, WA'},
'1504566':{'en': 'New Orleans, LA'},
'1610559':{'en': 'Easton, PA'},
'1603523':{'en': 'Canaan, NH'},
'1505730':{'en': 'Albuquerque, NM'},
'1570875':{'en': 'Ashland, PA'},
'1419774':{'en': 'Mansfield, OH'},
'1419775':{'en': 'Mansfield, OH'},
'1614236':{'en': 'Columbus, OH'},
'1614237':{'en': 'Columbus, OH'},
'1614234':{'en': 'Columbus, OH'},
'1570874':{'en': 'Frackville, PA'},
'1614231':{'en': 'Columbus, OH'},
'1574583':{'en': 'Monticello, IN'},
'1574586':{'en': 'Walkerton, IN'},
'1614238':{'en': 'Columbus, OH'},
'1614239':{'en': 'Columbus, OH'},
'1541902':{'en': 'Florence, OR'},
'1612341':{'en': 'Minneapolis, MN'},
'1505599':{'en': 'Farmington, NM'},
'1614722':{'en': 'Columbus, OH'},
'1614725':{'en': 'Columbus, OH'},
'1530824':{'en': 'Corning, CA'},
'1610882':{'en': 'Bethlehem, PA'},
'1530822':{'en': 'Yuba City, CA'},
'1530823':{'en': 'Auburn, CA'},
'1541306':{'en': 'Bend, OR'},
'1541301':{'en': 'Medford, OR'},
'1541302':{'en': 'Eugene, OR'},
'1410542':{'en': 'Baltimore, MD'},
'1410543':{'en': 'Salisbury, MD'},
'1410546':{'en': 'Salisbury, MD'},
'1410547':{'en': 'Baltimore, MD'},
'1503675':{'en': 'Lake Oswego, OR'},
'1503674':{'en': 'Gresham, OR'},
'1410548':{'en': 'Salisbury, MD'},
'1503678':{'en': 'Aurora, OR'},
'1508881':{'en': 'Ashland, MA'},
'1562856':{'en': 'Long Beach, CA'},
'1423209':{'en': 'Chattanooga, TN'},
'1574674':{'en': 'Osceola, IN'},
'1570808':{'en': 'Wilkes-Barre, PA'},
'1570779':{'en': 'Plymouth, PA'},
'1410522':{'en': 'Baltimore, MD'},
'1570773':{'en': 'Mahanoy City, PA'},
'1410366':{'en': 'Baltimore, MD'},
'1601888':{'en': 'Woodville, MS'},
'1480517':{'en': 'Tempe, AZ'},
'1513469':{'en': 'Cincinnati, OH'},
'1516496':{'en': 'Syosset, NY'},
'1516944':{'en': 'Port Washington, NY'},
'1435738':{'en': 'Duchesne, UT'},
'1418428':{'en': 'Saint-Ferdinand, QC'},
'1580234':{'en': 'Enid, OK'},
'1580233':{'en': 'Enid, OK'},
'1418423':{'en': 'Thetford Mines, QC'},
'1609844':{'en': 'Lawrenceville, NJ'},
'1435734':{'en': 'Brigham City, UT'},
'1418427':{'en': 'East Broughton, QC'},
'1418426':{'en': 'Tring-Jonction, QC'},
'1517548':{'en': 'Howell, MI'},
'1479271':{'en': 'Bentonville, AR'},
'1517545':{'en': 'Howell, MI'},
'1517546':{'en': 'Howell, MI'},
'1517540':{'en': 'Howell, MI'},
'1517541':{'en': 'Charlotte, MI'},
'1517542':{'en': 'Litchfield, MI'},
'1517543':{'en': 'Charlotte, MI'},
'1540672':{'en': 'Orange, VA'},
'1514899':{'en': 'Montreal, QC'},
'1608776':{'en': 'Darlington, WI'},
'1440266':{'en': 'Mentor, OH'},
'1513202':{'en': 'Harrison, OH'},
'1440268':{'en': 'Strongsville, OH'},
'1440269':{'en': 'Willoughby, OH'},
'1513204':{'en': 'Mason, OH'},
'1419332':{'en': 'Fremont, OH'},
'1502813':{'en': 'Louisville, KY'},
'1612347':{'en': 'Minneapolis, MN'},
'1616494':{'en': 'Holland, MI'},
'1416503':{'en': 'Etobicoke, ON'},
'1423764':{'en': 'Bristol, TN'},
'1608663':{'en': 'Madison, WI'},
'1603798':{'en': 'Chichester, NH'},
'1512476':{'en': 'Austin, TX'},
'1609344':{'en': 'Atlantic City, NJ'},
'1479986':{'en': 'Rogers, AR'},
'1602840':{'en': 'Phoenix, AZ'},
'1469633':{'en': 'Frisco, TX'},
'1416650':{'en': 'North York, ON'},
'1586446':{'en': 'Sterling Heights, MI'},
'1416652':{'en': 'Toronto, ON'},
'1416306':{'en': 'Toronto, ON'},
'1416304':{'en': 'Toronto, ON'},
'1416658':{'en': 'Toronto, ON'},
'1607589':{'en': 'Spencer, NY'},
'1607749':{'en': 'Homer, NY'},
'1603569':{'en': 'Wolfeboro, NH'},
'1519326':{'en': 'Leamington, ON'},
'1425204':{'en': 'Renton, WA'},
'1519322':{'en': 'Leamington, ON'},
'1519323':{'en': 'Mount Forest, ON'},
'1604415':{'en': 'Burnaby, BC'},
'1616796':{'en': 'Holland, MI'},
'1412795':{'en': 'Pittsburgh, PA'},
'1478633':{'en': 'Macon, GA'},
'1616794':{'en': 'Belding, MI'},
'1450266':{'en': 'Cowansville, QC'},
'1608882':{'en': 'Evansville, WI'},
'1450264':{'en': 'Huntingdon, QC'},
'1450263':{'en': 'Cowansville, QC'},
'1515327':{'en': 'West Des Moines, IA'},
'1450261':{'en': 'Saint-Hyacinthe, QC'},
'1609263':{'en': 'Sea Isle City, NJ'},
'1570473':{'en': 'Northumberland, PA'},
'1575624':{'en': 'Roswell, NM'},
'1505899':{'en': 'Albuquerque, NM'},
'1505898':{'en': 'Albuquerque, NM'},
'1612529':{'en': 'Minneapolis, MN'},
'1505891':{'en': 'Rio Rancho, NM'},
'1505890':{'en': 'Albuquerque, NM'},
'1505892':{'en': 'Rio Rancho, NM'},
'1615327':{'en': 'Nashville, TN'},
'1505897':{'en': 'Albuquerque, NM'},
'1505896':{'en': 'Rio Rancho, NM'},
'1503385':{'en': 'Salem, OR'},
'1503384':{'en': 'Portland, OR'},
'1503388':{'en': 'Portland, OR'},
'1512495':{'en': 'Austin, TX'},
'1415655':{'en': 'San Francisco, CA'},
'1423787':{'en': 'Greeneville, TN'},
'1423784':{'en': 'Jellico, TN'},
'1418228':{'en': 'Saint-Georges, QC'},
'1418227':{'en': 'Saint-Georges, QC'},
'1418226':{'en': 'Saint-Georges, QC'},
'1507498':{'en': 'Spring Grove, MN'},
'1512499':{'en': 'Austin, TX'},
'1609688':{'en': 'Princeton, NJ'},
'1514637':{'en': 'Lachine, QC'},
'1514636':{'en': 'Dorval, QC'},
'1514634':{'en': 'Lachine, QC'},
'1514633':{'en': 'Dorval, QC'},
'1514631':{'en': 'Dorval, QC'},
'1514630':{'en': 'Pointe-Claire, QC'},
'1514639':{'en': 'Lachine, QC'},
'1605232':{'en': 'North Sioux City, SD'},
'1605234':{'en': 'Chamberlain, SD'},
'1410939':{'en': 'Havre de Grace, MD'},
'1410938':{'en': 'Towson, MD'},
'1574262':{'en': 'Elkhart, IN'},
'1574266':{'en': 'Elkhart, IN'},
'1574267':{'en': 'Warsaw, IN'},
'1574264':{'en': 'Elkhart, IN'},
'1512671':{'en': 'Round Rock, TX'},
'1423569':{'en': 'Oneida, TN'},
'1423566':{'en': 'La Follette, TN'},
'1423562':{'en': 'La Follette, TN'},
'1506546':{'en': 'Bathurst, NB'},
'1561802':{'en': 'West Palm Beach, FL'},
'1561807':{'en': 'Boca Raton, FL'},
'1502384':{'en': 'Louisville, KY'},
'1506548':{'en': 'Bathurst, NB'},
'1585352':{'en': 'Spencerport, NY'},
'1615915':{'en': 'Nashville, TN'},
'1507237':{'en': 'Gaylord, MN'},
'1507235':{'en': 'Fairmont, MN'},
'1480218':{'en': 'Mesa, AZ'},
'1507233':{'en': 'New Ulm, MN'},
'1610363':{'en': 'Exton, PA'},
'1614398':{'en': 'Columbus, OH'},
'1602438':{'en': 'Phoenix, AZ'},
'1484223':{'en': 'Allentown, PA'},
'1507238':{'en': 'Fairmont, MN'},
'1615322':{'en': 'Nashville, TN'},
'1570696':{'en': 'Shavertown, PA'},
'1580536':{'en': 'Lawton, OK'},
'1573642':{'en': 'Fulton, MO'},
'1613549':{'en': 'Kingston, ON'},
'1506727':{'en': 'Caraquet, NB'},
'1573649':{'en': 'East Prairie, MO'},
'1602433':{'en': 'Phoenix, AZ'},
'1613547':{'en': 'Kingston, ON'},
'1613546':{'en': 'Kingston, ON'},
'1613543':{'en': 'Morrisburg, ON'},
'1613542':{'en': 'Kingston, ON'},
'1520626':{'en': 'Tucson, AZ'},
'1520625':{'en': 'Green Valley, AZ'},
'1519884':{'en': 'Waterloo, ON'},
'1520623':{'en': 'Tucson, AZ'},
'1520622':{'en': 'Tucson, AZ'},
'1520621':{'en': 'Tucson, AZ'},
'1520620':{'en': 'Tucson, AZ'},
'1605997':{'en': 'Flandreau, SD'},
'1615624':{'en': 'Murfreesboro, TN'},
'1540427':{'en': 'Roanoke, VA'},
'1520629':{'en': 'Tucson, AZ'},
'1520628':{'en': 'Tucson, AZ'},
'1417223':{'en': 'Pineville, MO'},
'1609466':{'en': 'Hopewell, NJ'},
'1435381':{'en': 'Castle Dale, UT'},
'1608655':{'en': 'Marshall, WI'},
'1617328':{'en': 'Quincy, MA'},
'1580395':{'en': 'Medford, OK'},
'1434654':{'en': 'Charlottesville, VA'},
'1434656':{'en': 'Gretna, VA'},
'1505563':{'en': 'Albuquerque, NM'},
'1505565':{'en': 'Los Lunas, NM'},
'1505564':{'en': 'Farmington, NM'},
'1570345':{'en': 'Pine Grove, PA'},
'1570344':{'en': 'Scranton, PA'},
'1570347':{'en': 'Scranton, PA'},
'1570346':{'en': 'Scranton, PA'},
'1570341':{'en': 'Scranton, PA'},
'1570340':{'en': 'Scranton, PA'},
'1570343':{'en': 'Scranton, PA'},
'1570342':{'en': 'Scranton, PA'},
'1561822':{'en': 'West Palm Beach, FL'},
'1561820':{'en': 'West Palm Beach, FL'},
'1612632':{'en': 'Minneapolis, MN'},
'1517750':{'en': 'Jackson, MI'},
'1434384':{'en': 'Lynchburg, VA'},
'1434385':{'en': 'Lynchburg, VA'},
'1510259':{'en': 'Hayward, CA'},
'1517975':{'en': 'Lansing, MI'},
'1510251':{'en': 'Oakland, CA'},
'1510522':{'en': 'Alameda, CA'},
'1510521':{'en': 'Alameda, CA'},
'1510252':{'en': 'Fremont, CA'},
'1541464':{'en': 'Roseburg, OR'},
'1541465':{'en': 'Eugene, OR'},
'1425438':{'en': 'Everett, WA'},
'1541461':{'en': 'Eugene, OR'},
'1541463':{'en': 'Eugene, OR'},
'1425432':{'en': 'Maple Valley, WA'},
'1425430':{'en': 'Renton, WA'},
'1541469':{'en': 'Brookings, OR'},
'1434476':{'en': 'Halifax, VA'},
'1616393':{'en': 'Holland, MI'},
'1616392':{'en': 'Holland, MI'},
'1616391':{'en': 'Grand Rapids, MI'},
'1616396':{'en': 'Holland, MI'},
'1616395':{'en': 'Holland, MI'},
'1616394':{'en': 'Holland, MI'},
'1616399':{'en': 'Holland, MI'},
'1514956':{'en': 'Saint-Laurent, QC'},
'1602304':{'en': 'Phoenix, AZ'},
'1514954':{'en': 'Montreal, QC'},
'1503808':{'en': 'Portland, OR'},
'1415885':{'en': 'San Francisco, CA'},
'1415882':{'en': 'San Francisco, CA'},
'1415883':{'en': 'Novato, CA'},
'1415888':{'en': 'Mill Valley, CA'},
'1615399':{'en': 'Nashville, TN'},
'1510441':{'en': 'Union City, CA'},
'1580735':{'en': 'Buffalo, OK'},
'1575737':{'en': 'Taos, NM'},
'1614544':{'en': 'Columbus, OH'},
'1602264':{'en': 'Phoenix, AZ'},
'1602265':{'en': 'Phoenix, AZ'},
'1413301':{'en': 'Springfield, MA'},
'1609340':{'en': 'Atlantic City, NJ'},
'1575882':{'en': 'Anthony, NM'},
'1478935':{'en': 'Lizella, GA'},
'1478934':{'en': 'Cochran, GA'},
'1575887':{'en': 'Carlsbad, NM'},
'1450458':{'en': 'Hudson, QC'},
'1509735':{'en': 'Kennewick, WA'},
'1509736':{'en': 'Kennewick, WA'},
'1509737':{'en': 'Kennewick, WA'},
'1450454':{'en': u('Saint-R\u00e9mi, QC')},
'1450455':{'en': 'Vaudreuil-Dorion, QC'},
'1518512':{'en': 'Albany, NY'},
'1450451':{'en': 'Rigaud, QC'},
'1450452':{'en': u('Les C\u00e8dres, QC')},
'1604629':{'en': 'Vancouver, BC'},
'1408866':{'en': 'Campbell, CA'},
'1408867':{'en': 'Saratoga, CA'},
'1530258':{'en': 'Chester, CA'},
'1530251':{'en': 'Susanville, CA'},
'1530257':{'en': 'Susanville, CA'},
'1450678':{'en': 'Saint-Hubert, QC'},
'1450679':{'en': 'Longueuil, QC'},
'1585442':{'en': 'Rochester, NY'},
'1509444':{'en': 'Spokane, WA'},
'1415460':{'en': 'San Rafael, CA'},
'1450670':{'en': 'Longueuil, QC'},
'1450674':{'en': 'Longueuil, QC'},
'1415468':{'en': 'San Francisco, CA'},
'1415469':{'en': 'San Francisco, CA'},
'1414223':{'en': 'Milwaukee, WI'},
'1414220':{'en': 'Milwaukee, WI'},
'1414226':{'en': 'Milwaukee, WI'},
'1414225':{'en': 'Milwaukee, WI'},
'1414224':{'en': 'Milwaukee, WI'},
'1414228':{'en': 'Milwaukee, WI'},
'1417326':{'en': 'Bolivar, MO'},
'1416516':{'en': 'Toronto, ON'},
'1416515':{'en': 'Toronto, ON'},
'1530333':{'en': 'Georgetown, CA'},
'1416512':{'en': 'North York, ON'},
'1530336':{'en': 'Fall River Mills, CA'},
'1416510':{'en': 'North York, ON'},
'1563875':{'en': 'Dyersville, IA'},
'1563873':{'en': 'McGregor, IA'},
'1563872':{'en': 'Bellevue, IA'},
'1520818':{'en': 'Tucson, AZ'},
'1520364':{'en': 'Douglas, AZ'},
'1512804':{'en': 'Austin, TX'},
'1512805':{'en': 'San Marcos, TX'},
'1415796':{'en': 'San Francisco, CA'},
'1604331':{'en': 'Vancouver, BC'},
'1605574':{'en': 'Hill City, SD'},
'1573256':{'en': 'Columbia, MO'},
'1608':{'en': 'Wisconsin'},
'1605578':{'en': 'Deadwood, SD'},
'1515465':{'en': 'Perry, IA'},
'1580421':{'en': 'Ada, OK'},
'1515462':{'en': 'Winterset, IA'},
'1614268':{'en': 'Columbus, OH'},
'1540921':{'en': 'Pearisburg, VA'},
'1503248':{'en': 'Portland, OR'},
'1503249':{'en': 'Portland, OR'},
'1503246':{'en': 'Portland, OR'},
'1503247':{'en': 'Portland, OR'},
'1503244':{'en': 'Portland, OR'},
'1503245':{'en': 'Portland, OR'},
'1503242':{'en': 'Portland, OR'},
'1503243':{'en': 'Portland, OR'},
'1503240':{'en': 'Portland, OR'},
'1503241':{'en': 'Portland, OR'},
'1610298':{'en': 'New Tripoli, PA'},
'1614267':{'en': 'Columbus, OH'},
'1505717':{'en': 'Albuquerque, NM'},
'1505715':{'en': 'Albuquerque, NM'},
'1606593':{'en': 'Booneville, KY'},
'1505710':{'en': 'Albuquerque, NM'},
'1614261':{'en': 'Columbus, OH'},
'1443977':{'en': 'Baltimore, MD'},
'1607':{'en': 'New York'},
'1614262':{'en': 'Columbus, OH'},
'1610282':{'en': 'Coopersburg, PA'},
'1478328':{'en': 'Warner Robins, GA'},
'1610280':{'en': 'Exton, PA'},
'1610287':{'en': 'Schwenksville, PA'},
'1614255':{'en': 'Columbus, OH'},
'1614257':{'en': 'Columbus, OH'},
'1614258':{'en': 'Columbus, OH'},
'1617':{'en': 'Massachusetts'},
'1614':{'en': 'Ohio'},
'1615':{'en': 'Tennessee'},
'1612':{'en': 'Minnesota'},
'1613':{'en': 'Ontario'},
'1610':{'en': 'Pennsylvania'},
'1541923':{'en': 'Redmond, OR'},
'1541922':{'en': 'Umatilla, OR'},
'1541924':{'en': 'Albany, OR'},
'1541926':{'en': 'Albany, OR'},
'1541929':{'en': 'Philomath, OR'},
'1541928':{'en': 'Albany, OR'},
'1541678':{'en': 'Bend, OR'},
'1530809':{'en': 'Chico, CA'},
'1541673':{'en': 'Roseburg, OR'},
'1541672':{'en': 'Roseburg, OR'},
'1541677':{'en': 'Roseburg, OR'},
'1541676':{'en': 'Heppner, OR'},
'1503658':{'en': 'Damascus, OR'},
'1410219':{'en': 'Salisbury, MD'},
'1410216':{'en': 'Annapolis, MD'},
'1503651':{'en': 'Canby, OR'},
'1410213':{'en': 'Ocean City, MD'},
'1503652':{'en': 'Clackamas, OR'},
'1423224':{'en': 'Kingsport, TN'},
'1605765':{'en': 'Gettysburg, SD'},
'1608756':{'en': 'Janesville, WI'},
'1570288':{'en': 'Kingston, PA'},
'1443394':{'en': 'Owings Mills, MD'},
'1514488':{'en': 'Montreal, QC'},
'1570282':{'en': 'Carbondale, PA'},
'1570283':{'en': 'Kingston, PA'},
'1570286':{'en': 'Sunbury, PA'},
'1508790':{'en': 'Hyannis, MA'},
'1610827':{'en': 'Chester Springs, PA'},
'1435245':{'en': 'Hyrum, UT'},
'1608757':{'en': 'Janesville, WI'},
'1614877':{'en': 'Orient, OH'},
'1435716':{'en': 'Logan, UT'},
'1614871':{'en': 'Grove City, OH'},
'1610821':{'en': 'Allentown, PA'},
'1610820':{'en': 'Allentown, PA'},
'1418449':{'en': 'Disraeli, QC'},
'1609729':{'en': 'Wildwood, NJ'},
'1614879':{'en': 'West Jefferson, OH'},
'1580250':{'en': 'Lawton, OK'},
'1580252':{'en': 'Duncan, OK'},
'1580254':{'en': 'Woodward, OK'},
'1580255':{'en': 'Duncan, OK'},
'1580256':{'en': 'Woodward, OK'},
'1609861':{'en': 'Woodbine, NJ'},
'1517568':{'en': 'Homer, MI'},
'1613732':{'en': 'Pembroke, ON'},
'1613733':{'en': 'Ottawa, ON'},
'1613730':{'en': 'Ottawa, ON'},
'1613731':{'en': 'Ottawa, ON'},
'1613736':{'en': 'Ottawa, ON'},
'1613737':{'en': 'Ottawa, ON'},
'1613735':{'en': 'Pembroke, ON'},
'1613738':{'en': 'Ottawa, ON'},
'1613739':{'en': 'Ottawa, ON'},
'1608242':{'en': 'Madison, WI'},
'1513221':{'en': 'Cincinnati, OH'},
'1612467':{'en': 'Minneapolis, MN'},
'1432943':{'en': 'Monahans, TX'},
'1513229':{'en': 'Mason, OH'},
'1513228':{'en': 'Lebanon, OH'},
'1614421':{'en': 'Columbus, OH'},
'1540989':{'en': 'Roanoke, VA'},
'1440288':{'en': 'Lorain, OH'},
'1440284':{'en': 'Elyria, OH'},
'1440285':{'en': 'Chardon, OH'},
'1440286':{'en': 'Chardon, OH'},
'1540983':{'en': 'Roanoke, VA'},
'1540984':{'en': 'Edinburg, VA'},
'1540985':{'en': 'Roanoke, VA'},
'1440282':{'en': 'Lorain, OH'},
'1540987':{'en': 'Sperryville, VA'},
'1610967':{'en': 'Emmaus, PA'},
'1502839':{'en': 'Lawrenceburg, KY'},
'1517694':{'en': 'Holt, MI'},
'1517699':{'en': 'Holt, MI'},
'1614294':{'en': 'Columbus, OH'},
'1503648':{'en': 'Hillsboro, OR'},
'1541582':{'en': 'Rogue River, OR'},
'1570752':{'en': 'Berwick, PA'},
'1570759':{'en': 'Berwick, PA'},
'1586286':{'en': 'Clinton Twp, MI'},
'1413796':{'en': 'Springfield, MA'},
'1413794':{'en': 'Springfield, MA'},
'1413827':{'en': 'Springfield, MA'},
'1580875':{'en': 'Walters, OK'},
'1410590':{'en': 'Glen Burnie, MD'},
'1585374':{'en': 'Naples, NY'},
'1410267':{'en': 'Annapolis, MD'},
'1410266':{'en': 'Annapolis, MD'},
'1602795':{'en': 'Phoenix, AZ'},
'1416679':{'en': 'Etobicoke, ON'},
'1416674':{'en': 'Etobicoke, ON'},
'1416675':{'en': 'Etobicoke, ON'},
'1510752':{'en': 'Oakland, CA'},
'1519341':{'en': 'Guelph, ON'},
'1519342':{'en': 'Kitchener, ON'},
'1519343':{'en': 'Palmerston, ON'},
'1519344':{'en': 'Sarnia, ON'},
'1604438':{'en': 'Burnaby, BC'},
'1608834':{'en': 'Sun Prairie, WI'},
'1519348':{'en': 'Mitchell, ON'},
'1604434':{'en': 'Burnaby, BC'},
'1604437':{'en': 'Burnaby, BC'},
'1507825':{'en': 'Pipestone, MN'},
'1604431':{'en': 'Burnaby, BC'},
'1603876':{'en': 'Marlborough, NH'},
'1604433':{'en': 'Burnaby, BC'},
'1604432':{'en': 'Burnaby, BC'},
'1608836':{'en': 'Middleton, WI'},
'1608831':{'en': 'Middleton, WI'},
'1504299':{'en': 'New Orleans, LA'},
'1450243':{'en': 'Brome Lake, QC'},
'1515699':{'en': 'Des Moines, IA'},
'1450245':{'en': 'Napierville, QC'},
'1608833':{'en': 'Madison, WI'},
'1450247':{'en': 'Hemmingford, QC'},
'1450246':{'en': 'Lacolle, QC'},
'1450248':{'en': 'Bedford, QC'},
'1423663':{'en': 'Huntsville, TN'},
'1508473':{'en': 'Milford, MA'},
'1508476':{'en': 'Douglas, MA'},
'1508477':{'en': 'Mashpee, MA'},
'1508478':{'en': 'Milford, MA'},
'1608839':{'en': 'Cottage Grove, WI'},
'1512551':{'en': 'Austin, TX'},
'1502254':{'en': 'Louisville, KY'},
'1408982':{'en': 'Santa Clara, CA'},
'1408980':{'en': 'Santa Clara, CA'},
'1408986':{'en': 'Santa Clara, CA'},
'1408988':{'en': 'Santa Clara, CA'},
'1604291':{'en': 'Burnaby, BC'},
'1604293':{'en': 'Burnaby, BC'},
'1604295':{'en': 'Richmond, BC'},
'1604294':{'en': 'Burnaby, BC'},
'1512479':{'en': 'Austin, TX'},
'1512478':{'en': 'Austin, TX'},
'1512477':{'en': 'Austin, TX'},
'1423765':{'en': 'Kingsport, TN'},
'1512474':{'en': 'Austin, TX'},
'1512473':{'en': 'Austin, TX'},
'1512472':{'en': 'Austin, TX'},
'1512471':{'en': 'Austin, TX'},
'1609660':{'en': 'Barnegat Township, NJ'},
'1516823':{'en': 'Valley Stream, NY'},
'1605745':{'en': 'Hot Springs, SD'},
'1605747':{'en': 'Rosebud, SD'},
'1605217':{'en': 'North Sioux City, SD'},
'1561686':{'en': 'West Palm Beach, FL'},
'1610965':{'en': 'Emmaus, PA'},
'1423508':{'en': 'Chattanooga, TN'},
'1508295':{'en': 'Wareham, MA'},
'1508291':{'en': 'Wareham, MA'},
'1512610':{'en': 'Austin, TX'},
'1512617':{'en': 'Austin, TX'},
'1602992':{'en': 'Phoenix, AZ'},
'1512615':{'en': 'Austin, TX'},
'1512614':{'en': 'Austin, TX'},
'1601914':{'en': 'Jackson, MS'},
'1506523':{'en': 'Richibucto, NB'},
'1580628':{'en': 'Tonkawa, OK'},
'1432447':{'en': 'Pecos, TX'},
'1506529':{'en': 'Saint Andrews, NB'},
'1432445':{'en': 'Pecos, TX'},
'1561826':{'en': 'Boca Raton, FL'},
'1602995':{'en': 'Phoenix, AZ'},
'1563689':{'en': 'Preston, IA'},
'1501513':{'en': 'Conway, AR'},
'1615396':{'en': 'Murfreesboro, TN'},
'1602997':{'en': 'Phoenix, AZ'},
'1615936':{'en': 'Nashville, TN'},
'1610619':{'en': 'Chester, PA'},
'1610347':{'en': 'Kennett Square, PA'},
'1610344':{'en': 'West Chester, PA'},
'1610345':{'en': 'West Grove, PA'},
'1615823':{'en': 'Nashville, TN'},
'1609890':{'en': 'Trenton, NJ'},
'1540400':{'en': 'Roanoke, VA'},
'1609877':{'en': 'Willingboro, NJ'},
'1573624':{'en': 'Dexter, MO'},
'1574936':{'en': 'Plymouth, IN'},
'1425317':{'en': 'Everett, WA'},
'1574935':{'en': 'Plymouth, IN'},
'1615641':{'en': 'Antioch, TN'},
'1615643':{'en': 'Greenbrier, TN'},
'1615644':{'en': 'Westmoreland, TN'},
'1615646':{'en': 'Nashville, TN'},
'1562985':{'en': 'Long Beach, CA'},
'1423447':{'en': 'Pikeville, TN'},
'1617391':{'en': 'Boston, MA'},
'1561355':{'en': 'West Palm Beach, FL'},
'1561353':{'en': 'Boca Raton, FL'},
'1617350':{'en': 'Boston, MA'},
'1419637':{'en': 'Gibsonburg, OH'},
'1419636':{'en': 'Bryan, OH'},
'1419634':{'en': 'Ada, OH'},
'1419633':{'en': 'Bryan, OH'},
'1480947':{'en': 'Scottsdale, AZ'},
'1480946':{'en': 'Scottsdale, AZ'},
'1480945':{'en': 'Scottsdale, AZ'},
'1480941':{'en': 'Scottsdale, AZ'},
'1606248':{'en': 'Middlesboro, KY'},
'1480949':{'en': 'Scottsdale, AZ'},
'1480948':{'en': 'Scottsdale, AZ'},
'1434676':{'en': 'Kenbridge, VA'},
'1561687':{'en': 'West Palm Beach, FL'},
'1561684':{'en': 'West Palm Beach, FL'},
'1561683':{'en': 'West Palm Beach, FL'},
'1561688':{'en': 'West Palm Beach, FL'},
'1561689':{'en': 'West Palm Beach, FL'},
'1613839':{'en': 'Carp, ON'},
'1613838':{'en': 'Richmond, ON'},
'1505508':{'en': 'Albuquerque, NM'},
'1613830':{'en': u('Orl\u00e9ans, ON')},
'1613833':{'en': 'Cumberland, ON'},
'1613835':{'en': 'Navan, ON'},
'1613834':{'en': u('Orl\u00e9ans, ON')},
'1613837':{'en': u('Orl\u00e9ans, ON')},
'1410667':{'en': 'Cockeysville, MD'},
'1410666':{'en': 'Cockeysville, MD'},
'1410665':{'en': 'Parkville, MD'},
'1410664':{'en': 'Baltimore, MD'},
'1410662':{'en': 'Baltimore, MD'},
'1505503':{'en': 'Albuquerque, NM'},
'1613521':{'en': 'Ottawa, ON'},
'1505507':{'en': 'Albuquerque, NM'},
'1410669':{'en': 'Baltimore, MD'},
'1443708':{'en': 'Baltimore, MD'},
'1516572':{'en': 'East Meadow, NY'},
'1516576':{'en': 'Plainview, NY'},
'1434455':{'en': 'Lynchburg, VA'},
'1517223':{'en': 'Fowlerville, MI'},
'1510505':{'en': 'Fremont, CA'},
'1608779':{'en': 'Onalaska, WI'},
'1541447':{'en': 'Prineville, OR'},
'1602368':{'en': 'Phoenix, AZ'},
'1541440':{'en': 'Roseburg, OR'},
'1503823':{'en': 'Portland, OR'},
'1503829':{'en': 'Molalla, OR'},
'1418589':{'en': 'Baie-Comeau, QC'},
'1418587':{'en': 'Forestville, QC'},
'1418856':{'en': u('La Pocati\u00e8re, QC')},
'1418851':{'en': 'Trois-Pistoles, QC'},
'1418853':{'en': 'Degelis, QC'},
'1562691':{'en': 'La Habra, CA'},
'1607272':{'en': 'Ithaca, NY'},
'1607273':{'en': 'Ithaca, NY'},
'1562693':{'en': 'Whittier, CA'},
'1562695':{'en': 'Whittier, CA'},
'1413363':{'en': 'Springfield, MA'},
'1440546':{'en': 'Cleveland, OH'},
'1413367':{'en': 'Montague, MA'},
'1562696':{'en': 'Whittier, CA'},
'1562697':{'en': 'La Habra, CA'},
'1502995':{'en': 'Louisville, KY'},
'1518758':{'en': 'Valatie, NY'},
'1518756':{'en': 'Ravena, NY'},
'1518753':{'en': 'Schaghticoke, NY'},
'1478953':{'en': 'Warner Robins, GA'},
'1514422':{'en': 'Dorval, QC'},
'1478956':{'en': 'Byron, GA'},
'1616738':{'en': 'Holland, MI'},
'1519482':{'en': 'Clinton, ON'},
'1514428':{'en': 'Pointe-Claire, QC'},
'1602588':{'en': 'Glendale, AZ'},
'1612872':{'en': 'Minneapolis, MN'},
'1612873':{'en': 'Minneapolis, MN'},
'1612870':{'en': 'Minneapolis, MN'},
'1612871':{'en': 'Minneapolis, MN'},
'1612877':{'en': 'Minneapolis, MN'},
'1612874':{'en': 'Minneapolis, MN'},
'1612879':{'en': 'Minneapolis, MN'},
'1518286':{'en': 'Rensselaer, NY'},
'1450477':{'en': 'Terrebonne, QC'},
'1450474':{'en': 'Mascouche, QC'},
'1450475':{'en': 'Mirabel, QC'},
'1450472':{'en': 'Saint-Eustache, QC'},
'1450473':{'en': 'Saint-Eustache, QC'},
'1450470':{'en': 'Repentigny, QC'},
'1450471':{'en': 'Terrebonne, QC'},
'1450478':{'en': 'Sainte-Anne-des-Plaines, QC'},
'1450479':{'en': 'Oka, QC'},
'1509248':{'en': 'Yakima, WA'},
'1509249':{'en': 'Yakima, WA'},
'1509244':{'en': 'Airway Heights, WA'},
'1509242':{'en': 'Spokane, WA'},
'1508595':{'en': 'Worcester, MA'},
'1413587':{'en': 'Northampton, MA'},
'1413586':{'en': 'Northampton, MA'},
'1413585':{'en': 'Northampton, MA'},
'1413584':{'en': 'Northampton, MA'},
'1413583':{'en': 'Ludlow, MA'},
'1413582':{'en': 'Northampton, MA'},
'1408848':{'en': 'Gilroy, CA'},
'1530272':{'en': 'Grass Valley, CA'},
'1408846':{'en': 'Gilroy, CA'},
'1408847':{'en': 'Gilroy, CA'},
'1408844':{'en': 'Santa Clara, CA'},
'1408842':{'en': 'Gilroy, CA'},
'1413589':{'en': 'Ludlow, MA'},
'1450652':{'en': 'Varennes, QC'},
'1450653':{'en': 'St-Bruno-de-Montarville, QC'},
'1450651':{'en': 'Longueuil, QC'},
'1450656':{'en': 'Saint-Hubert, QC'},
'1450657':{'en': 'Repentigny, QC'},
'1450654':{'en': 'Repentigny, QC'},
'1450655':{'en': 'Boucherville, QC'},
'1450658':{'en': 'Chambly, QC'},
'1450659':{'en': 'La Prairie, QC'},
'1415400':{'en': 'San Francisco, CA'},
'1415401':{'en': 'San Francisco, CA'},
'1414805':{'en': 'Milwaukee, WI'},
'1412363':{'en': 'Pittsburgh, PA'},
'1412364':{'en': 'Pittsburgh, PA'},
'1412365':{'en': 'Pittsburgh, PA'},
'1412366':{'en': 'Pittsburgh, PA'},
'1412367':{'en': 'Pittsburgh, PA'},
'1585428':{'en': 'Rochester, NY'},
'1415409':{'en': 'San Francisco, CA'},
'1540297':{'en': 'Moneta, VA'},
'1414755':{'en': 'Milwaukee, WI'},
'1416531':{'en': 'Toronto, ON'},
'1416530':{'en': 'Toronto, ON'},
'1416533':{'en': 'Toronto, ON'},
'1416532':{'en': 'Toronto, ON'},
'1416535':{'en': 'Toronto, ON'},
'1416534':{'en': 'Toronto, ON'},
'1416537':{'en': 'Toronto, ON'},
'1416536':{'en': 'Toronto, ON'},
'1416539':{'en': 'Toronto, ON'},
'1416538':{'en': 'Toronto, ON'},
'1540231':{'en': 'Blacksburg, VA'},
'1540234':{'en': 'Weyers Cave, VA'},
'1608278':{'en': 'Madison, WI'},
'1502339':{'en': 'Louisville, KY'},
'1519627':{'en': 'Wallaceburg, ON'},
'1585398':{'en': 'Farmington, NY'},
'1512863':{'en': 'Georgetown, TX'},
'1512864':{'en': 'Georgetown, TX'},
'1519622':{'en': 'Cambridge, ON'},
'1519621':{'en': 'Cambridge, ON'},
'1519620':{'en': 'Cambridge, ON'},
'1512868':{'en': 'Georgetown, TX'},
'1512869':{'en': 'Georgetown, TX'},
'1604608':{'en': 'Vancouver, BC'},
'1604609':{'en': 'Vancouver, BC'},
'1585396':{'en': 'Canandaigua, NY'},
'1585394':{'en': 'Canandaigua, NY'},
'1585395':{'en': 'Brockport, NY'},
'1615895':{'en': 'Murfreesboro, TN'},
'1615896':{'en': 'Murfreesboro, TN'},
'1615891':{'en': 'Nashville, TN'},
'1615890':{'en': 'Murfreesboro, TN'},
'1615893':{'en': 'Murfreesboro, TN'},
'1615898':{'en': 'Murfreesboro, TN'},
'1503228':{'en': 'Portland, OR'},
'1503229':{'en': 'Portland, OR'},
'1503220':{'en': 'Portland, OR'},
'1503221':{'en': 'Portland, OR'},
'1503222':{'en': 'Portland, OR'},
'1503223':{'en': 'Portland, OR'},
'1503224':{'en': 'Portland, OR'},
'1503225':{'en': 'Portland, OR'},
'1503226':{'en': 'Portland, OR'},
'1503227':{'en': 'Portland, OR'},
'1508624':{'en': 'Marlborough, MA'},
'1508627':{'en': 'Edgartown, MA'},
'1508626':{'en': 'Framingham, MA'},
'1508620':{'en': 'Framingham, MA'},
'1559747':{'en': 'Farmersville, CA'},
'1508628':{'en': 'Framingham, MA'},
'1601271':{'en': 'Hattiesburg, MS'},
'1601276':{'en': 'Summit, MS'},
'1574893':{'en': 'Akron, IN'},
'1574892':{'en': 'Argos, IN'},
'1574896':{'en': 'North Judson, IN'},
'1574546':{'en': 'Bremen, IN'},
'1512284':{'en': 'Austin, TX'},
'1512285':{'en': 'Elgin, TX'},
'1609497':{'en': 'Princeton, NJ'},
'1512280':{'en': 'Austin, TX'},
'1512281':{'en': 'Elgin, TX'},
'1512282':{'en': 'Austin, TX'},
'1435882':{'en': 'Tooele, UT'},
'1614273':{'en': 'Columbus, OH'},
'1512288':{'en': 'Austin, TX'},
'1541592':{'en': 'Cave Junction, OR'},
'1435884':{'en': 'Grantsville, UT'},
'1614275':{'en': 'Columbus, OH'},
'1559456':{'en': 'Fresno, CA'},
'1541942':{'en': 'Cottage Grove, OR'},
'1541941':{'en': 'Medford, OR'},
'1541947':{'en': 'Lakeview, OR'},
'1570726':{'en': 'Mill Hall, PA'},
'1410585':{'en': 'Baltimore, MD'},
'1410581':{'en': 'Owings Mills, MD'},
'1570724':{'en': 'Wellsboro, PA'},
'1530865':{'en': 'Orland, CA'},
'1606589':{'en': 'Cumberland, KY'},
'1410272':{'en': 'Aberdeen, MD'},
'1410273':{'en': 'Aberdeen, MD'},
'1410276':{'en': 'Baltimore, MD'},
'1615370':{'en': 'Brentwood, TN'},
'1416255':{'en': 'Etobicoke, ON'},
'1423247':{'en': 'Kingsport, TN'},
'1423246':{'en': 'Kingsport, TN'},
'1423245':{'en': 'Kingsport, TN'},
'1601587':{'en': 'Monticello, MS'},
'1601584':{'en': 'Hattiesburg, MS'},
'1615373':{'en': 'Brentwood, TN'},
'1601582':{'en': 'Hattiesburg, MS'},
'1601583':{'en': 'Hattiesburg, MS'},
'1432272':{'en': 'Odessa, TX'},
'1416250':{'en': 'North York, ON'},
'1419207':{'en': 'Ashland, OH'},
'1513423':{'en': 'Middletown, OH'},
'1513422':{'en': 'Middletown, OH'},
'1513421':{'en': 'Cincinnati, OH'},
'1513420':{'en': 'Middletown, OH'},
'1606723':{'en': 'Irvine, KY'},
'1416924':{'en': 'Toronto, ON'},
'1513425':{'en': 'Middletown, OH'},
'1513424':{'en': 'Middletown, OH'},
'1416253':{'en': 'Etobicoke, ON'},
'1415989':{'en': 'San Francisco, CA'},
'1610807':{'en': 'Bethlehem, PA'},
'1504828':{'en': 'Metairie, LA'},
'1440734':{'en': 'North Olmsted, OH'},
'1415984':{'en': 'San Francisco, CA'},
'1415986':{'en': 'San Francisco, CA'},
'1415981':{'en': 'San Francisco, CA'},
'1504822':{'en': 'New Orleans, LA'},
'1415983':{'en': 'San Francisco, CA'},
'1415982':{'en': 'San Francisco, CA'},
'1417588':{'en': 'Lebanon, MO'},
'1479238':{'en': 'Siloam Springs, AR'},
'1410381':{'en': 'Columbia, MD'},
'1417582':{'en': 'Ozark, MO'},
'1417581':{'en': 'Ozark, MO'},
'1580276':{'en': 'Marietta, OK'},
'1540310':{'en': 'Fredericksburg, VA'},
'1612626':{'en': 'Minneapolis, MN'},
'1541617':{'en': 'Bend, OR'},
'1606437':{'en': 'Pikeville, KY'},
'1410385':{'en': 'Baltimore, MD'},
'1585293':{'en': 'Churchville, NY'},
'1516632':{'en': 'Oceanside, NY'},
'1606435':{'en': 'Hazard, KY'},
'1417725':{'en': 'Nixa, MO'},
'1417724':{'en': 'Nixa, MO'},
'1417723':{'en': 'Crane, MO'},
'1606439':{'en': 'Hazard, KY'},
'1561544':{'en': 'Boca Raton, FL'},
'1419841':{'en': 'Toledo, OH'},
'1419842':{'en': 'Toledo, OH'},
'1419843':{'en': 'Toledo, OH'},
'1570739':{'en': 'Schuylkill Haven, PA'},
'1419849':{'en': 'Woodville, OH'},
'1586268':{'en': 'Sterling Heights, MI'},
'1413774':{'en': 'Greenfield, MA'},
'1586264':{'en': 'Sterling Heights, MI'},
'1586263':{'en': 'Clinton Twp, MI'},
'1413772':{'en': 'Greenfield, MA'},
'1413773':{'en': 'Greenfield, MA'},
'1479495':{'en': 'Danville, AR'},
'1479494':{'en': 'Fort Smith, AR'},
'1580856':{'en': 'Ratliff City, OK'},
'1425576':{'en': 'Kirkland, WA'},
'1616726':{'en': 'Grand Rapids, MI'},
'1575388':{'en': 'Silver City, NM'},
'1602778':{'en': 'Phoenix, AZ'},
'1514858':{'en': 'Montreal, QC'},
'1575382':{'en': 'Las Cruces, NM'},
'1604277':{'en': 'Richmond, BC'},
'1514855':{'en': 'Saint-Laurent, QC'},
'1575387':{'en': 'Mora, NM'},
'1607724':{'en': 'Binghamton, NY'},
'1604274':{'en': 'Richmond, BC'},
'1607722':{'en': 'Binghamton, NY'},
'1607723':{'en': 'Binghamton, NY'},
'1585275':{'en': 'Rochester, NY'},
'1440543':{'en': 'Chagrin Falls, OH'},
'1510770':{'en': 'Fremont, CA'},
'1610687':{'en': 'Wayne, PA'},
'1519368':{'en': 'Tiverton, ON'},
'1519369':{'en': 'Durham, ON'},
'1519363':{'en': 'Chesley, ON'},
'1519367':{'en': 'Mildmay, ON'},
'1519364':{'en': 'Hanover, ON'},
'1507847':{'en': 'Jackson, MN'},
'1585273':{'en': 'Rochester, NY'},
'1610683':{'en': 'Kutztown, PA'},
'1409832':{'en': 'Beaumont, TX'},
'1409833':{'en': 'Beaumont, TX'},
'1409835':{'en': 'Beaumont, TX'},
'1409838':{'en': 'Beaumont, TX'},
'1409839':{'en': 'Beaumont, TX'},
'1480759':{'en': 'Phoenix, AZ'},
'1450226':{'en': 'Morin-Heights, QC'},
'1450225':{'en': 'Beauharnois, QC'},
'1450224':{'en': u('Pr\u00e9vost, QC')},
'1508459':{'en': 'Worcester, MA'},
'1508457':{'en': 'Falmouth, MA'},
'1412647':{'en': 'Pittsburgh, PA'},
'1415341':{'en': 'San Francisco, CA'},
'1423745':{'en': 'Athens, TN'},
'1415346':{'en': 'San Francisco, CA'},
'1412641':{'en': 'Pittsburgh, PA'},
'1418269':{'en': u('Gasp\u00e9, QC')},
'1415348':{'en': 'San Francisco, CA'},
'1412648':{'en': 'Pittsburgh, PA'},
'1512459':{'en': 'Austin, TX'},
'1512458':{'en': 'Austin, TX'},
'1609399':{'en': 'Ocean City, NJ'},
'1609398':{'en': 'Ocean City, NJ'},
'1512451':{'en': 'Austin, TX'},
'1512450':{'en': 'Austin, TX'},
'1512453':{'en': 'Austin, TX'},
'1512452':{'en': 'Austin, TX'},
'1609397':{'en': 'Lambertville, NJ'},
'1512454':{'en': 'Austin, TX'},
'1512457':{'en': 'Austin, TX'},
'1609394':{'en': 'Trenton, NJ'},
'1609572':{'en': 'Atlantic City, NJ'},
'1514678':{'en': 'Montreal, QC'},
'1605763':{'en': 'Beresford, SD'},
'1575391':{'en': 'Hobbs, NM'},
'1514670':{'en': 'Montreal, QC'},
'1603647':{'en': 'Manchester, NH'},
'1603646':{'en': 'Hanover, NH'},
'1501686':{'en': 'Little Rock, AR'},
'1501687':{'en': 'Little Rock, AR'},
'1603643':{'en': 'Hanover, NH'},
'1603642':{'en': 'Kingston, NH'},
'1501682':{'en': 'Little Rock, AR'},
'1610942':{'en': 'Glenmoore, PA'},
'1563441':{'en': 'Davenport, IA'},
'1607369':{'en': 'Unadilla, NY'},
'1563332':{'en': 'Bettendorf, IA'},
'1563445':{'en': 'Davenport, IA'},
'1514426':{'en': 'Pointe-Claire, QC'},
'1512637':{'en': 'Austin, TX'},
'1423521':{'en': 'Chattanooga, TN'},
'1502348':{'en': 'Bardstown, KY'},
'1502349':{'en': 'Bardstown, KY'},
'1506756':{'en': 'Petitcodiac, NB'},
'1605498':{'en': 'Tea, SD'},
'1570925':{'en': 'Benton, PA'},
'1440899':{'en': 'Cleveland, OH'},
'1604522':{'en': 'New Westminster, BC'},
'1501537':{'en': 'Little Rock, AR'},
'1440893':{'en': 'Chagrin Falls, OH'},
'1520444':{'en': 'Tucson, AZ'},
'1440895':{'en': 'Cleveland, OH'},
'1559227':{'en': 'Fresno, CA'},
'1559226':{'en': 'Fresno, CA'},
'1559225':{'en': 'Fresno, CA'},
'1559224':{'en': 'Fresno, CA'},
'1559222':{'en': 'Fresno, CA'},
'1559221':{'en': 'Fresno, CA'},
'1610323':{'en': 'Pottstown, PA'},
'1507275':{'en': 'Hendricks, MN'},
'1507274':{'en': 'Westbrook, MN'},
'1519485':{'en': 'Ingersoll, ON'},
'1414562':{'en': 'Milwaukee, WI'},
'1604606':{'en': 'Vancouver, BC'},
'1416927':{'en': 'Toronto, ON'},
'1606387':{'en': 'Albany, KY'},
'1573359':{'en': 'Hayti, MO'},
'1573358':{'en': 'Bonne Terre, MO'},
'1615662':{'en': 'Nashville, TN'},
'1615661':{'en': 'Brentwood, TN'},
'1615666':{'en': 'Lafayette, TN'},
'1615665':{'en': 'Nashville, TN'},
'1520663':{'en': 'Tucson, AZ'},
'1561374':{'en': 'Boynton Beach, FL'},
'1417269':{'en': 'Springfield, MO'},
'1561372':{'en': 'Boca Raton, FL'},
'1417264':{'en': 'Thayer, MO'},
'1601645':{'en': 'Centreville, MS'},
'1605945':{'en': 'Pierre, SD'},
'1601649':{'en': 'Laurel, MS'},
'1505699':{'en': 'Santa Fe, NM'},
'1505690':{'en': 'Santa Fe, NM'},
'1480961':{'en': 'Chandler, AZ'},
'1480963':{'en': 'Chandler, AZ'},
'1480962':{'en': 'Mesa, AZ'},
'1480965':{'en': 'Tempe, AZ'},
'1480964':{'en': 'Mesa, AZ'},
'1480967':{'en': 'Tempe, AZ'},
'1480966':{'en': 'Tempe, AZ'},
'1480969':{'en': 'Mesa, AZ'},
'1480784':{'en': 'Tempe, AZ'},
'1480786':{'en': 'Chandler, AZ'},
'1480782':{'en': 'Chandler, AZ'},
'1613673':{'en': 'Plantagenet, ON'},
'1603362':{'en': 'Atkinson, NH'},
'1613679':{'en': 'Alfred, ON'},
'1613678':{'en': 'Vankleek Hill, ON'},
'1410641':{'en': 'Berlin, MD'},
'1409794':{'en': 'Beaumont, TX'},
'1410643':{'en': 'Stevensville, MD'},
'1410642':{'en': 'Perryville, MD'},
'1410644':{'en': 'Baltimore, MD'},
'1410647':{'en': 'Severna Park, MD'},
'1410646':{'en': 'Baltimore, MD'},
'1605367':{'en': 'Sioux Falls, SD'},
'1615807':{'en': 'Franklin, TN'},
'1604421':{'en': 'Burnaby, BC'},
'1434929':{'en': 'Madison Heights, VA'},
'1434924':{'en': 'Charlottesville, VA'},
'1615597':{'en': 'Smithville, TN'},
'1541420':{'en': 'Bend, OR'},
'1602344':{'en': 'Phoenix, AZ'},
'1602347':{'en': 'Phoenix, AZ'},
'1602340':{'en': 'Phoenix, AZ'},
'1541426':{'en': 'Enterprise, OR'},
'1418877':{'en': 'Quebec City, QC'},
'1418873':{'en': 'Pont-Rouge, QC'},
'1418871':{'en': 'Quebec City, QC'},
'1604588':{'en': 'Surrey, BC'},
'1418878':{'en': 'Saint-Augustin-de-Desmaures, QC'},
'1469241':{'en': 'Plano, TX'},
'1410524':{'en': 'Ocean City, MD'},
'1410525':{'en': 'Baltimore, MD'},
'1501336':{'en': 'Conway, AR'},
'1501337':{'en': 'Malvern, AR'},
'1518773':{'en': 'Gloversville, NY'},
'1435527':{'en': 'Monroe, UT'},
'1435529':{'en': 'Salina, UT'},
'1435528':{'en': 'Gunnison, UT'},
'1510562':{'en': 'Oakland, CA'},
'1510567':{'en': 'Oakland, CA'},
'1517244':{'en': 'Mason, MI'},
'1510569':{'en': 'Oakland, CA'},
'1510568':{'en': 'Oakland, CA'},
'1478751':{'en': 'Macon, GA'},
'1478750':{'en': 'Macon, GA'},
'1478755':{'en': 'Macon, GA'},
'1478757':{'en': 'Macon, GA'},
'1410528':{'en': 'Baltimore, MD'},
'1478971':{'en': 'Warner Robins, GA'},
'1615284':{'en': 'Nashville, TN'},
'1616575':{'en': 'Grand Rapids, MI'},
'1450417':{'en': 'Mascouche, QC'},
'1603343':{'en': 'Dover, NH'},
'1603436':{'en': 'Portsmouth, NH'},
'1603430':{'en': 'Portsmouth, NH'},
'1603431':{'en': 'Portsmouth, NH'},
'1603433':{'en': 'Portsmouth, NH'},
'1541767':{'en': 'Cottage Grove, OR'},
'1416739':{'en': 'North York, ON'},
'1530297':{'en': 'Davis, CA'},
'1416736':{'en': 'North York, ON'},
'1530295':{'en': 'Placerville, CA'},
'1416733':{'en': 'North York, ON'},
'1416730':{'en': 'North York, ON'},
'1530275':{'en': 'Shasta Lake, CA'},
'1510383':{'en': 'Oakland, CA'},
'1614429':{'en': 'Columbus, OH'},
'1530274':{'en': 'Grass Valley, CA'},
'1604661':{'en': 'Vancouver, BC'},
'1412434':{'en': 'Pittsburgh, PA'},
'1412343':{'en': 'Pittsburgh, PA'},
'1415421':{'en': 'San Francisco, CA'},
'1425388':{'en': 'Everett, WA'},
'1412431':{'en': 'Pittsburgh, PA'},
'1412432':{'en': 'Pittsburgh, PA'},
'1563785':{'en': 'Durant, IA'},
'1414778':{'en': 'Milwaukee, WI'},
'1530273':{'en': 'Grass Valley, CA'},
'1414771':{'en': 'Milwaukee, WI'},
'1414774':{'en': 'Milwaukee, WI'},
'1414777':{'en': 'Milwaukee, WI'},
'1608251':{'en': 'Madison, WI'},
'1608250':{'en': 'Madison, WI'},
'1608253':{'en': 'Wisconsin Dells, WI'},
'1608252':{'en': 'Madison, WI'},
'1608255':{'en': 'Madison, WI'},
'1608254':{'en': 'Wisconsin Dells, WI'},
'1608257':{'en': 'Madison, WI'},
'1608256':{'en': 'Madison, WI'},
'1608259':{'en': 'Madison, WI'},
'1608258':{'en': 'Madison, WI'},
'1530279':{'en': 'Cedarville, CA'},
'1513598':{'en': 'Cincinnati, OH'},
'1509996':{'en': 'Winthrop, WA'},
'1509997':{'en': 'Twisp, WA'},
'1519601':{'en': 'London, ON'},
'1609252':{'en': 'Princeton, NJ'},
'1512846':{'en': 'Hutto, TX'},
'1512847':{'en': 'Wimberley, TX'},
'1504467':{'en': 'Kenner, LA'},
'1504466':{'en': 'Kenner, LA'},
'1504465':{'en': 'Kenner, LA'},
'1504464':{'en': 'Kenner, LA'},
'1615459':{'en': 'Smyrna, TN'},
'1504461':{'en': 'Kenner, LA'},
'1605532':{'en': 'Clark, SD'},
'1615874':{'en': 'Nashville, TN'},
'1615873':{'en': 'Nashville, TN'},
'1615872':{'en': 'Nashville, TN'},
'1504469':{'en': 'Kenner, LA'},
'1504468':{'en': 'Kenner, LA'},
'1503203':{'en': 'Portland, OR'},
'1503206':{'en': 'Portland, OR'},
'1503208':{'en': 'Portland, OR'},
'1562789':{'en': 'Whittier, CA'},
'1415288':{'en': 'San Francisco, CA'},
'1415289':{'en': 'Sausalito, CA'},
'1415284':{'en': 'San Francisco, CA'},
'1415285':{'en': 'San Francisco, CA'},
'1415282':{'en': 'San Francisco, CA'},
'1415283':{'en': 'San Francisco, CA'},
'1415281':{'en': 'San Francisco, CA'},
'1559945':{'en': 'Huron, CA'},
'1505753':{'en': 'Espanola, NM'},
'1505757':{'en': 'Pecos, NM'},
'1541967':{'en': 'Albany, OR'},
'1541966':{'en': 'Pendleton, OR'},
'1541963':{'en': 'La Grande, OR'},
'1412361':{'en': 'Pittsburgh, PA'},
'1412362':{'en': 'Pittsburgh, PA'},
'1604951':{'en': 'Surrey, BC'},
'1414483':{'en': 'Milwaukee, WI'},
'1414482':{'en': 'Milwaukee, WI'},
'1414481':{'en': 'Milwaukee, WI'},
'1585423':{'en': 'Rochester, NY'},
'1414486':{'en': 'Milwaukee, WI'},
'1585424':{'en': 'Rochester, NY'},
'1414489':{'en': 'Cudahy, WI'},
'1585425':{'en': 'Fairport, NY'},
'1410250':{'en': 'Ocean City, MD'},
'1585426':{'en': 'Rochester, NY'},
'1410254':{'en': 'Baltimore, MD'},
'1410255':{'en': 'Pasadena, MD'},
'1585427':{'en': 'Rochester, NY'},
'1423265':{'en': 'Chattanooga, TN'},
'1423267':{'en': 'Chattanooga, TN'},
'1423266':{'en': 'Chattanooga, TN'},
'1423263':{'en': 'Etowah, TN'},
'1412369':{'en': 'Pittsburgh, PA'},
'1601250':{'en': 'McComb, MS'},
'1613448':{'en': 'Chesterville, ON'},
'1613445':{'en': 'Russell, ON'},
'1613446':{'en': 'Rockland, ON'},
'1613443':{'en': 'Embrun, ON'},
'1440716':{'en': 'North Olmsted, OH'},
'1440717':{'en': 'Cleveland, OH'},
'1612798':{'en': 'Richfield, MN'},
'1513407':{'en': 'Cincinnati, OH'},
'1516921':{'en': 'Syosset, NY'},
'1516432':{'en': 'Long Beach, NY'},
'1516431':{'en': 'Long Beach, NY'},
'1516922':{'en': 'Oyster Bay, NY'},
'1614839':{'en': 'Westerville, OH'},
'1610869':{'en': 'West Grove, PA'},
'1610868':{'en': 'Bethlehem, PA'},
'1501833':{'en': 'Sherwood, AR'},
'1610861':{'en': 'Bethlehem, PA'},
'1610867':{'en': 'Bethlehem, PA'},
'1610866':{'en': 'Bethlehem, PA'},
'1501835':{'en': 'Sherwood, AR'},
'1501834':{'en': 'Sherwood, AR'},
'1517529':{'en': 'Clarklake, MI'},
'1517522':{'en': 'Grass Lake Charter Township, MI'},
'1517523':{'en': 'Osseo, MI'},
'1517521':{'en': 'Webberville, MI'},
'1580924':{'en': 'Durant, OK'},
'1517524':{'en': 'Concord, MI'},
'1530842':{'en': 'Yreka, CA'},
'1530841':{'en': 'Yreka, CA'},
'1530846':{'en': 'Gridley, CA'},
'1541636':{'en': 'Eugene, OR'},
'1541633':{'en': 'Bend, OR'},
'1570465':{'en': 'New Milford, PA'},
'1540948':{'en': 'Madison, VA'},
'1540949':{'en': 'Waynesboro, VA'},
'1540946':{'en': 'Waynesboro, VA'},
'1540941':{'en': 'Waynesboro, VA'},
'1540942':{'en': 'Waynesboro, VA'},
'1540943':{'en': 'Waynesboro, VA'},
'1502561':{'en': 'Louisville, KY'},
'1502562':{'en': 'Louisville, KY'},
'1502564':{'en': 'Frankfort, KY'},
'1502568':{'en': 'Louisville, KY'},
'1502569':{'en': 'Louisville, KY'},
'1425635':{'en': 'Bellevue, WA'},
'1425637':{'en': 'Bellevue, WA'},
'1609656':{'en': 'Trenton, NJ'},
'1608276':{'en': 'Madison, WI'},
'1530318':{'en': 'South Lake Tahoe, CA'},
'1615453':{'en': 'Lebanon, TN'},
'1570718':{'en': 'Kingston, PA'},
'1608274':{'en': 'Madison, WI'},
'1580928':{'en': 'Sayre, OK'},
'1608273':{'en': 'Madison, WI'},
'1419864':{'en': 'Cardington, OH'},
'1570247':{'en': 'Rome, PA'},
'1419862':{'en': 'Elmore, OH'},
'1570714':{'en': 'Kingston, PA'},
'1413289':{'en': 'Palmer, MA'},
'1608271':{'en': 'Madison, WI'},
'1586792':{'en': 'Clinton Twp, MI'},
'1586791':{'en': 'Clinton Twp, MI'},
'1413283':{'en': 'Palmer, MA'},
'1413284':{'en': 'Palmer, MA'},
'1586795':{'en': 'Sterling Heights, MI'},
'1615452':{'en': 'Gallatin, TN'},
'1479968':{'en': 'Russellville, AR'},
'1479963':{'en': 'Paris, AR'},
'1479965':{'en': 'Charleston, AR'},
'1604284':{'en': 'Richmond, BC'},
'1479967':{'en': 'Russellville, AR'},
'1479966':{'en': 'Fayetteville, AR'},
'1425558':{'en': 'Redmond, WA'},
'1609654':{'en': 'Medford, NJ'},
'1512467':{'en': 'Austin, TX'},
'1425557':{'en': 'Issaquah, WA'},
'1425556':{'en': 'Redmond, WA'},
'1514879':{'en': 'Montreal, QC'},
'1514878':{'en': 'Montreal, QC'},
'1616742':{'en': 'Grand Rapids, MI'},
'1423757':{'en': 'Chattanooga, TN'},
'1514871':{'en': 'Montreal, QC'},
'1480657':{'en': 'Scottsdale, AZ'},
'1514872':{'en': 'Montreal, QC'},
'1514875':{'en': 'Montreal, QC'},
'1514874':{'en': 'Montreal, QC'},
'1602286':{'en': 'Phoenix, AZ'},
'1503788':{'en': 'Portland, OR'},
'1480655':{'en': 'Mesa, AZ'},
'1519836':{'en': 'Guelph, ON'},
'1519837':{'en': 'Guelph, ON'},
'1519832':{'en': 'Port Elgin, ON'},
'1507867':{'en': 'Chatfield, MN'},
'1507864':{'en': 'Rushford, MN'},
'1510713':{'en': 'Fremont, CA'},
'1609652':{'en': 'Galloway, NJ'},
'1519839':{'en': 'Cottam, ON'},
'1409212':{'en': 'Beaumont, TX'},
'1509529':{'en': 'Walla Walla, WA'},
'1509520':{'en': 'Walla Walla, WA'},
'1509522':{'en': 'Walla Walla, WA'},
'1509525':{'en': 'Walla Walla, WA'},
'1509527':{'en': 'Walla Walla, WA'},
'1509526':{'en': 'Walla Walla, WA'},
'1604602':{'en': 'Vancouver, BC'},
'1514389':{'en': 'Montreal, QC'},
'1514388':{'en': 'Montreal, QC'},
'1514383':{'en': 'Montreal, QC'},
'1514382':{'en': 'Montreal, QC'},
'1514381':{'en': 'Montreal, QC'},
'1514387':{'en': 'Montreal, QC'},
'1514385':{'en': 'Montreal, QC'},
'1514384':{'en': 'Montreal, QC'},
'1586427':{'en': 'Warren, MI'},
'1519624':{'en': 'Cambridge, ON'},
'1519623':{'en': 'Cambridge, ON'},
'1412661':{'en': 'Pittsburgh, PA'},
'1423893':{'en': 'Chattanooga, TN'},
'1412665':{'en': 'Pittsburgh, PA'},
'1412664':{'en': 'McKeesport, PA'},
'1423894':{'en': 'Chattanooga, TN'},
'1423727':{'en': 'Mountain City, TN'},
'1412885':{'en': 'Pittsburgh, PA'},
'1412884':{'en': 'Pittsburgh, PA'},
'1418247':{'en': 'L\'Islet, QC'},
'1423899':{'en': 'Chattanooga, TN'},
'1412881':{'en': 'Pittsburgh, PA'},
'1415362':{'en': 'San Francisco, CA'},
'1585392':{'en': 'Hilton, NY'},
'1563326':{'en': 'Davenport, IA'},
'1514658':{'en': 'Montreal, QC'},
'1605772':{'en': 'Howard, SD'},
'1605775':{'en': 'Burke, SD'},
'1573996':{'en': 'Doniphan, MO'},
'1515832':{'en': 'Webster City, IA'},
'1607563':{'en': 'Sidney, NY'},
'1450755':{'en': 'Joliette, QC'},
'1450754':{'en': 'Crabtree, QC'},
'1450753':{'en': 'Joliette, QC'},
'1450752':{'en': 'Joliette, QC'},
'1515386':{'en': 'Jefferson, IA'},
'1603666':{'en': 'Manchester, NH'},
'1504254':{'en': 'New Orleans, LA'},
'1603668':{'en': 'Manchester, NH'},
'1603887':{'en': 'Chester, NH'},
'1603886':{'en': 'Nashua, NH'},
'1603881':{'en': 'Nashua, NH'},
'1603880':{'en': 'Nashua, NH'},
'1450759':{'en': 'Joliette, QC'},
'1603882':{'en': 'Nashua, NH'},
'1508926':{'en': 'Worcester, MA'},
'1502367':{'en': 'Louisville, KY'},
'1502364':{'en': 'Louisville, KY'},
'1502365':{'en': 'Louisville, KY'},
'1512389':{'en': 'Austin, TX'},
'1512388':{'en': 'Round Rock, TX'},
'1502361':{'en': 'Louisville, KY'},
'1512385':{'en': 'Austin, TX'},
'1441292':{'en': 'Hamilton'},
'1512386':{'en': 'Austin, TX'},
'1512380':{'en': 'Austin, TX'},
'1512383':{'en': 'Austin, TX'},
'1512382':{'en': 'Austin, TX'},
'1435615':{'en': 'Park City, UT'},
'1416944':{'en': 'Toronto, ON'},
'1615463':{'en': 'Nashville, TN'},
'1504780':{'en': 'Metairie, LA'},
'1519541':{'en': 'Sarnia, ON'},
'1610948':{'en': 'Royersford, PA'},
'1540375':{'en': 'Salem, VA'},
'1540374':{'en': 'Fredericksburg, VA'},
'1540373':{'en': 'Fredericksburg, VA'},
'1540372':{'en': 'Fredericksburg, VA'},
'1540371':{'en': 'Fredericksburg, VA'},
'1540370':{'en': 'Fredericksburg, VA'},
'1501552':{'en': 'Little Rock, AR'},
'1501556':{'en': 'Rose Bud, AR'},
'1520466':{'en': 'Eloy, AZ'},
'1612767':{'en': 'Minneapolis, MN'},
'1506783':{'en': 'Petit Rocher, NB'},
'1573374':{'en': 'Sunrise Beach, MO'},
'1573377':{'en': 'Stover, MO'},
'1414546':{'en': 'Milwaukee, WI'},
'1506789':{'en': 'Campbellton, NB'},
'1414545':{'en': 'Milwaukee, WI'},
'1414543':{'en': 'Milwaukee, WI'},
'1414540':{'en': 'Milwaukee, WI'},
'1414541':{'en': 'Milwaukee, WI'},
'1608935':{'en': 'Dodgeville, WI'},
'1520647':{'en': 'Tucson, AZ'},
'1602395':{'en': 'Phoenix, AZ'},
'1608930':{'en': 'Dodgeville, WI'},
'1515523':{'en': 'Stuart, IA'},
'1608938':{'en': 'Monticello, WI'},
'1520648':{'en': 'Green Valley, AZ'},
'1615683':{'en': 'Gordonsville, TN'},
'1574970':{'en': 'Elkhart, IN'},
'1580351':{'en': 'Lawton, OK'},
'1608648':{'en': 'De Soto, WI'},
'1419673':{'en': 'Kenton, OH'},
'1425828':{'en': 'Kirkland, WA'},
'1580353':{'en': 'Lawton, OK'},
'1419675':{'en': 'Kenton, OH'},
'1419674':{'en': 'Kenton, OH'},
'1425821':{'en': 'Kirkland, WA'},
'1425820':{'en': 'Kirkland, WA'},
'1425823':{'en': 'Kirkland, WA'},
'1419678':{'en': 'Coldwater, OH'},
'1425825':{'en': 'Kirkland, WA'},
'1425827':{'en': 'Kirkland, WA'},
'1503413':{'en': 'Portland, OR'},
'1503418':{'en': 'Portland, OR'},
'1507255':{'en': 'Rochester, MN'},
'1507526':{'en': 'Blue Earth, MN'},
'1507524':{'en': 'Mapleton, MN'},
'1507523':{'en': 'Lewiston, MN'},
'1610655':{'en': 'Reading, PA'},
'1614487':{'en': 'Columbus, OH'},
'1507252':{'en': 'Rochester, MN'},
'1510923':{'en': 'Oakland, CA'},
'1510922':{'en': 'Oakland, CA'},
'1413642':{'en': 'Westfield, MA'},
'1480905':{'en': 'Scottsdale, AZ'},
'1613652':{'en': 'Iroquois, ON'},
'1613659':{'en': 'Lansdowne, ON'},
'1617355':{'en': 'Boston, MA'},
'1610891':{'en': 'Media, PA'},
'1434636':{'en': 'Bracey, VA'},
'1434634':{'en': 'Emporia, VA'},
'1617353':{'en': 'Boston, MA'},
'1562997':{'en': 'Long Beach, CA'},
'1410629':{'en': 'Berlin, MD'},
'1410628':{'en': 'Cockeysville, MD'},
'1503574':{'en': 'Beaverton, OR'},
'1410620':{'en': 'Elkton, MD'},
'1503570':{'en': 'Wilsonville, OR'},
'1410626':{'en': 'Annapolis, MD'},
'1410625':{'en': 'Baltimore, MD'},
'1409770':{'en': 'Galveston, TX'},
'1615730':{'en': 'Nashville, TN'},
'1417934':{'en': 'Mountain View, MO'},
'1417935':{'en': 'Seymour, MO'},
'1417932':{'en': 'Summersville, MO'},
'1605428':{'en': 'Dell Rapids, SD'},
'1434946':{'en': 'Amherst, VA'},
'1434947':{'en': 'Lynchburg, VA'},
'1616887':{'en': 'Sparta, MI'},
'1616885':{'en': 'Grand Rapids, MI'},
'1602285':{'en': 'Phoenix, AZ'},
'1559741':{'en': 'Visalia, CA'},
'1580482':{'en': 'Altus, OK'},
'1580338':{'en': 'Guymon, OK'},
'1580336':{'en': 'Perry, OK'},
'1580335':{'en': 'Frederick, OK'},
'1580332':{'en': 'Ada, OK'},
'1575758':{'en': 'Taos, NM'},
'1575754':{'en': 'Red River, NM'},
'1575756':{'en': 'Chama, NM'},
'1575751':{'en': 'Taos, NM'},
'1607674':{'en': 'Sherburne, NY'},
'1570501':{'en': 'Hazleton, PA'},
'1513367':{'en': 'Harrison, OH'},
'1513360':{'en': 'Monroe, OH'},
'1501318':{'en': 'Hot Springs, AR'},
'1501316':{'en': 'Benton, AR'},
'1501315':{'en': 'Benton, AR'},
'1501312':{'en': 'Little Rock, AR'},
'1510549':{'en': 'Berkeley, CA'},
'1510548':{'en': 'Berkeley, CA'},
'1517265':{'en': 'Adrian, MI'},
'1517264':{'en': 'Adrian, MI'},
'1510547':{'en': 'Oakland, CA'},
'1479571':{'en': 'Fayetteville, AR'},
'1510540':{'en': 'Berkeley, CA'},
'1517263':{'en': 'Adrian, MI'},
'1479575':{'en': 'Fayetteville, AR'},
'1616225':{'en': 'Greenville, MI'},
'1450358':{'en': 'Saint-Jean-sur-Richelieu, QC'},
'1580661':{'en': 'Thomas, OK'},
'1616222':{'en': 'Grand Rapids, MI'},
'1615735':{'en': 'Carthage, TN'},
'1562929':{'en': 'Norwalk, CA'},
'1514461':{'en': 'Montreal, QC'},
'1478225':{'en': 'Warner Robins, GA'},
'1603262':{'en': 'Merrimack, NH'},
'1530722':{'en': 'Redding, CA'},
'1450438':{'en': u('Saint-J\u00e9r\u00f4me, QC')},
'1450439':{'en': 'Saint-Lin-Laurentides, QC'},
'1450928':{'en': 'Longueuil, QC'},
'1450929':{'en': 'Varennes, QC'},
'1606451':{'en': 'Somerset, KY'},
'1450432':{'en': u('Saint-J\u00e9r\u00f4me, QC')},
'1450926':{'en': 'Saint-Hubert, QC'},
'1450431':{'en': u('Saint-J\u00e9r\u00f4me, QC')},
'1450436':{'en': u('Saint-J\u00e9r\u00f4me, QC')},
'1450922':{'en': 'Sainte-Julie, QC'},
'1614253':{'en': 'Columbus, OH'},
'1610625':{'en': 'Bethlehem, PA'},
'1450692':{'en': u('Ch\u00e2teauguay, QC')},
'1450691':{'en': u('Ch\u00e2teauguay, QC')},
'1450698':{'en': u('Ch\u00e2teauguay, QC')},
'1450699':{'en': u('Ch\u00e2teauguay, QC')},
'1517841':{'en': 'Jackson, MI'},
'1517849':{'en': 'Jonesville, MI'},
'1519449':{'en': 'Burford, ON'},
'1519448':{'en': 'St George Brant, ON'},
'1519445':{'en': 'Ohsweken, ON'},
'1519443':{'en': 'Waterford, ON'},
'1519442':{'en': 'Paris, ON'},
'1419383':{'en': 'Toledo, OH'},
'1419382':{'en': 'Toledo, OH'},
'1419381':{'en': 'Toledo, OH'},
'1419380':{'en': 'Toledo, OH'},
'1419385':{'en': 'Toledo, OH'},
'1416572':{'en': 'Toronto, ON'},
'1561488':{'en': 'Boca Raton, FL'},
'1419389':{'en': 'Toledo, OH'},
'1608238':{'en': 'Madison, WI'},
'1417336':{'en': 'Branson, MO'},
'1608233':{'en': 'Madison, WI'},
'1608232':{'en': 'Madison, WI'},
'1515733':{'en': 'Story City, IA'},
'1520876':{'en': 'Casa Grande, AZ'},
'1520877':{'en': 'Tucson, AZ'},
'1520874':{'en': 'Tucson, AZ'},
'1519669':{'en': 'Elmira, ON'},
'1519668':{'en': 'London, ON'},
'1508559':{'en': 'Brockton, MA'},
'1519663':{'en': 'London, ON'},
'1418968':{'en': 'Sept-Iles, QC'},
'1519661':{'en': 'London, ON'},
'1519660':{'en': 'London, ON'},
'1508553':{'en': 'Franklin, MA'},
'1519666':{'en': 'Ilderton, ON'},
'1519664':{'en': 'St. Jacobs, ON'},
'1615859':{'en': 'Goodlettsville, TN'},
'1504443':{'en': 'Kenner, LA'},
'1615851':{'en': 'Goodlettsville, TN'},
'1615855':{'en': 'Goodlettsville, TN'},
'1614279':{'en': 'Columbus, OH'},
'1609492':{'en': 'Beach Haven, NJ'},
'1418380':{'en': 'Quebec City, QC'},
'1418385':{'en': u('Grande-Rivi\u00e8re, QC')},
'1418386':{'en': 'Sainte-Marie, QC'},
'1418387':{'en': 'Sainte-Marie, QC'},
'1614272':{'en': 'Columbus, OH'},
'1418962':{'en': 'Sept-Iles, QC'},
'1559924':{'en': 'Lemoore, CA'},
'1559925':{'en': 'Lemoore, CA'},
'1615206':{'en': 'Gallatin, TN'},
'1614276':{'en': 'Columbus, OH'},
'1614277':{'en': 'Grove City, OH'},
'1614274':{'en': 'Columbus, OH'},
'1604938':{'en': 'Whistler, BC'},
'1604939':{'en': 'Coquitlam, BC'},
'1541988':{'en': 'Springfield, OR'},
'1604930':{'en': 'Surrey, BC'},
'1604931':{'en': 'Coquitlam, BC'},
'1604932':{'en': 'Whistler, BC'},
'1604935':{'en': 'Whistler, BC'},
'1604936':{'en': 'Coquitlam, BC'},
'1604937':{'en': 'Coquitlam, BC'},
'1608392':{'en': 'La Crosse, WI'},
'1606549':{'en': 'Williamsburg, KY'},
'1606546':{'en': 'Barbourville, KY'},
'1606545':{'en': 'Barbourville, KY'},
'1423288':{'en': 'Kingsport, TN'},
'1423286':{'en': 'Oneida, TN'},
'1423283':{'en': 'Johnson City, TN'},
'1423282':{'en': 'Johnson City, TN'},
'1540586':{'en': 'Bedford, VA'},
'1540587':{'en': 'Bedford, VA'},
'1540582':{'en': 'Spotsylvania, VA'},
'1506336':{'en': 'Shippagan, NB'},
'1504861':{'en': 'New Orleans, LA'},
'1606768':{'en': 'Frenchburg, KY'},
'1440774':{'en': 'Oberlin, OH'},
'1504866':{'en': 'New Orleans, LA'},
'1504865':{'en': 'New Orleans, LA'},
'1440777':{'en': 'North Olmsted, OH'},
'1440779':{'en': 'North Olmsted, OH'},
'1480596':{'en': 'Scottsdale, AZ'},
'1610518':{'en': 'Downingtown, PA'},
'1417890':{'en': 'Springfield, MO'},
'1417895':{'en': 'Springfield, MO'},
'1417548':{'en': 'Sarcoxie, MO'},
'1417546':{'en': 'Forsyth, MO'},
'1570963':{'en': 'Scranton, PA'},
'1613798':{'en': 'Ottawa, ON'},
'1540639':{'en': 'Radford, VA'},
'1540636':{'en': 'Front Royal, VA'},
'1540635':{'en': 'Front Royal, VA'},
'1540633':{'en': 'Radford, VA'},
'1540631':{'en': 'Front Royal, VA'},
'1610935':{'en': 'Phoenixville, PA'},
'1434797':{'en': 'Danville, VA'},
'1502549':{'en': 'New Haven, KY'},
'1434791':{'en': 'Danville, VA'},
'1434793':{'en': 'Danville, VA'},
'1434792':{'en': 'Danville, VA'},
'1502543':{'en': 'Shepherdsville, KY'},
'1502540':{'en': 'Louisville, KY'},
'1434799':{'en': 'Danville, VA'},
'1570265':{'en': 'Towanda, PA'},
'1615385':{'en': 'Nashville, TN'},
'1561368':{'en': 'Boca Raton, FL'},
'1415541':{'en': 'San Francisco, CA'},
'1425614':{'en': 'Bellevue, WA'},
'1570268':{'en': 'Towanda, PA'},
'1435637':{'en': 'Price, UT'},
'1612225':{'en': 'Minneapolis, MN'},
'1610892':{'en': 'Media, PA'},
'1510489':{'en': 'Union City, CA'},
'1434572':{'en': 'South Boston, VA'},
'1434575':{'en': 'South Boston, VA'},
'1510481':{'en': 'San Leandro, CA'},
'1510482':{'en': 'Oakland, CA'},
'1510483':{'en': 'San Leandro, CA'},
'1510486':{'en': 'Berkeley, CA'},
'1510487':{'en': 'Union City, CA'},
'1601679':{'en': 'Meridian, MS'},
'1516674':{'en': 'Glen Cove, NY'},
'1513281':{'en': 'Cincinnati, OH'},
'1516676':{'en': 'Glen Cove, NY'},
'1516671':{'en': 'Glen Cove, NY'},
'1513285':{'en': 'Hamilton, OH'},
'1540961':{'en': 'Blacksburg, VA'},
'1616942':{'en': 'Grand Rapids, MI'},
'1616940':{'en': 'Grand Rapids, MI'},
'1479631':{'en': 'Rogers, AR'},
'1510733':{'en': 'Hayward, CA'},
'1479633':{'en': 'Rogers, AR'},
'1479632':{'en': 'Alma, AR'},
'1479637':{'en': 'Waldron, AR'},
'1479636':{'en': 'Rogers, AR'},
'1510739':{'en': 'Fremont, CA'},
'1519850':{'en': 'London, ON'},
'1519853':{'en': 'Acton, ON'},
'1425289':{'en': 'Bellevue, WA'},
'1519855':{'en': 'Hillsburgh, ON'},
'1519856':{'en': 'Rockwood, ON'},
'1541210':{'en': 'Medford, OR'},
'1519858':{'en': 'London, ON'},
'1507886':{'en': 'Harmony, MN'},
'1585658':{'en': 'Mount Morris, NY'},
'1425282':{'en': 'Renton, WA'},
'1608355':{'en': 'Baraboo, WI'},
'1608356':{'en': 'Baraboo, WI'},
'1413731':{'en': 'Springfield, MA'},
'1413732':{'en': 'Springfield, MA'},
'1413733':{'en': 'Springfield, MA'},
'1413734':{'en': 'Springfield, MA'},
'1413736':{'en': 'Springfield, MA'},
'1413737':{'en': 'Springfield, MA'},
'1413739':{'en': 'Springfield, MA'},
'1608824':{'en': 'Madison, WI'},
'1604222':{'en': 'Vancouver, BC'},
'1575257':{'en': 'Ruidoso, NM'},
'1610932':{'en': 'Oxford, PA'},
'1575258':{'en': 'Ruidoso, NM'},
'1513825':{'en': 'Cincinnati, OH'},
'1608829':{'en': 'Madison, WI'},
'1513821':{'en': 'Cincinnati, OH'},
'1604215':{'en': 'Vancouver, BC'},
'1513829':{'en': 'Fairfield, OH'},
'1518456':{'en': 'Albany, NY'},
'1607762':{'en': 'Binghamton, NY'},
'1607763':{'en': 'Johnson City, NY'},
'1518453':{'en': 'Albany, NY'},
'1518452':{'en': 'Albany, NY'},
'1450592':{'en': u('Saint-J\u00e9r\u00f4me, QC')},
'1450598':{'en': 'Saint-Eustache, QC'},
'1518459':{'en': 'Albany, NY'},
'1480951':{'en': 'Scottsdale, AZ'},
'1604581':{'en': 'Surrey, BC'},
'1519275':{'en': 'Stratford, ON'},
'1604583':{'en': 'Surrey, BC'},
'1604582':{'en': 'Surrey, BC'},
'1512419':{'en': 'Austin, TX'},
'1512418':{'en': 'Austin, TX'},
'1519272':{'en': 'Stratford, ON'},
'1519273':{'en': 'Stratford, ON'},
'1423702':{'en': 'Chattanooga, TN'},
'1512414':{'en': 'Austin, TX'},
'1609607':{'en': 'Barnegat Township, NJ'},
'1512416':{'en': 'Austin, TX'},
'1585235':{'en': 'Rochester, NY'},
'1585234':{'en': 'Rochester, NY'},
'1585237':{'en': 'Perry, NY'},
'1520324':{'en': 'Tucson, AZ'},
'1504277':{'en': 'Chalmette, LA'},
'1530550':{'en': 'Truckee, CA'},
'1504271':{'en': 'Chalmette, LA'},
'1605722':{'en': 'Spearfish, SD'},
'1605720':{'en': 'Sturgis, SD'},
'1605721':{'en': 'Rapid City, SD'},
'1504278':{'en': 'Chalmette, LA'},
'1504279':{'en': 'Chalmette, LA'},
'1509543':{'en': 'Pasco, WA'},
'1509542':{'en': 'Pasco, WA'},
'1450773':{'en': 'Saint-Hyacinthe, QC'},
'1450772':{'en': 'Saint-Pie, QC'},
'1509547':{'en': 'Pasco, WA'},
'1509546':{'en': 'Pasco, WA'},
'1450777':{'en': 'Granby, QC'},
'1509544':{'en': 'Pasco, WA'},
'1450778':{'en': 'Saint-Hyacinthe, QC'},
'1603601':{'en': 'Hampton, NH'},
'1509548':{'en': 'Leavenworth, WA'},
'1603606':{'en': 'Manchester, NH'},
'1508764':{'en': 'Southbridge, MA'},
'1508941':{'en': 'Brockton, MA'},
'1508943':{'en': 'Webster, MA'},
'1508945':{'en': 'Chatham, MA'},
'1508946':{'en': 'Middleborough, MA'},
'1508947':{'en': 'Middleborough, MA'},
'1508949':{'en': 'Webster, MA'},
'1510307':{'en': 'Richmond, CA'},
'1607756':{'en': 'Cortland, NY'},
'1432426':{'en': 'Fort Davis, TX'},
'1501570':{'en': 'Little Rock, AR'},
'1615449':{'en': 'Lebanon, TN'},
'1615338':{'en': 'Hendersonville, TN'},
'1519674':{'en': 'Ridgetown, ON'},
'1416968':{'en': 'Toronto, ON'},
'1520404':{'en': 'Tucson, AZ'},
'1419246':{'en': 'Toledo, OH'},
'1416967':{'en': 'Toronto, ON'},
'1419244':{'en': 'Toledo, OH'},
'1419245':{'en': 'Toledo, OH'},
'1416962':{'en': 'Toronto, ON'},
'1416963':{'en': 'Toronto, ON'},
'1416960':{'en': 'Toronto, ON'},
'1419241':{'en': 'Toledo, OH'},
'1610939':{'en': 'Reading, PA'},
'1607652':{'en': 'Stamford, NY'},
'1559268':{'en': 'Fresno, CA'},
'1559591':{'en': 'Dinuba, CA'},
'1559261':{'en': 'Fresno, CA'},
'1559592':{'en': 'Exeter, CA'},
'1559595':{'en': 'Dinuba, CA'},
'1559266':{'en': 'Fresno, CA'},
'1559264':{'en': 'Fresno, CA'},
'1573317':{'en': 'Camdenton, MO'},
'1414527':{'en': 'Milwaukee, WI'},
'1608637':{'en': 'Viroqua, WI'},
'1562429':{'en': 'Long Beach, CA'},
'1519936':{'en': 'London, ON'},
'1562427':{'en': 'Long Beach, CA'},
'1562426':{'en': 'Long Beach, CA'},
'1562425':{'en': 'Long Beach, CA'},
'1562424':{'en': 'Long Beach, CA'},
'1562423':{'en': 'Long Beach, CA'},
'1562422':{'en': 'Long Beach, CA'},
'1562421':{'en': 'Long Beach, CA'},
'1562420':{'en': 'Long Beach, CA'},
'1601605':{'en': 'Ridgeland, MS'},
'1605987':{'en': 'Canton, SD'},
'1561338':{'en': 'Boca Raton, FL'},
'1519934':{'en': 'Tara, ON'},
'1601353':{'en': 'Jackson, MS'},
'1601352':{'en': 'Jackson, MS'},
'1561998':{'en': 'Boca Raton, FL'},
'1561999':{'en': 'Boca Raton, FL'},
'1561996':{'en': 'Belle Glade, FL'},
'1561997':{'en': 'Boca Raton, FL'},
'1561330':{'en': 'Delray Beach, FL'},
'1561995':{'en': 'Boca Raton, FL'},
'1561992':{'en': 'Belle Glade, FL'},
'1601359':{'en': 'Jackson, MS'},
'1504827':{'en': 'New Orleans, LA'},
'1423451':{'en': 'Soddy-Daisy, TN'},
'1419659':{'en': 'Columbus Grove, OH'},
'1513876':{'en': 'Felicity, OH'},
'1480551':{'en': 'Scottsdale, AZ'},
'1610478':{'en': 'Reading, PA'},
'1519422':{'en': 'Sauble Beach, ON'},
'1613233':{'en': 'Ottawa, ON'},
'1480924':{'en': 'Mesa, AZ'},
'1480921':{'en': 'Tempe, AZ'},
'1503434':{'en': 'McMinnville, OR'},
'1480922':{'en': 'Scottsdale, AZ'},
'1614853':{'en': 'Columbus, OH'},
'1480556':{'en': 'Scottsdale, AZ'},
'1480557':{'en': 'Tempe, AZ'},
'1613232':{'en': 'Ottawa, ON'},
'1510786':{'en': 'Hayward, CA'},
'1503585':{'en': 'Salem, OR'},
'1613321':{'en': 'Ottawa, ON'},
'1605472':{'en': 'Redfield, SD'},
'1613634':{'en': 'Kingston, ON'},
'1410605':{'en': 'Baltimore, MD'},
'1410604':{'en': 'Stevensville, MD'},
'1410355':{'en': 'Baltimore, MD'},
'1410354':{'en': 'Baltimore, MD'},
'1410601':{'en': 'Baltimore, MD'},
'1410352':{'en': 'Bishopville, MD'},
'1410602':{'en': 'Pikesville, MD'},
'1601736':{'en': 'Columbia, MS'},
'1410358':{'en': 'Baltimore, MD'},
'1409751':{'en': 'Lumberton, TX'},
'1410673':{'en': 'Preston, MD'},
'1409755':{'en': 'Lumberton, TX'},
'1574335':{'en': 'Mishawaka, IN'},
'1614486':{'en': 'Columbus, OH'},
'1516883':{'en': 'Port Washington, NY'},
'1606376':{'en': 'Whitley City, KY'},
'1503885':{'en': 'Tualatin, OR'},
'1516889':{'en': 'Long Beach, NY'},
'1606379':{'en': 'Eubank, KY'},
'1418838':{'en': 'Levis, QC'},
'1418529':{'en': 'Quebec City, QC'},
'1418832':{'en': 'Charny, QC'},
'1418525':{'en': 'Quebec City, QC'},
'1418527':{'en': 'Quebec City, QC'},
'1415800':{'en': 'San Francisco, CA'},
'1418837':{'en': 'Levis, QC'},
'1418522':{'en': 'Quebec City, QC'},
'1418523':{'en': 'Quebec City, QC'},
'1617376':{'en': 'Quincy, MA'},
'1617375':{'en': 'Boston, MA'},
'1617371':{'en': 'Boston, MA'},
'1580310':{'en': 'Ada, OK'},
'1601928':{'en': 'Wiggins, MS'},
'1570523':{'en': 'Lewisburg, PA'},
'1570522':{'en': 'Lewisburg, PA'},
'1570524':{'en': 'Lewisburg, PA'},
'1508767':{'en': 'Worcester, MA'},
'1435563':{'en': 'Smithfield, UT'},
'1614764':{'en': 'Dublin, OH'},
'1513346':{'en': 'Cincinnati, OH'},
'1513347':{'en': 'Cincinnati, OH'},
'1502933':{'en': 'Louisville, KY'},
'1501379':{'en': 'Little Rock, AR'},
'1502937':{'en': 'Louisville, KY'},
'1507433':{'en': 'Austin, MN'},
'1502935':{'en': 'Louisville, KY'},
'1501370':{'en': 'Little Rock, AR'},
'1501371':{'en': 'Little Rock, AR'},
'1501372':{'en': 'Little Rock, AR'},
'1518731':{'en': 'Coxsackie, NY'},
'1518736':{'en': 'Johnstown, NY'},
'1501375':{'en': 'Little Rock, AR'},
'1501376':{'en': 'Little Rock, AR'},
'1434964':{'en': 'Charlottesville, VA'},
'1434969':{'en': 'Buckingham, VA'},
'1614552':{'en': 'Columbus, OH'},
'1518597':{'en': 'Crown Point, NY'},
'1603472':{'en': 'Bedford, NH'},
'1603474':{'en': 'Seabrook, NH'},
'1615538':{'en': 'Franklin, TN'},
'1603476':{'en': 'Moultonborough, NH'},
'1530529':{'en': 'Red Bluff, CA'},
'1509226':{'en': 'Newman Lake, WA'},
'1509225':{'en': 'Yakima, WA'},
'1469752':{'en': 'Plano, TX'},
'1559864':{'en': 'Caruthers, CA'},
'1416777':{'en': 'Toronto, ON'},
'1416778':{'en': 'Toronto, ON'},
'1573379':{'en': 'Portageville, MO'},
'1603663':{'en': 'Manchester, NH'},
'1412471':{'en': 'Pittsburgh, PA'},
'1412472':{'en': 'Pittsburgh, PA'},
'1519461':{'en': 'Thorndale, ON'},
'1608743':{'en': 'Janesville, WI'},
'1608742':{'en': 'Portage, WI'},
'1607937':{'en': 'Corning, NY'},
'1607936':{'en': 'Corning, NY'},
'1607243':{'en': 'Dundee, NY'},
'1416599':{'en': 'Toronto, ON'},
'1416598':{'en': 'Toronto, ON'},
'1416597':{'en': 'Toronto, ON'},
'1416596':{'en': 'Toronto, ON'},
'1416595':{'en': 'Toronto, ON'},
'1416594':{'en': 'Toronto, ON'},
'1416593':{'en': 'Toronto, ON'},
'1563744':{'en': 'Farley, IA'},
'1416591':{'en': 'Toronto, ON'},
'1416590':{'en': 'North York, ON'},
'1509488':{'en': 'Othello, WA'},
'1509489':{'en': 'Spokane, WA'},
'1509486':{'en': 'Tonasket, WA'},
'1509487':{'en': 'Spokane, WA'},
'1509484':{'en': 'Spokane, WA'},
'1509482':{'en': 'Spokane, WA'},
'1509483':{'en': 'Spokane, WA'},
'1509953':{'en': 'Spokane, WA'},
'1519645':{'en': 'London, ON'},
'1519644':{'en': 'Belmont, ON'},
'1519641':{'en': 'London, ON'},
'1519642':{'en': 'London, ON'},
'1608837':{'en': 'Sun Prairie, WI'},
'1519649':{'en': 'London, ON'},
'1519648':{'en': 'Breslau, ON'},
'1602388':{'en': 'Phoenix, AZ'},
'1412299':{'en': 'Coraopolis, PA'},
'1506696':{'en': 'Saint John, NB'},
'1478864':{'en': 'Wrightsville, GA'},
'1478862':{'en': 'Butler, GA'},
'1512446':{'en': 'Rockdale, TX'},
'1573226':{'en': 'Eminence, MO'},
'1573556':{'en': 'Jefferson City, MO'},
'1573222':{'en': 'Puxico, MO'},
'1512447':{'en': 'Austin, TX'},
'1520232':{'en': 'Tucson, AZ'},
'1574834':{'en': 'North Webster, IN'},
'1418364':{'en': 'Carleton, QC'},
'1574523':{'en': 'Elkhart, IN'},
'1574522':{'en': 'Elkhart, IN'},
'1604913':{'en': 'West Vancouver, BC'},
'1503289':{'en': 'Portland, OR'},
'1415202':{'en': 'San Francisco, CA'},
'1614781':{'en': 'Columbus, OH'},
'1614784':{'en': 'Columbus, OH'},
'1412920':{'en': 'Pittsburgh, PA'},
'1434977':{'en': 'Charlottesville, VA'},
'1615833':{'en': 'Nashville, TN'},
'1615832':{'en': 'Nashville, TN'},
'1615831':{'en': 'Nashville, TN'},
'1615781':{'en': 'Nashville, TN'},
'1615783':{'en': 'Nashville, TN'},
'1503283':{'en': 'Portland, OR'},
'1615789':{'en': 'Charlotte, TN'},
'1503280':{'en': 'Portland, OR'},
'1570735':{'en': 'Nanticoke, PA'},
'1512445':{'en': 'Austin, TX'},
'1509625':{'en': 'Spokane, WA'},
'1480609':{'en': 'Scottsdale, AZ'},
'1480607':{'en': 'Scottsdale, AZ'},
'1512343':{'en': 'Austin, TX'},
'1559674':{'en': 'Madera, CA'},
'1559675':{'en': 'Madera, CA'},
'1503284':{'en': 'Portland, OR'},
'1559673':{'en': 'Madera, CA'},
'1415209':{'en': 'Novato, CA'},
'1601296':{'en': 'Hattiesburg, MS'},
'1508798':{'en': 'Worcester, MA'},
'1506357':{'en': 'Oromocto, NB'},
'1573782':{'en': 'Russellville, MO'},
'1520907':{'en': 'Tucson, AZ'},
'1432218':{'en': 'Midland, TX'},
'1512443':{'en': 'Austin, TX'},
'1520903':{'en': 'Tucson, AZ'},
'1610530':{'en': 'Allentown, PA'},
'1435792':{'en': 'Logan, UT'},
'1435797':{'en': 'Logan, UT'},
'1504842':{'en': 'Jefferson, LA'},
'1604251':{'en': 'Vancouver, BC'},
'1580782':{'en': 'Mangum, OK'},
'1530886':{'en': 'Auburn, CA'},
'1530887':{'en': 'Auburn, CA'},
'1530885':{'en': 'Auburn, CA'},
'1573438':{'en': 'Potosi, MO'},
'1573436':{'en': 'Potosi, MO'},
'1573437':{'en': 'Owensville, MO'},
'1530888':{'en': 'Auburn, CA'},
'1530889':{'en': 'Auburn, CA'},
'1540658':{'en': 'Stafford, VA'},
'1410297':{'en': 'Aberdeen, MD'},
'1410295':{'en': 'Annapolis, MD'},
'1615343':{'en': 'Nashville, TN'},
'1410290':{'en': 'Columbia, MD'},
'1540652':{'en': 'Shenandoah, VA'},
'1540656':{'en': 'Fredericksburg, VA'},
'1540657':{'en': 'Stafford, VA'},
'1417745':{'en': 'Hermitage, MO'},
'1417741':{'en': 'Hartville, MO'},
'1417742':{'en': 'Willard, MO'},
'1419822':{'en': 'Delta, OH'},
'1505466':{'en': 'Santa Fe, NM'},
'1505467':{'en': 'Santa Fe, NM'},
'1419826':{'en': 'Swanton, OH'},
'1419824':{'en': 'Sylvania, OH'},
'1505463':{'en': 'Albuquerque, NM'},
'1570208':{'en': 'Wilkes-Barre, PA'},
'1606743':{'en': 'West Liberty, KY'},
'1479928':{'en': 'Mansfield, AR'},
'1479925':{'en': 'Rogers, AR'},
'1479927':{'en': 'Springdale, AR'},
'1416964':{'en': 'Toronto, ON'},
'1570966':{'en': 'Mifflinburg, PA'},
'1434517':{'en': 'South Boston, VA'},
'1425513':{'en': 'Everett, WA'},
'1610454':{'en': 'Collegeville, PA'},
'1602248':{'en': 'Phoenix, AZ'},
'1602249':{'en': 'Phoenix, AZ'},
'1519756':{'en': 'Brantford, ON'},
'1602244':{'en': 'Phoenix, AZ'},
'1602246':{'en': 'Phoenix, AZ'},
'1602240':{'en': 'Phoenix, AZ'},
'1602241':{'en': 'Phoenix, AZ'},
'1602242':{'en': 'Phoenix, AZ'},
'1602243':{'en': 'Phoenix, AZ'},
'1604263':{'en': 'Vancouver, BC'},
'1520':{'en': 'Arizona'},
'1604264':{'en': 'Vancouver, BC'},
'1516694':{'en': 'Farmingdale, NY'},
'1516692':{'en': 'Woodbury, NY'},
'1604266':{'en': 'Vancouver, BC'},
'1607772':{'en': 'Binghamton, NY'},
'1604267':{'en': 'Vancouver, BC'},
'1575492':{'en': 'Hobbs, NM'},
'1585262':{'en': 'Rochester, NY'},
'1519875':{'en': 'Langton, ON'},
'1518695':{'en': 'Schuylerville, NY'},
'1518694':{'en': 'Albany, NY'},
'1586759':{'en': 'Warren, MI'},
'1518692':{'en': 'Greenwich, NY'},
'1586757':{'en': 'Warren, MI'},
'1413245':{'en': 'Brimfield, MA'},
'1586755':{'en': 'Warren, MI'},
'1413247':{'en': 'Hatfield, MA'},
'1586751':{'en': 'Warren, MI'},
'1413243':{'en': 'Lee, MA'},
'1530271':{'en': 'Grass Valley, CA'},
'1605685':{'en': 'Martin, SD'},
'1514345':{'en': 'Montreal, QC'},
'1514342':{'en': 'Montreal, QC'},
'1514340':{'en': 'Montreal, QC'},
'1612977':{'en': 'Minneapolis, MN'},
'1602808':{'en': 'Phoenix, AZ'},
'1607748':{'en': 'Endicott, NY'},
'1518472':{'en': 'Albany, NY'},
'1518474':{'en': 'Albany, NY'},
'1518478':{'en': 'Delmar, NY'},
'1607746':{'en': 'Delhi, NY'},
'1603595':{'en': 'Nashua, NH'},
'1603594':{'en': 'Nashua, NH'},
'1605328':{'en': 'Sioux Falls, SD'},
'1519258':{'en': 'Windsor, ON'},
'1519256':{'en': 'Windsor, ON'},
'1519254':{'en': 'Windsor, ON'},
'1519255':{'en': 'Windsor, ON'},
'1519252':{'en': 'Windsor, ON'},
'1519253':{'en': 'Windsor, ON'},
'1519250':{'en': 'Windsor, ON'},
'1519251':{'en': 'Windsor, ON'},
'1514695':{'en': 'Pointe-Claire, QC'},
'1514694':{'en': 'Pointe-Claire, QC'},
'1514697':{'en': 'Pointe-Claire, QC'},
'1603625':{'en': 'Manchester, NH'},
'1603624':{'en': 'Manchester, NH'},
'1603627':{'en': 'Manchester, NH'},
'1563359':{'en': 'Davenport, IA'},
'1603621':{'en': 'Manchester, NH'},
'1603623':{'en': 'Manchester, NH'},
'1603622':{'en': 'Manchester, NH'},
'1504218':{'en': 'New Orleans, LA'},
'1530577':{'en': 'South Lake Tahoe, CA'},
'1603629':{'en': 'Manchester, NH'},
'1530573':{'en': 'South Lake Tahoe, CA'},
'1563355':{'en': 'Bettendorf, IA'},
'1505920':{'en': 'Santa Fe, NM'},
'1505922':{'en': 'Albuquerque, NM'},
'1604233':{'en': 'Richmond, BC'},
'1508748':{'en': 'Marion, MA'},
'1508746':{'en': 'Plymouth, MA'},
'1508747':{'en': 'Plymouth, MA'},
'1508961':{'en': 'New Bedford, MA'},
'1508966':{'en': 'Bellingham, MA'},
'1502327':{'en': 'Louisville, KY'},
'1540332':{'en': 'Staunton, VA'},
'1615312':{'en': 'Nashville, TN'},
'1615313':{'en': 'Nashville, TN'},
'1540334':{'en': 'Boones Mill, VA'},
'1540338':{'en': 'Purcellville, VA'},
'1601991':{'en': 'Ridgeland, MS'},
'1419228':{'en': 'Lima, OH'},
'1419229':{'en': 'Lima, OH'},
'1586979':{'en': 'Sterling Heights, MI'},
'1586978':{'en': 'Sterling Heights, MI'},
'1419221':{'en': 'Lima, OH'},
'1419222':{'en': 'Lima, OH'},
'1419223':{'en': 'Lima, OH'},
'1419224':{'en': 'Lima, OH'},
'1419225':{'en': 'Lima, OH'},
'1419226':{'en': 'Lima, OH'},
'1419227':{'en': 'Lima, OH'},
'1423857':{'en': 'Kingsport, TN'},
'1423854':{'en': 'Johnson City, TN'},
'1423855':{'en': 'Chattanooga, TN'},
'1412621':{'en': 'Pittsburgh, PA'},
'1585256':{'en': 'Rochester, NY'},
'1412623':{'en': 'Pittsburgh, PA'},
'1412622':{'en': 'Pittsburgh, PA'},
'1585258':{'en': 'Rochester, NY'},
'1573335':{'en': 'Cape Girardeau, MO'},
'1573334':{'en': 'Cape Girardeau, MO'},
'1573336':{'en': 'St. Robert, MO'},
'1573331':{'en': 'Cape Girardeau, MO'},
'1573333':{'en': 'Caruthersville, MO'},
'1573332':{'en': 'Cape Girardeau, MO'},
'1573339':{'en': 'Cape Girardeau, MO'},
'1607239':{'en': 'Endicott, NY'},
'1540489':{'en': 'Rocky Mount, VA'},
'1613526':{'en': 'Ottawa, ON'},
'1540484':{'en': 'Rocky Mount, VA'},
'1613525':{'en': 'Alexandria, ON'},
'1540483':{'en': 'Rocky Mount, VA'},
'1613524':{'en': 'Saint Isidore, ON'},
'1410998':{'en': 'Owings Mills, MD'},
'1410995':{'en': 'Columbia, MD'},
'1410997':{'en': 'Columbia, MD'},
'1410996':{'en': 'Elkton, MD'},
'1410990':{'en': 'Annapolis, MD'},
'1410992':{'en': 'Columbia, MD'},
'1423581':{'en': 'Morristown, TN'},
'1607778':{'en': 'Binghamton, NY'},
'1423585':{'en': 'Morristown, TN'},
'1423586':{'en': 'Morristown, TN'},
'1423587':{'en': 'Morristown, TN'},
'1562401':{'en': 'Downey, CA'},
'1507744':{'en': 'Lonsdale, MN'},
'1607637':{'en': 'Hancock, NY'},
'1601371':{'en': 'Jackson, MS'},
'1601373':{'en': 'Jackson, MS'},
'1601372':{'en': 'Jackson, MS'},
'1425869':{'en': 'Redmond, WA'},
'1601376':{'en': 'Jackson, MS'},
'1425867':{'en': 'Redmond, WA'},
'1510777':{'en': 'Oakland, CA'},
'1505670':{'en': 'Santa Fe, NM'},
'1505672':{'en': 'Los Alamos, NM'},
'1503459':{'en': 'Portland, OR'},
'1503452':{'en': 'Portland, OR'},
'1559244':{'en': 'Fresno, CA'},
'1559243':{'en': 'Fresno, CA'},
'1507292':{'en': 'Rochester, MN'},
'1559248':{'en': 'Fresno, CA'},
'1520584':{'en': 'Tucson, AZ'},
'1574647':{'en': 'South Bend, IN'},
'1503534':{'en': 'Lake Oswego, OR'},
'1503535':{'en': 'Portland, OR'},
'1410377':{'en': 'Baltimore, MD'},
'1503537':{'en': 'Newberg, OR'},
'1503538':{'en': 'Newberg, OR'},
'1423323':{'en': 'Blountville, TN'},
'1603427':{'en': 'Portsmouth, NH'},
'1603424':{'en': 'Merrimack, NH'},
'1505272':{'en': 'Albuquerque, NM'},
'1415826':{'en': 'San Francisco, CA'},
'1415824':{'en': 'San Francisco, CA'},
'1415822':{'en': 'San Francisco, CA'},
'1516869':{'en': 'Manhasset, NY'},
'1415820':{'en': 'San Francisco, CA'},
'1415821':{'en': 'San Francisco, CA'},
'1606354':{'en': 'Pine Knot, KY'},
'1415829':{'en': 'San Francisco, CA'},
'1504988':{'en': 'New Orleans, LA'},
'1580371':{'en': 'Tishomingo, OK'},
'1609965':{'en': 'Egg Harbor City, NJ'},
'1609967':{'en': 'Avalon, NJ'},
'1613342':{'en': 'Brockville, ON'},
'1613347':{'en': 'Lancaster, ON'},
'1613345':{'en': 'Brockville, ON'},
'1605352':{'en': 'Huron, SD'},
'1513636':{'en': 'Cincinnati, OH'},
'1513631':{'en': 'Cincinnati, OH'},
'1605357':{'en': 'Sioux Falls, SD'},
'1501353':{'en': 'Little Rock, AR'},
'1501354':{'en': 'Morrilton, AR'},
'1435587':{'en': 'Monticello, UT'},
'1513321':{'en': 'Cincinnati, OH'},
'1417358':{'en': 'Carthage, MO'},
'1417359':{'en': 'Carthage, MO'},
'1509750':{'en': 'Moses Lake, WA'},
'1434984':{'en': 'Charlottesville, VA'},
'1434981':{'en': 'Charlottesville, VA'},
'1434982':{'en': 'Charlottesville, VA'},
'1434983':{'en': 'Dillwyn, VA'},
'1530763':{'en': 'Yuba City, CA'},
'1450229':{'en': u('Sainte-Ad\u00e8le, QC')},
'1450961':{'en': 'Terrebonne, QC'},
'1603458':{'en': 'Salem, NH'},
'1580994':{'en': 'Mooreland, OK'},
'1450964':{'en': 'Terrebonne, QC'},
'1450966':{'en': 'Mascouche, QC'},
'1450968':{'en': 'Terrebonne, QC'},
'1603456':{'en': 'Warner, NH'},
'1613967':{'en': 'Belleville, ON'},
'1613966':{'en': 'Belleville, ON'},
'1613965':{'en': 'Trenton, ON'},
'1613962':{'en': 'Belleville, ON'},
'1561712':{'en': 'West Palm Beach, FL'},
'1613969':{'en': 'Belleville, ON'},
'1613968':{'en': 'Belleville, ON'},
'1570542':{'en': 'Shickshinny, PA'},
'1570547':{'en': 'Montgomery, PA'},
'1570546':{'en': 'Muncy, PA'},
'1570544':{'en': 'Minersville, PA'},
'1416759':{'en': 'Scarborough, ON'},
'1604885':{'en': 'Sechelt, BC'},
'1416755':{'en': 'Scarborough, ON'},
'1416754':{'en': 'Scarborough, ON'},
'1416757':{'en': 'Scarborough, ON'},
'1416750':{'en': 'Scarborough, ON'},
'1416752':{'en': 'Scarborough, ON'},
'1510675':{'en': 'Union City, CA'},
'1607546':{'en': 'Burdett, NY'},
'1510670':{'en': 'Hayward, CA'},
'1607547':{'en': 'Cooperstown, NY'},
'1610398':{'en': 'Allentown, PA'},
'1434239':{'en': 'Lynchburg, VA'},
'1434237':{'en': 'Lynchburg, VA'},
'1412456':{'en': 'Pittsburgh, PA'},
'1571285':{'en': 'Woodbridge, VA'},
'1614342':{'en': 'Columbus, OH'},
'1602508':{'en': 'Phoenix, AZ'},
'1602506':{'en': 'Phoenix, AZ'},
'1602504':{'en': 'Phoenix, AZ'},
'1515953':{'en': 'Des Moines, IA'},
'1515955':{'en': 'Fort Dodge, IA'},
'1607264':{'en': 'Cherry Valley, NY'},
'1515957':{'en': 'Altoona, IA'},
'1607266':{'en': 'Ithaca, NY'},
'1608764':{'en': 'Deerfield, WI'},
'1608767':{'en': 'Black Earth, WI'},
'1530265':{'en': 'Nevada City, CA'},
'1604688':{'en': 'Vancouver, BC'},
'1508510':{'en': 'Brockton, MA'},
'1575682':{'en': 'Cloudcroft, NM'},
'1604682':{'en': 'Vancouver, BC'},
'1604683':{'en': 'Vancouver, BC'},
'1604681':{'en': 'Vancouver, BC'},
'1604687':{'en': 'Vancouver, BC'},
'1604684':{'en': 'Vancouver, BC'},
'1604685':{'en': 'Vancouver, BC'},
'1612340':{'en': 'Minneapolis, MN'},
'1530634':{'en': 'Beale AFB, CA'},
'1609695':{'en': 'Trenton, NJ'},
'1418349':{'en': u('M\u00e9tabetchouan-Lac-\u00e0-la-Croix, QC')},
'1604532':{'en': 'Langley, BC'},
'1412904':{'en': 'Pittsburgh, PA'},
'1415227':{'en': 'San Francisco, CA'},
'1415221':{'en': 'San Francisco, CA'},
'1415591':{'en': 'San Francisco, CA'},
'1604605':{'en': 'Vancouver, BC'},
'1512206':{'en': 'Austin, TX'},
'1432582':{'en': 'Odessa, TX'},
'1432580':{'en': 'Odessa, TX'},
'1432586':{'en': 'Kermit, TX'},
'1609698':{'en': 'Barnegat Township, NJ'},
'1510531':{'en': 'Oakland, CA'},
'1425394':{'en': 'Issaquah, WA'},
'1415439':{'en': 'San Francisco, CA'},
'1541517':{'en': 'Eugene, OR'},
'1610738':{'en': 'West Chester, PA'},
'1610734':{'en': 'Upper Darby, PA'},
'1559658':{'en': 'Oakhurst, CA'},
'1559659':{'en': 'Firebaugh, CA'},
'1559655':{'en': 'Mendota, CA'},
'1559651':{'en': 'Visalia, CA'},
'1506375':{'en': 'Hartland, NB'},
'1415431':{'en': 'San Francisco, CA'},
'1510533':{'en': 'Oakland, CA'},
'1613421':{'en': 'Ottawa, ON'},
'1412422':{'en': 'Pittsburgh, PA'},
'1520744':{'en': 'Tucson, AZ'},
'1520745':{'en': 'Tucson, AZ'},
'1520746':{'en': 'Tucson, AZ'},
'1520747':{'en': 'Tucson, AZ'},
'1520740':{'en': 'Tucson, AZ'},
'1415433':{'en': 'San Francisco, CA'},
'1520742':{'en': 'Tucson, AZ'},
'1520743':{'en': 'Tucson, AZ'},
'1520219':{'en': 'Tucson, AZ'},
'1520748':{'en': 'Tucson, AZ'},
'1520749':{'en': 'Tucson, AZ'},
'1418263':{'en': 'Quebec City, QC'},
'1417501':{'en': 'Springfield, MO'},
'1601782':{'en': 'Raleigh, MS'},
'1601783':{'en': 'Magnolia, MS'},
'1423744':{'en': 'Athens, TN'},
'1561279':{'en': 'Delray Beach, FL'},
'1561278':{'en': 'Delray Beach, FL'},
'1561276':{'en': 'Delray Beach, FL'},
'1561274':{'en': 'Delray Beach, FL'},
'1561272':{'en': 'Delray Beach, FL'},
'1423743':{'en': 'Erwin, TN'},
'1419592':{'en': 'Napoleon, OH'},
'1415345':{'en': 'San Francisco, CA'},
'1540674':{'en': 'Dublin, VA'},
'1540675':{'en': 'Washington, VA'},
'1540678':{'en': 'Winchester, VA'},
'1419599':{'en': 'Napoleon, OH'},
'1504834':{'en': 'Metairie, LA'},
'1580772':{'en': 'Weatherford, OK'},
'1504835':{'en': 'Metairie, LA'},
'1425653':{'en': 'Bellevue, WA'},
'1425656':{'en': 'Renton, WA'},
'1613288':{'en': 'Ottawa, ON'},
'1570454':{'en': 'Hazleton, PA'},
'1613284':{'en': 'Smiths Falls, ON'},
'1613283':{'en': 'Smiths Falls, ON'},
'1610814':{'en': 'Bethlehem, PA'},
'1570223':{'en': 'East Stroudsburg, PA'},
'1570226':{'en': 'Hawley, PA'},
'1505440':{'en': 'Albuquerque, NM'},
'1570450':{'en': 'Hazleton, PA'},
'1479419':{'en': 'Springdale, AR'},
'1434534':{'en': 'Forest, VA'},
'1517324':{'en': 'East Lansing, MI'},
'1479410':{'en': 'Van Buren, AR'},
'1517327':{'en': 'Lansing, MI'},
'1510440':{'en': 'Fremont, CA'},
'1517321':{'en': 'Lansing, MI'},
'1517322':{'en': 'Lansing, MI'},
'1517323':{'en': 'Lansing, MI'},
'1602266':{'en': 'Phoenix, AZ'},
'1602267':{'en': 'Phoenix, AZ'},
'1541783':{'en': 'Chiloquin, OR'},
'1541782':{'en': 'Oakridge, OR'},
'1602262':{'en': 'Phoenix, AZ'},
'1602263':{'en': 'Phoenix, AZ'},
'1609392':{'en': 'Trenton, NJ'},
'1541789':{'en': 'Medford, OR'},
'1609391':{'en': 'Ocean City, NJ'},
'1602268':{'en': 'Phoenix, AZ'},
'1602269':{'en': 'Phoenix, AZ'},
'1410414':{'en': 'Prince Frederick, MD'},
'1410415':{'en': 'Pikesville, MD'},
'1609390':{'en': 'Marmora, NJ'},
'1480641':{'en': 'Mesa, AZ'},
'1410418':{'en': 'Ellicott City, MD'},
'1604248':{'en': 'Richmond, BC'},
'1609396':{'en': 'Trenton, NJ'},
'1502':{'en': 'Kentucky'},
'1503':{'en': 'Oregon'},
'1501':{'en': 'Arkansas'},
'1506':{'en': 'New Brunswick'},
'1507':{'en': 'Minnesota'},
'1504':{'en': 'Louisiana'},
'1505':{'en': 'New Mexico'},
'1418977':{'en': 'Quebec City, QC'},
'1480644':{'en': 'Mesa, AZ'},
'1508':{'en': 'Massachusetts'},
'1509':{'en': 'Washington State'},
'1541259':{'en': 'Lebanon, OR'},
'1541258':{'en': 'Lebanon, OR'},
'1570488':{'en': 'Waymart, PA'},
'1570955':{'en': 'Scranton, PA'},
'1575472':{'en': 'Santa Rosa, NM'},
'1513791':{'en': 'Cincinnati, OH'},
'1413267':{'en': 'Monson, MA'},
'1513793':{'en': 'Cincinnati, OH'},
'1513792':{'en': 'Cincinnati, OH'},
'1513794':{'en': 'Cincinnati, OH'},
'1513797':{'en': 'Amelia, OH'},
'1413268':{'en': 'Williamsburg, MA'},
'1518677':{'en': 'Cambridge, NY'},
'1518674':{'en': 'Averill Park, NY'},
'1518673':{'en': 'Canajoharie, NY'},
'1514369':{'en': 'Montreal, QC'},
'1514368':{'en': 'Lasalle, QC'},
'1616676':{'en': 'Ada, MI'},
'1616677':{'en': 'Marne, MI'},
'1514363':{'en': 'Lasalle, QC'},
'1602993':{'en': 'Phoenix, AZ'},
'1514365':{'en': 'Lasalle, QC'},
'1514364':{'en': 'Lasalle, QC'},
'1514367':{'en': 'Lasalle, QC'},
'1514366':{'en': 'Lasalle, QC'},
'1513868':{'en': 'Hamilton, OH'},
'1616844':{'en': 'Grand Haven, MI'},
'1513863':{'en': 'Hamilton, OH'},
'1513862':{'en': 'Cincinnati, OH'},
'1513861':{'en': 'Cincinnati, OH'},
'1513867':{'en': 'Hamilton, OH'},
'1603645':{'en': 'Manchester, NH'},
'1479675':{'en': 'Booneville, AR'},
'1502495':{'en': 'Louisville, KY'},
'1603644':{'en': 'Manchester, NH'},
'1502491':{'en': 'Louisville, KY'},
'1502493':{'en': 'Louisville, KY'},
'1502499':{'en': 'Louisville, KY'},
'1519631':{'en': 'St. Thomas, ON'},
'1519238':{'en': 'Grand Bend, ON'},
'1417782':{'en': 'Joplin, MO'},
'1603641':{'en': 'Manchester, NH'},
'1519633':{'en': 'St. Thomas, ON'},
'1519235':{'en': 'Exeter, ON'},
'1519236':{'en': 'Zurich, ON'},
'1617298':{'en': 'Mattapan, MA'},
'1512854':{'en': 'Austin, TX'},
'1616842':{'en': 'Grand Haven, MI'},
'1501609':{'en': 'Hot Springs, AR'},
'1501604':{'en': 'Little Rock, AR'},
'1501605':{'en': 'Cabot, AR'},
'1501603':{'en': 'Little Rock, AR'},
'1574654':{'en': 'New Carlisle, IN'},
'1607898':{'en': 'Groton, NY'},
'1609242':{'en': 'Forked River, NJ'},
'1615883':{'en': 'Nashville, TN'},
'1508721':{'en': 'Auburn, MA'},
'1610838':{'en': 'Hellertown, PA'},
'1416922':{'en': 'Toronto, ON'},
'1416923':{'en': 'Toronto, ON'},
'1416920':{'en': 'Toronto, ON'},
'1416921':{'en': 'Toronto, ON'},
'1416926':{'en': 'Toronto, ON'},
'1416251':{'en': 'Etobicoke, ON'},
'1416252':{'en': 'Etobicoke, ON'},
'1416925':{'en': 'Toronto, ON'},
'1416928':{'en': 'Toronto, ON'},
'1416929':{'en': 'Toronto, ON'},
'1416259':{'en': 'Etobicoke, ON'},
'1616847':{'en': 'Grand Haven, MI'},
'1415876':{'en': 'San Francisco, CA'},
'1510436':{'en': 'Oakland, CA'},
'1520917':{'en': 'Tucson, AZ'},
'1604273':{'en': 'Richmond, BC'},
'1604272':{'en': 'Richmond, BC'},
'1604271':{'en': 'Richmond, BC'},
'1604270':{'en': 'Richmond, BC'},
'1585279':{'en': 'Rochester, NY'},
'1604276':{'en': 'Richmond, BC'},
'1604275':{'en': 'Richmond, BC'},
'1423837':{'en': 'South Pittsburg, TN'},
'1415695':{'en': 'San Francisco, CA'},
'1604279':{'en': 'Richmond, BC'},
'1604278':{'en': 'Richmond, BC'},
'1585271':{'en': 'Rochester, NY'},
'1585270':{'en': 'Rochester, NY'},
'1415693':{'en': 'San Francisco, CA'},
'1585272':{'en': 'Rochester, NY'},
'1573860':{'en': 'Sullivan, MO'},
'1573686':{'en': 'Poplar Bluff, MO'},
'1573683':{'en': 'Charleston, MO'},
'1573682':{'en': 'Centralia, MO'},
'1515237':{'en': 'Des Moines, IA'},
'1515232':{'en': 'Ames, IA'},
'1515233':{'en': 'Ames, IA'},
'1515239':{'en': 'Ames, IA'},
'1562461':{'en': 'Bellflower, CA'},
'1562464':{'en': 'Whittier, CA'},
'1508234':{'en': 'Whitinsville, MA'},
'1508235':{'en': 'Fall River, MA'},
'1508232':{'en': 'Brockton, MA'},
'1507765':{'en': 'Preston, MN'},
'1510433':{'en': 'Oakland, CA'},
'1615595':{'en': 'Franklin, TN'},
'1505610':{'en': 'Albuquerque, NM'},
'1615591':{'en': 'Franklin, TN'},
'1505615':{'en': 'Albuquerque, NM'},
'1410788':{'en': 'Catonsville, MD'},
'1605322':{'en': 'Sioux Falls, SD'},
'1615599':{'en': 'Franklin, TN'},
'1503474':{'en': 'McMinnville, OR'},
'1503477':{'en': 'Portland, OR'},
'1574299':{'en': 'South Bend, IN'},
'1503473':{'en': 'Portland, OR'},
'1503472':{'en': 'McMinnville, OR'},
'1604894':{'en': 'Pemberton, BC'},
'1604892':{'en': 'Squamish, BC'},
'1604891':{'en': 'Vancouver, BC'},
'1614428':{'en': 'Columbus, OH'},
'1614355':{'en': 'Columbus, OH'},
'1614351':{'en': 'Columbus, OH'},
'1604899':{'en': 'Vancouver, BC'},
'1604898':{'en': 'Squamish, BC'},
'1509829':{'en': 'Zillah, WA'},
'1607625':{'en': 'Apalachin, NY'},
'1410318':{'en': 'Baltimore, MD'},
'1410313':{'en': 'Ellicott City, MD'},
'1410312':{'en': 'Columbia, MD'},
'1607334':{'en': 'Norwich, NY'},
'1503517':{'en': 'Portland, OR'},
'1410315':{'en': 'Severna Park, MD'},
'1440356':{'en': 'Cleveland, OH'},
'1423307':{'en': 'Morristown, TN'},
'1423305':{'en': 'Chattanooga, TN'},
'1610944':{'en': 'Fleetwood, PA'},
'1418562':{'en': 'Matane, QC'},
'1418566':{'en': 'Matane, QC'},
'1418567':{'en': 'Chute-aux-Outardes, QC'},
'1606330':{'en': 'London, KY'},
'1480472':{'en': 'Mesa, AZ'},
'1505822':{'en': 'Albuquerque, NM'},
'1435613':{'en': 'Price, UT'},
'1606337':{'en': 'Pineville, KY'},
'1580355':{'en': 'Lawton, OK'},
'1580354':{'en': 'Lawton, OK'},
'1580357':{'en': 'Lawton, OK'},
'1502708':{'en': 'Louisville, KY'},
'1505417':{'en': 'Albuquerque, NM'},
'1506634':{'en': 'Saint John, NB'},
'1506635':{'en': 'Saint John, NB'},
'1617338':{'en': 'Boston, MA'},
'1605297':{'en': 'Parker, SD'},
'1440358':{'en': 'Painesville, OH'},
'1506632':{'en': 'Saint John, NB'},
'1506633':{'en': 'Saint John, NB'},
'1617332':{'en': 'Newton, MA'},
'1617330':{'en': 'Boston, MA'},
'1513651':{'en': 'Cincinnati, OH'},
'1612545':{'en': 'Minneapolis, MN'},
'1570882':{'en': 'Sayre, PA'},
'1417338':{'en': 'Branson, MO'},
'1417339':{'en': 'Branson, MO'},
'1561487':{'en': 'Boca Raton, FL'},
'1561482':{'en': 'Boca Raton, FL'},
'1561483':{'en': 'Boca Raton, FL'},
'1417332':{'en': 'Branson, MO'},
'1517796':{'en': 'Jackson, MI'},
'1417334':{'en': 'Branson, MO'},
'1417335':{'en': 'Branson, MO'},
'1502647':{'en': 'Shelbyville, KY'},
'1417337':{'en': 'Branson, MO'},
'1419784':{'en': 'Defiance, OH'},
'1419782':{'en': 'Defiance, OH'},
'1518262':{'en': 'Albany, NY'},
'1610328':{'en': 'Springfield, PA'},
'1530749':{'en': 'Marysville, CA'},
'1530747':{'en': 'Davis, CA'},
'1530741':{'en': 'Marysville, CA'},
'1530743':{'en': 'Marysville, CA'},
'1530742':{'en': 'Marysville, CA'},
'1479880':{'en': 'Russellville, AR'},
'1540224':{'en': 'Roanoke, VA'},
'1561738':{'en': 'Boynton Beach, FL'},
'1561739':{'en': 'Boynton Beach, FL'},
'1561736':{'en': 'Boynton Beach, FL'},
'1561737':{'en': 'Boynton Beach, FL'},
'1561734':{'en': 'Boynton Beach, FL'},
'1561735':{'en': 'Boynton Beach, FL'},
'1561732':{'en': 'Boynton Beach, FL'},
'1561733':{'en': 'Boynton Beach, FL'},
'1561731':{'en': 'Boynton Beach, FL'},
'1570563':{'en': 'Dalton, PA'},
'1570562':{'en': 'Taylor, PA'},
'1413529':{'en': 'Easthampton, MA'},
'1413528':{'en': 'Great Barrington, MA'},
'1512462':{'en': 'Austin, TX'},
'1607467':{'en': 'Deposit, NY'},
'1413525':{'en': 'East Longmeadow, MA'},
'1413527':{'en': 'Easthampton, MA'},
'1510651':{'en': 'Fremont, CA'},
'1510653':{'en': 'Oakland, CA'},
'1510652':{'en': 'Oakland, CA'},
'1510655':{'en': 'Oakland, CA'},
'1510654':{'en': 'Oakland, CA'},
'1510657':{'en': 'Fremont, CA'},
'1510656':{'en': 'Fremont, CA'},
'1510659':{'en': 'Fremont, CA'},
'1559228':{'en': 'Fresno, CA'},
'1518348':{'en': 'Clifton Park, NY'},
'1512463':{'en': 'Austin, TX'},
'1519428':{'en': 'Simcoe, ON'},
'1519938':{'en': 'Orangeville, ON'},
'1519425':{'en': 'Ingersoll, ON'},
'1519424':{'en': 'Burgessville, ON'},
'1519426':{'en': 'Simcoe, ON'},
'1519421':{'en': 'Woodstock, ON'},
'1425303':{'en': 'Everett, WA'},
'1616245':{'en': 'Grand Rapids, MI'},
'1616247':{'en': 'Grand Rapids, MI'},
'1616241':{'en': 'Grand Rapids, MI'},
'1616243':{'en': 'Grand Rapids, MI'},
'1616242':{'en': 'Grand Rapids, MI'},
'1602522':{'en': 'Phoenix, AZ'},
'1616248':{'en': 'Grand Rapids, MI'},
'1519688':{'en': 'Tillsonburg, ON'},
'1508539':{'en': 'Mashpee, MA'},
'1519681':{'en': 'London, ON'},
'1519680':{'en': 'London, ON'},
'1519683':{'en': 'Dresden, ON'},
'1519682':{'en': 'Tilbury, ON'},
'1519685':{'en': 'London, ON'},
'1508533':{'en': 'Medway, MA'},
'1519686':{'en': 'London, ON'},
'1415206':{'en': 'San Francisco, CA'},
'1503288':{'en': 'Portland, OR'},
'1418365':{'en': 'St-Tite, QC'},
'1412922':{'en': 'Pittsburgh, PA'},
'1509628':{'en': 'Richland, WA'},
'1412921':{'en': 'Pittsburgh, PA'},
'1503282':{'en': 'Portland, OR'},
'1509627':{'en': 'Richland, WA'},
'1509624':{'en': 'Spokane, WA'},
'1503281':{'en': 'Portland, OR'},
'1503286':{'en': 'Portland, OR'},
'1503287':{'en': 'Portland, OR'},
'1418368':{'en': u('Gasp\u00e9, QC')},
'1503285':{'en': 'Portland, OR'},
'1585599':{'en': 'Corfu, NY'},
'1585591':{'en': 'Attica, NY'},
'1585593':{'en': 'Wellsville, NY'},
'1416351':{'en': 'Toronto, ON'},
'1432620':{'en': 'Midland, TX'},
'1478825':{'en': 'Fort Valley, GA'},
'1541490':{'en': 'Hood River, OR'},
'1603926':{'en': 'Hampton, NH'},
'1603924':{'en': 'Peterborough, NH'},
'1563259':{'en': 'Camanche, IA'},
'1563252':{'en': 'Guttenberg, IA'},
'1573486':{'en': 'Hermann, MO'},
'1603929':{'en': 'Hampton, NH'},
'1585730':{'en': 'Rochester, NY'},
'1609430':{'en': 'Princeton, NJ'},
'1508393':{'en': 'Northborough, MA'},
'1508399':{'en': 'Attleboro, MA'},
'1570970':{'en': 'Wilkes-Barre, PA'},
'1432561':{'en': 'Odessa, TX'},
'1615230':{'en': 'Gallatin, TN'},
'1615298':{'en': 'Nashville, TN'},
'1520586':{'en': 'Benson, AZ'},
'1507789':{'en': 'Kenyon, MN'},
'1615741':{'en': 'Nashville, TN'},
'1615292':{'en': 'Nashville, TN'},
'1615291':{'en': 'Nashville, TN'},
'1615742':{'en': 'Nashville, TN'},
'1615297':{'en': 'Nashville, TN'},
'1615746':{'en': 'Pleasant View, TN'},
'1610718':{'en': 'Pottstown, PA'},
'1562612':{'en': 'Long Beach, CA'},
'1541278':{'en': 'Pendleton, OR'},
'1559638':{'en': 'Reedley, CA'},
'1559635':{'en': 'Visalia, CA'},
'1559636':{'en': 'Visalia, CA'},
'1559637':{'en': 'Reedley, CA'},
'1574875':{'en': 'Elkhart, IN'},
'1520760':{'en': 'Tucson, AZ'},
'1520761':{'en': 'Nogales, AZ'},
'1417833':{'en': 'Springfield, MO'},
'1417832':{'en': 'Springfield, MO'},
'1417831':{'en': 'Springfield, MO'},
'1573472':{'en': 'Sikeston, MO'},
'1601785':{'en': 'Taylorsville, MS'},
'1601786':{'en': 'Fayette, MS'},
'1414332':{'en': 'Milwaukee, WI'},
'1573474':{'en': 'Columbia, MO'},
'1408654':{'en': 'Santa Clara, CA'},
'1601788':{'en': 'Richton, MS'},
'1419578':{'en': 'Toledo, OH'},
'1412278':{'en': 'Carnegie, PA'},
'1510885':{'en': 'Hayward, CA'},
'1510886':{'en': 'Hayward, CA'},
'1510887':{'en': 'Hayward, CA'},
'1480860':{'en': 'Scottsdale, AZ'},
'1606528':{'en': 'Corbin, KY'},
'1510883':{'en': 'Berkeley, CA'},
'1606837':{'en': 'Evarts, KY'},
'1480649':{'en': 'Mesa, AZ'},
'1606526':{'en': 'Corbin, KY'},
'1510888':{'en': 'Hayward, CA'},
'1606832':{'en': 'Jenkins, KY'},
'1606523':{'en': 'Corbin, KY'},
'1519882':{'en': 'Petrolia, ON'},
'1617294':{'en': 'Everett, MA'},
'1434736':{'en': 'Keysville, VA'},
'1617292':{'en': 'Boston, MA'},
'1417781':{'en': 'Joplin, MO'},
'1434738':{'en': 'Boydton, VA'},
'1440466':{'en': 'Geneva, OH'},
'1601437':{'en': 'Port Gibson, MS'},
'1505428':{'en': 'Santa Fe, NM'},
'1574296':{'en': 'Elkhart, IN'},
'1574295':{'en': 'Elkhart, IN'},
'1410787':{'en': 'Glen Burnie, MD'},
'1574293':{'en': 'Elkhart, IN'},
'1574291':{'en': 'South Bend, IN'},
'1410783':{'en': 'Baltimore, MD'},
'1505424':{'en': 'Santa Fe, NM'},
'1505425':{'en': 'Las Vegas, NM'},
'1505426':{'en': 'Las Vegas, NM'},
'1606789':{'en': 'Paintsville, KY'},
'1606788':{'en': 'Paintsville, KY'},
'1435283':{'en': 'Ephraim, UT'},
'1606780':{'en': 'Morehead, KY'},
'1606783':{'en': 'Morehead, KY'},
'1606785':{'en': 'Hindman, KY'},
'1606784':{'en': 'Morehead, KY'},
'1606787':{'en': 'Liberty, KY'},
'1418248':{'en': 'Montmagny, QC'},
'1602200':{'en': 'Phoenix, AZ'},
'1585647':{'en': 'Rochester, NY'},
'1574773':{'en': 'Nappanee, IN'},
'1410439':{'en': 'Pasadena, MD'},
'1410437':{'en': 'Pasadena, MD'},
'1410435':{'en': 'Baltimore, MD'},
'1410433':{'en': 'Baltimore, MD'},
'1580657':{'en': 'Lone Grove, OK'},
'1561':{'en': 'Florida'},
'1562':{'en': 'California'},
'1563':{'en': 'Iowa'},
'1564':{'en': 'Washington State'},
'1567':{'en': 'Ohio'},
'1541276':{'en': 'Pendleton, OR'},
'1541271':{'en': 'Reedsport, OR'},
'1541273':{'en': 'Klamath Falls, OR'},
'1501565':{'en': 'Little Rock, AR'},
'1573764':{'en': 'Gerald, MO'},
'1605260':{'en': 'Yankton, SD'},
'1501257':{'en': 'Little Rock, AR'},
'1501255':{'en': 'Little Rock, AR'},
'1440460':{'en': 'Cleveland, OH'},
'1440461':{'en': 'Cleveland, OH'},
'1409296':{'en': 'Winnie, TX'},
'1580654':{'en': 'Carnegie, OK'},
'1479471':{'en': 'Van Buren, AR'},
'1510465':{'en': 'Oakland, CA'},
'1580652':{'en': 'Hooker, OK'},
'1479474':{'en': 'Van Buren, AR'},
'1608365':{'en': 'Beloit, WI'},
'1479478':{'en': 'Fort Smith, AR'},
'1580658':{'en': 'Marlow, OK'},
'1518654':{'en': 'Corinth, NY'},
}
| 36.746982
| 75
| 0.531716
|
b1abf7c81e9fe042ac34e59b32616e4452c68bec
| 383
|
py
|
Python
|
src/tars/strategies/__init__.py
|
fredmontet/tars
|
922786e8c6456fc0cc1a9db07714f11dd78219d9
|
[
"MIT"
] | 3
|
2022-02-06T14:41:07.000Z
|
2022-03-25T16:27:45.000Z
|
src/tars/strategies/__init__.py
|
fredmontet/tars
|
922786e8c6456fc0cc1a9db07714f11dd78219d9
|
[
"MIT"
] | 6
|
2021-09-20T03:33:31.000Z
|
2022-03-24T09:00:48.000Z
|
src/tars/strategies/__init__.py
|
fredmontet/tars
|
922786e8c6456fc0cc1a9db07714f11dd78219d9
|
[
"MIT"
] | null | null | null |
from .abstract_strategy import AbstractStrategy
from .buy_and_hold_strategy import BuyAndHold
from .random_investment_strategy import RandomInvestment
from .sequential_investment_strategy import SequentialInvestment
from .trend_following_strategy import TrendFollowing
from .trend_following_macd_strategy import TrendFollowingMACD
from .prediction_strategy import PredictionStrategy
| 47.875
| 64
| 0.908616
|
b5dbdcc6413acae66261f9783c3eb96335bbaf29
| 11,274
|
py
|
Python
|
test/functional/rpc_psbt.py
|
anandhu-here/chuckrum
|
f2a734745e752cda50f5556cded7a713d969f4bc
|
[
"MIT"
] | null | null | null |
test/functional/rpc_psbt.py
|
anandhu-here/chuckrum
|
f2a734745e752cda50f5556cded7a713d969f4bc
|
[
"MIT"
] | 1
|
2021-07-12T07:38:58.000Z
|
2021-07-12T07:38:58.000Z
|
test/functional/rpc_psbt.py
|
anandhu-here/chuckrum
|
f2a734745e752cda50f5556cded7a713d969f4bc
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the Partially Signed Transaction RPCs.
"""
from test_framework.test_framework import ChuckrumTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error, find_output
import json
import os
MAX_BIP125_RBF_SEQUENCE = 0xfffffffd
# Create one-input, one-output, no-fee transaction:
class PSBTTest(ChuckrumTestFramework):
def set_test_params(self):
self.setup_clean_chain = False
self.num_nodes = 3
def run_test(self):
# Create and fund a raw tx for sending 10 CKM
psbtx1 = self.nodes[0].walletcreatefundedpsbt([], {self.nodes[2].getnewaddress():10})['psbt']
# Node 1 should not be able to add anything to it but still return the psbtx same as before
psbtx = self.nodes[1].walletprocesspsbt(psbtx1)['psbt']
assert_equal(psbtx1, psbtx)
# Sign the transaction and send
signed_tx = self.nodes[0].walletprocesspsbt(psbtx)['psbt']
final_tx = self.nodes[0].finalizepsbt(signed_tx)['hex']
self.nodes[0].sendrawtransaction(final_tx)
# Create p2sh, p2wpkh, and p2wsh addresses
pubkey0 = self.nodes[0].getaddressinfo(self.nodes[0].getnewaddress())['pubkey']
pubkey1 = self.nodes[1].getaddressinfo(self.nodes[1].getnewaddress())['pubkey']
pubkey2 = self.nodes[2].getaddressinfo(self.nodes[2].getnewaddress())['pubkey']
p2sh = self.nodes[1].addmultisigaddress(2, [pubkey0, pubkey1, pubkey2], "", "legacy")['address']
p2wsh = self.nodes[1].addmultisigaddress(2, [pubkey0, pubkey1, pubkey2], "", "bech32")['address']
p2sh_p2wsh = self.nodes[1].addmultisigaddress(2, [pubkey0, pubkey1, pubkey2], "", "p2sh-segwit")['address']
p2wpkh = self.nodes[1].getnewaddress("", "bech32")
p2pkh = self.nodes[1].getnewaddress("", "legacy")
p2sh_p2wpkh = self.nodes[1].getnewaddress("", "p2sh-segwit")
# fund those addresses
rawtx = self.nodes[0].createrawtransaction([], {p2sh:10, p2wsh:10, p2wpkh:10, p2sh_p2wsh:10, p2sh_p2wpkh:10, p2pkh:10})
rawtx = self.nodes[0].fundrawtransaction(rawtx, {"changePosition":3})
signed_tx = self.nodes[0].signrawtransactionwithwallet(rawtx['hex'])['hex']
txid = self.nodes[0].sendrawtransaction(signed_tx)
self.nodes[0].generate(6)
self.sync_all()
# Find the output pos
p2sh_pos = -1
p2wsh_pos = -1
p2wpkh_pos = -1
p2pkh_pos = -1
p2sh_p2wsh_pos = -1
p2sh_p2wpkh_pos = -1
decoded = self.nodes[0].decoderawtransaction(signed_tx)
for out in decoded['vout']:
if out['scriptPubKey']['addresses'][0] == p2sh:
p2sh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2wsh:
p2wsh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2wpkh:
p2wpkh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2sh_p2wsh:
p2sh_p2wsh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2sh_p2wpkh:
p2sh_p2wpkh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2pkh:
p2pkh_pos = out['n']
# spend single key from node 1
rawtx = self.nodes[1].walletcreatefundedpsbt([{"txid":txid,"vout":p2wpkh_pos},{"txid":txid,"vout":p2sh_p2wpkh_pos},{"txid":txid,"vout":p2pkh_pos}], {self.nodes[1].getnewaddress():29.99})['psbt']
walletprocesspsbt_out = self.nodes[1].walletprocesspsbt(rawtx)
assert_equal(walletprocesspsbt_out['complete'], True)
self.nodes[1].sendrawtransaction(self.nodes[1].finalizepsbt(walletprocesspsbt_out['psbt'])['hex'])
# partially sign multisig things with node 1
psbtx = self.nodes[1].walletcreatefundedpsbt([{"txid":txid,"vout":p2wsh_pos},{"txid":txid,"vout":p2sh_pos},{"txid":txid,"vout":p2sh_p2wsh_pos}], {self.nodes[1].getnewaddress():29.99})['psbt']
walletprocesspsbt_out = self.nodes[1].walletprocesspsbt(psbtx)
psbtx = walletprocesspsbt_out['psbt']
assert_equal(walletprocesspsbt_out['complete'], False)
# partially sign with node 2. This should be complete and sendable
walletprocesspsbt_out = self.nodes[2].walletprocesspsbt(psbtx)
assert_equal(walletprocesspsbt_out['complete'], True)
self.nodes[2].sendrawtransaction(self.nodes[2].finalizepsbt(walletprocesspsbt_out['psbt'])['hex'])
# check that walletprocesspsbt fails to decode a non-psbt
rawtx = self.nodes[1].createrawtransaction([{"txid":txid,"vout":p2wpkh_pos}], {self.nodes[1].getnewaddress():9.99})
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[1].walletprocesspsbt, rawtx)
# Convert a non-psbt to psbt and make sure we can decode it
rawtx = self.nodes[0].createrawtransaction([], {self.nodes[1].getnewaddress():10})
rawtx = self.nodes[0].fundrawtransaction(rawtx)
new_psbt = self.nodes[0].converttopsbt(rawtx['hex'])
self.nodes[0].decodepsbt(new_psbt)
# Make sure that a psbt with signatures cannot be converted
signedtx = self.nodes[0].signrawtransactionwithwallet(rawtx['hex'])
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].converttopsbt, signedtx['hex'])
# Explicilty allow converting non-empty txs
new_psbt = self.nodes[0].converttopsbt(rawtx['hex'])
self.nodes[0].decodepsbt(new_psbt)
# Create outputs to nodes 1 and 2
node1_addr = self.nodes[1].getnewaddress()
node2_addr = self.nodes[2].getnewaddress()
txid1 = self.nodes[0].sendtoaddress(node1_addr, 13)
txid2 =self.nodes[0].sendtoaddress(node2_addr, 13)
self.nodes[0].generate(6)
self.sync_all()
vout1 = find_output(self.nodes[1], txid1, 13)
vout2 = find_output(self.nodes[2], txid2, 13)
# Create a psbt spending outputs from nodes 1 and 2
psbt_orig = self.nodes[0].createpsbt([{"txid":txid1, "vout":vout1}, {"txid":txid2, "vout":vout2}], {self.nodes[0].getnewaddress():25.999})
# Update psbts, should only have data for one input and not the other
psbt1 = self.nodes[1].walletprocesspsbt(psbt_orig)['psbt']
psbt1_decoded = self.nodes[0].decodepsbt(psbt1)
assert psbt1_decoded['inputs'][0] and not psbt1_decoded['inputs'][1]
psbt2 = self.nodes[2].walletprocesspsbt(psbt_orig)['psbt']
psbt2_decoded = self.nodes[0].decodepsbt(psbt2)
assert not psbt2_decoded['inputs'][0] and psbt2_decoded['inputs'][1]
# Combine, finalize, and send the psbts
combined = self.nodes[0].combinepsbt([psbt1, psbt2])
finalized = self.nodes[0].finalizepsbt(combined)['hex']
self.nodes[0].sendrawtransaction(finalized)
self.nodes[0].generate(6)
self.sync_all()
# Test additional args in walletcreatepsbt
# Make sure both pre-included and funded inputs
# have the correct sequence numbers based on
# replaceable arg
block_height = self.nodes[0].getblockcount()
unspent = self.nodes[0].listunspent()[0]
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}], block_height+2, {"replaceable":True}, False)
decoded_psbt = self.nodes[0].decodepsbt(psbtx_info["psbt"])
for tx_in, psbt_in in zip(decoded_psbt["tx"]["vin"], decoded_psbt["inputs"]):
assert_equal(tx_in["sequence"], MAX_BIP125_RBF_SEQUENCE)
assert "bip32_derivs" not in psbt_in
assert_equal(decoded_psbt["tx"]["locktime"], block_height+2)
# Same construction with only locktime set
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}], block_height, {}, True)
decoded_psbt = self.nodes[0].decodepsbt(psbtx_info["psbt"])
for tx_in, psbt_in in zip(decoded_psbt["tx"]["vin"], decoded_psbt["inputs"]):
assert tx_in["sequence"] > MAX_BIP125_RBF_SEQUENCE
assert "bip32_derivs" in psbt_in
assert_equal(decoded_psbt["tx"]["locktime"], block_height)
# Same construction without optional arguments
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}])
decoded_psbt = self.nodes[0].decodepsbt(psbtx_info["psbt"])
for tx_in in decoded_psbt["tx"]["vin"]:
assert tx_in["sequence"] > MAX_BIP125_RBF_SEQUENCE
assert_equal(decoded_psbt["tx"]["locktime"], 0)
# BIP 174 Test Vectors
# Check that unknown values are just passed through
unknown_psbt = "cHNidP8BAD8CAAAAAf//////////////////////////////////////////AAAAAAD/////AQAAAAAAAAAAA2oBAAAAAAAACg8BAgMEBQYHCAkPAQIDBAUGBwgJCgsMDQ4PAAA="
unknown_out = self.nodes[0].walletprocesspsbt(unknown_psbt)['psbt']
assert_equal(unknown_psbt, unknown_out)
# Open the data file
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/rpc_psbt.json'), encoding='utf-8') as f:
d = json.load(f)
invalids = d['invalid']
valids = d['valid']
creators = d['creator']
signers = d['signer']
combiners = d['combiner']
finalizers = d['finalizer']
extractors = d['extractor']
# Invalid PSBTs
for invalid in invalids:
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].decodepsbt, invalid)
# Valid PSBTs
for valid in valids:
self.nodes[0].decodepsbt(valid)
# Creator Tests
for creator in creators:
created_tx = self.nodes[0].createpsbt(creator['inputs'], creator['outputs'])
assert_equal(created_tx, creator['result'])
# Signer tests
for i, signer in enumerate(signers):
self.nodes[2].createwallet("wallet{}".format(i))
wrpc = self.nodes[2].get_wallet_rpc("wallet{}".format(i))
for key in signer['privkeys']:
wrpc.importprivkey(key)
signed_tx = wrpc.walletprocesspsbt(signer['psbt'])['psbt']
assert_equal(signed_tx, signer['result'])
# Combiner test
for combiner in combiners:
combined = self.nodes[2].combinepsbt(combiner['combine'])
assert_equal(combined, combiner['result'])
# Finalizer test
for finalizer in finalizers:
finalized = self.nodes[2].finalizepsbt(finalizer['finalize'], False)['psbt']
assert_equal(finalized, finalizer['result'])
# Extractor test
for extractor in extractors:
extracted = self.nodes[2].finalizepsbt(extractor['extract'], True)['hex']
assert_equal(extracted, extractor['result'])
if __name__ == '__main__':
PSBTTest().main()
| 49.665198
| 209
| 0.644758
|
969429acd21b101d3565ac8f11590d31cec75d4f
| 3,099
|
py
|
Python
|
covid.py
|
renancvr/covid19-piumhi
|
5159bfe1fcc11dc26f1b260ba2a06c4a61249bf5
|
[
"MIT"
] | null | null | null |
covid.py
|
renancvr/covid19-piumhi
|
5159bfe1fcc11dc26f1b260ba2a06c4a61249bf5
|
[
"MIT"
] | null | null | null |
covid.py
|
renancvr/covid19-piumhi
|
5159bfe1fcc11dc26f1b260ba2a06c4a61249bf5
|
[
"MIT"
] | null | null | null |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import pandas as pd
import math
def moving_average(a, n=7) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
#leitura de dados e montagem dos arrays para plotagem:
df = pd.read_excel('dados.xlsx')
casos = []
mortes = []
recuperados = []
dias = []
for i in range(len(df.values)):
casos.append(df.values[i][1])
mortes.append(df.values[i][2])
recuperados.append(df.values[i][3])
dias.append(df.values[i][4])
#calculo de casos diários
casos_dia = [0]
for i in range(len(casos)):
if i+1<=len(casos)-1:
novos_casos = casos[i+1] - casos[i]
casos_dia.append(novos_casos)
#calculo de casos ativos
casos_ativos = []
for i in range(len(casos)):
ativos = (casos[i] - recuperados[i]) - mortes[i]
casos_ativos.append(ativos)
#atualizar a tabela de dados com casos diários e casos ativos
dados_atualizados = [casos,mortes,recuperados,dias,casos_dia,casos_ativos]
df = pd.DataFrame(dados_atualizados,index=['Casos Confirmados','Óbitos','Recuperados','Dia','Casos Diários','Casos Ativos']).T
df.to_excel('dados.xlsx')
#cálculo taxa de mortalidade
taxa = round((mortes[len(mortes)-1] * 100) / casos[len(casos)-1],2)
#criação de informações para a legenda
string_mortalidade = 'Taxa de mortalidade: ' + str(taxa) + '%'
string_ativos = 'Casos ativos: ' + str(int(casos_ativos[len(casos_ativos)-1]))
string_mortes = 'Total de mortes: ' + str(mortes[len(mortes)-1])
#calcular número R
r = math.exp((math.log(34691/((1/(casos[len(casos)-1]/(casos[0]*34691)))-1)))/(len(dias)))
print('Número R: ' + str(r))
#criação dos arrays para plotagem
y_casos = moving_average(casos)
y_casos_dia = moving_average(casos_dia)
y_recuperados = moving_average(recuperados)
y_mortes = moving_average(mortes)
y_casos_ativos = moving_average(casos_ativos)
x = np.arange(1,len(y_casos)+1,1)
#plotagem do gráfico
f1 = plt.figure(1)
blue_patch = mpatches.Patch(color='blue',label='Casos confirmados')
purple_patch = mpatches.Patch(color='purple',label='Casos ativos')
green_patch = mpatches.Patch(color='green',label='Recuperados')
taxa_patch = mpatches.Patch(color = 'white', label = string_mortalidade)
ativos_patch = mpatches.Patch(color = 'white', label = string_ativos)
legenda = 'Dias (04/06/2020 - '+str(int(dias[len(dias)-1]))+'/08/2021 )'
plt.plot(x,y_casos,color='blue')
plt.plot(x,y_recuperados,color='green')
plt.plot(x,y_casos_ativos,color='purple')
plt.ylabel('Média móvel de 7 dias')
plt.xlabel(legenda)
plt.grid(True)
plt.legend(handles=[blue_patch,purple_patch,green_patch,taxa_patch,ativos_patch])
f2 = plt.figure(2)
orange_patch = mpatches.Patch(color='orange',label='Casos diários')
red_patch = mpatches.Patch(color='red',label='Óbitos confirmados')
mortes_patch = mpatches.Patch(color='white',label=string_mortes)
plt.plot(x,y_mortes,color='red')
plt.plot(x,y_casos_dia,color='orange')
plt.ylabel('Média móvel de 7 dias')
plt.xlabel(legenda)
plt.grid(True)
plt.legend(handles=[red_patch,orange_patch,taxa_patch,mortes_patch])
plt.show()
| 29.798077
| 126
| 0.727654
|
6afd272e033ced6a6b66a9d7761f8febdebaeeb3
| 10,879
|
py
|
Python
|
tests/puzzle/test_provider.py
|
maggyero/poetry
|
3c7592c2f3d481f5e655a68fc1fa15c5bc024cda
|
[
"MIT"
] | 2
|
2019-06-19T15:07:58.000Z
|
2019-11-24T14:08:55.000Z
|
tests/puzzle/test_provider.py
|
djetelina/poetry
|
1aa1ab2962bb8b6aed33c2308cf8352809d91685
|
[
"MIT"
] | 1
|
2019-09-07T16:31:54.000Z
|
2019-09-07T16:31:54.000Z
|
tests/puzzle/test_provider.py
|
djetelina/poetry
|
1aa1ab2962bb8b6aed33c2308cf8352809d91685
|
[
"MIT"
] | 1
|
2019-06-19T15:08:05.000Z
|
2019-06-19T15:08:05.000Z
|
import pytest
from poetry.io import NullIO
from poetry.packages import ProjectPackage
from poetry.packages.directory_dependency import DirectoryDependency
from poetry.packages.file_dependency import FileDependency
from poetry.packages.vcs_dependency import VCSDependency
from poetry.puzzle.provider import Provider
from poetry.repositories.pool import Pool
from poetry.repositories.repository import Repository
from poetry.utils._compat import PY35
from poetry.utils._compat import Path
from poetry.utils.env import EnvCommandError
from poetry.utils.env import MockEnv as BaseMockEnv
from tests.helpers import get_dependency
from subprocess import CalledProcessError
class MockEnv(BaseMockEnv):
def run(self, bin, *args):
raise EnvCommandError(CalledProcessError(1, "python", output=""))
@pytest.fixture
def root():
return ProjectPackage("root", "1.2.3")
@pytest.fixture
def repository():
return Repository()
@pytest.fixture
def pool(repository):
pool = Pool()
pool.add_repository(repository)
return pool
@pytest.fixture
def provider(root, pool):
return Provider(root, pool, NullIO())
def test_search_for_vcs_setup_egg_info(provider):
dependency = VCSDependency("demo", "git", "https://github.com/demo/demo.git")
package = provider.search_for_vcs(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.2"
assert package.requires == [get_dependency("pendulum", ">=1.4.4")]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
def test_search_for_vcs_setup_egg_info_with_extras(provider):
dependency = VCSDependency("demo", "git", "https://github.com/demo/demo.git")
dependency.extras.append("foo")
package = provider.search_for_vcs(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.2"
assert package.requires == [
get_dependency("pendulum", ">=1.4.4"),
get_dependency("cleo", optional=True),
]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4")
def test_search_for_vcs_read_setup(provider, mocker):
mocker.patch("poetry.utils.env.Env.get", return_value=MockEnv())
dependency = VCSDependency("demo", "git", "https://github.com/demo/demo.git")
package = provider.search_for_vcs(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.2"
assert package.requires == [get_dependency("pendulum", ">=1.4.4")]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4")
def test_search_for_vcs_read_setup_with_extras(provider, mocker):
mocker.patch("poetry.utils.env.Env.get", return_value=MockEnv())
dependency = VCSDependency("demo", "git", "https://github.com/demo/demo.git")
dependency.extras.append("foo")
package = provider.search_for_vcs(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.2"
assert package.requires == [
get_dependency("pendulum", ">=1.4.4"),
get_dependency("cleo", optional=True),
]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
def test_search_for_vcs_read_setup_raises_error_if_no_version(provider, mocker):
mocker.patch("poetry.utils.env.Env.get", return_value=MockEnv())
dependency = VCSDependency("demo", "git", "https://github.com/demo/no-version.git")
with pytest.raises(RuntimeError):
provider.search_for_vcs(dependency)
def test_search_for_directory_setup_egg_info(provider):
dependency = DirectoryDependency(
"demo",
Path(__file__).parent.parent
/ "fixtures"
/ "git"
/ "github.com"
/ "demo"
/ "demo",
)
package = provider.search_for_directory(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.2"
assert package.requires == [get_dependency("pendulum", ">=1.4.4")]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
def test_search_for_directory_setup_egg_info_with_extras(provider):
dependency = DirectoryDependency(
"demo",
Path(__file__).parent.parent
/ "fixtures"
/ "git"
/ "github.com"
/ "demo"
/ "demo",
)
dependency.extras.append("foo")
package = provider.search_for_directory(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.2"
assert package.requires == [
get_dependency("pendulum", ">=1.4.4"),
get_dependency("cleo", optional=True),
]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4")
def test_search_for_directory_setup_read_setup(provider, mocker):
mocker.patch("poetry.utils.env.Env.get", return_value=MockEnv())
dependency = DirectoryDependency(
"demo",
Path(__file__).parent.parent
/ "fixtures"
/ "git"
/ "github.com"
/ "demo"
/ "demo",
)
package = provider.search_for_directory(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.2"
assert package.requires == [get_dependency("pendulum", ">=1.4.4")]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4")
def test_search_for_directory_setup_read_setup_with_extras(provider, mocker):
mocker.patch("poetry.utils.env.Env.get", return_value=MockEnv())
dependency = DirectoryDependency(
"demo",
Path(__file__).parent.parent
/ "fixtures"
/ "git"
/ "github.com"
/ "demo"
/ "demo",
)
dependency.extras.append("foo")
package = provider.search_for_directory(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.2"
assert package.requires == [
get_dependency("pendulum", ">=1.4.4"),
get_dependency("cleo", optional=True),
]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4")
def test_search_for_directory_setup_read_setup_with_no_dependencies(provider, mocker):
mocker.patch("poetry.utils.env.Env.get", return_value=MockEnv())
dependency = DirectoryDependency(
"demo",
Path(__file__).parent.parent
/ "fixtures"
/ "git"
/ "github.com"
/ "demo"
/ "no-dependencies",
)
package = provider.search_for_directory(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.2"
assert package.requires == []
assert package.extras == {}
def test_search_for_directory_poetry(provider):
dependency = DirectoryDependency(
"demo", Path(__file__).parent.parent / "fixtures" / "project_with_extras"
)
package = provider.search_for_directory(dependency)[0]
assert package.name == "project-with-extras"
assert package.version.text == "1.2.3"
assert package.requires == []
assert package.extras == {
"extras_a": [get_dependency("pendulum", ">=1.4.4")],
"extras_b": [get_dependency("cachy", ">=0.2.0")],
}
def test_search_for_directory_poetry_with_extras(provider):
dependency = DirectoryDependency(
"demo", Path(__file__).parent.parent / "fixtures" / "project_with_extras"
)
dependency.extras.append("extras_a")
package = provider.search_for_directory(dependency)[0]
assert package.name == "project-with-extras"
assert package.version.text == "1.2.3"
assert package.requires == [get_dependency("pendulum", ">=1.4.4")]
assert package.extras == {
"extras_a": [get_dependency("pendulum", ">=1.4.4")],
"extras_b": [get_dependency("cachy", ">=0.2.0")],
}
def test_search_for_file_sdist(provider):
dependency = FileDependency(
"demo",
Path(__file__).parent.parent
/ "fixtures"
/ "distributions"
/ "demo-0.1.0.tar.gz",
)
package = provider.search_for_file(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.0"
assert package.requires == [get_dependency("pendulum", ">=1.4.4")]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
def test_search_for_file_sdist_with_extras(provider):
dependency = FileDependency(
"demo",
Path(__file__).parent.parent
/ "fixtures"
/ "distributions"
/ "demo-0.1.0.tar.gz",
)
dependency.extras.append("foo")
package = provider.search_for_file(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.0"
assert package.requires == [
get_dependency("pendulum", ">=1.4.4"),
get_dependency("cleo", optional=True),
]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
def test_search_for_file_wheel(provider):
dependency = FileDependency(
"demo",
Path(__file__).parent.parent
/ "fixtures"
/ "distributions"
/ "demo-0.1.0-py2.py3-none-any.whl",
)
package = provider.search_for_file(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.0"
assert package.requires == [get_dependency("pendulum", ">=1.4.4")]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
def test_search_for_file_wheel_with_extras(provider):
dependency = FileDependency(
"demo",
Path(__file__).parent.parent
/ "fixtures"
/ "distributions"
/ "demo-0.1.0-py2.py3-none-any.whl",
)
dependency.extras.append("foo")
package = provider.search_for_file(dependency)[0]
assert package.name == "demo"
assert package.version.text == "0.1.0"
assert package.requires == [
get_dependency("pendulum", ">=1.4.4"),
get_dependency("cleo", optional=True),
]
assert package.extras == {
"foo": [get_dependency("cleo")],
"bar": [get_dependency("tomlkit")],
}
| 29.32345
| 87
| 0.646107
|
22914c017cc4c2bae76cc7b6f60e76ed95f9cf20
| 7,515
|
py
|
Python
|
net3.py
|
Linuxfabrik/lib
|
5dfad5fccf4e6e32e5882c9c832c5a42036a6a35
|
[
"Unlicense"
] | 11
|
2022-01-20T14:44:05.000Z
|
2022-03-02T13:08:00.000Z
|
net3.py
|
Linuxfabrik/lib
|
5dfad5fccf4e6e32e5882c9c832c5a42036a6a35
|
[
"Unlicense"
] | 4
|
2022-03-07T16:29:02.000Z
|
2022-03-24T08:49:17.000Z
|
net3.py
|
Linuxfabrik/lib
|
5dfad5fccf4e6e32e5882c9c832c5a42036a6a35
|
[
"Unlicense"
] | 1
|
2022-03-22T19:17:45.000Z
|
2022-03-22T19:17:45.000Z
|
#! /usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://git.linuxfabrik.ch/linuxfabrik-icinga-plugins/checks-linux/-/blob/master/CONTRIBUTING.md
"""Provides network related functions and variables.
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2021092801'
import random
import re
import socket
try:
import netifaces
lib_netifaces = True
except ImportError as e:
lib_netifaces = False
from . import url3 # pylint: disable=C0413
# address family
AF_INET = socket.AF_INET # 2
AF_INET6 = getattr(socket, 'AF_INET6', object()) # 10
AF_UNSPEC = socket.AF_UNSPEC # any kind of connection
try:
AF_UNIX = socket.AF_UNIX
except AttributeError:
# If the AF_UNIX constant is not defined then this protocol is unsupported.
AF_UNIX = None
# socket type
SOCK_TCP = socket.SOCK_STREAM # 1
SOCK_UDP = socket.SOCK_DGRAM # 2
SOCK_RAW = socket.SOCK_RAW
# protocol type
PROTO_TCP = socket.IPPROTO_TCP # 6
PROTO_UDP = socket.IPPROTO_UDP # 17
PROTO_IP = socket.IPPROTO_IP # 0
PROTO_MAP = {
# address family, socket type: proto
(AF_INET, socket.SOCK_STREAM): 'tcp',
(AF_INET, socket.SOCK_DGRAM): 'udp',
(AF_INET6, socket.SOCK_DGRAM): 'udp6',
(AF_INET6, socket.SOCK_STREAM): 'tcp6',
}
FAMILIYSTR = {
# as defined in Python's socketmodule.c
0: 'unspec',
1: 'unix',
2: '4', # inet
3: 'ax25',
4: 'ipx',
5: 'appletalk',
6: 'netrom',
7: 'bridge',
8: 'atmpvc',
9: 'x25',
10: '6', # inet6
11: 'rose',
12: 'decnet',
13: 'netbeui',
14: 'security',
15: 'key',
16: 'route',
17: 'packet',
18: 'ash',
19: 'econet',
20: 'atmsvc',
22: 'sna',
23: 'irda',
24: 'pppox',
25: 'wanpipe',
26: 'llc',
30: 'tipc',
31: 'bluetooth',
}
PROTOSTR = {
# as defined in Python's socketmodule.c
0: 'ip',
1: 'icmp',
2: 'igmp',
6: 'tcp',
8: 'egp',
12: 'pup',
17: 'udp',
22: 'idp',
41: 'ipv6',
43: 'routing',
44: 'fragment',
50: 'esp',
51: 'ah',
58: 'icmpv6',
59: 'none',
60: 'dstopts',
103: 'pim',
255: 'raw',
}
SOCKETSTR = {
# as defined in Python's socketmodule.c
1: 'tcp', # stream
2: 'udp', # dgram
3: 'raw',
4: 'rdm',
5: 'seqpacket',
}
FQDN_REGEX = re.compile(
r"^((?!-)[-A-Z\d]{1,63}(?<!-)\.)+(?!-)[-A-Z\d]{1,63}(?<!-)\.?$", re.IGNORECASE
)
def fetch(host, port, msg=None, timeout=3, ipv6=False):
"""Fetch data via a TCP/IP socket connection. You may optionally send a msg first.
Supports both IPv4 and IPv6.
Taken from https://docs.python.org/3/library/socket.html, enhanced.
"""
try:
if ipv6:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(int(timeout))
s.connect((host, int(port)))
except:
return (False, 'Could not open socket.')
if msg is not None:
try:
s.sendall(msg)
except:
return (False, 'Could not send payload "{}".'.format(msg))
fragments = []
while True:
try:
chunk = s.recv(1024)
if not chunk:
break
fragments.append(chunk)
except socket.timeout as e:
# non-blocking behavior via a time out with socket.settimeout(n)
err = e.args[0]
# this next if/else is a bit redundant, but illustrates how the
# timeout exception is setup
if err == 'timed out':
return (False, 'Socket timed out.')
else:
return (False, 'Can\'t fetch data: {}'.format(e))
except socket.error as e:
# Something else happened, handle error, exit, etc.
return (False, 'Can\'t fetch data: {}'.format(e))
try:
s.close()
except:
s = None
return (True, ''.join(fragments))
def get_ip_public():
"""Retrieve the public IP address from a list of online services.
"""
urls = [
'http://ipv4.icanhazip.com',
'http://ipecho.net/plain',
'http://ipinfo.io/ip'
]
random.shuffle(urls)
ip = None
for url in urls:
success, ip = url3.fetch(url, timeout=2)
if success and ip:
ip = ip.strip()
try:
return (True, ip.decode())
except:
return (True, ip)
return (False, ip)
def get_netinfo():
if lib_netifaces:
# Update stats using the netifaces lib
try:
default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
except (KeyError, AttributeError) as e:
return []
stats = {}
try:
stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr']
stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask']
stats['mask_cidr'] = ip_to_cidr(stats['mask'])
stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
except (KeyError, AttributeError) as e:
return []
stats['public_address'] = None
try:
stats['public_address'] = get_ip_public()
except:
return []
return stats
def ip_to_cidr(ip):
"""Convert IP address to CIDR.
Example: '255.255.255.0' will return 24
"""
# Thanks to @Atticfire
# See https://github.com/nicolargo/glances/issues/1417#issuecomment-469894399
if ip is None:
return 0
return sum(bin(int(x)).count('1') for x in ip.split('.'))
def is_valid_hostname(hostname):
"""True for a validated fully-qualified domain name (FQDN), in full
compliance with RFC 1035, and the "preferred form" specified in RFC
3686 s. 2, whether relative or absolute.
If and only if the FQDN ends with a dot (in place of the RFC1035
trailing null byte), it may have a total length of 254 bytes, still it
must be less than 253 bytes.
https://tools.ietf.org/html/rfc3696#section-2
https://tools.ietf.org/html/rfc1035
from https://github.com/ypcrts/fqdn/blob/develop/fqdn
"""
length = len(hostname)
if hostname.endswith("."):
length -= 1
if length > 253:
return False
return bool(FQDN_REGEX.match(hostname))
def is_valid_relative_hostname(hostname):
"""True for a fully-qualified domain name (FQDN) that is RFC
preferred-form compliant and ends with a `.`.
With relative FQDNS in DNS lookups, the current hosts domain name or
search domains may be appended.
from https://github.com/ypcrts/fqdn/blob/develop/fqdn
"""
return hostname.endswith(".") and is_valid_hostname(hostname)
def is_valid_absolute_hostname(hostname):
"""True for a validated fully-qualified domain name that compiles with the
RFC preferred-form and does not end with a `.`.
from https://github.com/ypcrts/fqdn/blob/develop/fqdn
"""
return not hostname.endswith(".") and is_valid_hostname(hostname)
| 27.228261
| 98
| 0.579375
|
ce2b8f91c4cde9a0a3dcf6af1fe621756003fb1d
| 1,217
|
py
|
Python
|
tests/uploadscript_tests.py
|
ZabeMath/pywikibot
|
856a197c53efcb80b16475a8d203a4ecd79eee2f
|
[
"MIT"
] | 326
|
2017-11-21T07:04:19.000Z
|
2022-03-26T01:25:44.000Z
|
tests/uploadscript_tests.py
|
ZabeMath/pywikibot
|
856a197c53efcb80b16475a8d203a4ecd79eee2f
|
[
"MIT"
] | 17
|
2017-12-20T13:41:32.000Z
|
2022-02-16T16:42:41.000Z
|
tests/uploadscript_tests.py
|
ZabeMath/pywikibot
|
856a197c53efcb80b16475a8d203a4ecd79eee2f
|
[
"MIT"
] | 147
|
2017-11-22T19:13:40.000Z
|
2022-03-29T04:47:07.000Z
|
"""upload.py script test."""
#
# (C) Pywikibot team, 2019-2021
#
# Distributed under the terms of the MIT license.
#
import unittest
from contextlib import suppress
from scripts.upload import CHUNK_SIZE_REGEX, get_chunk_size
from tests.aspects import TestCase
def match(value: str = '') -> int:
"""Create a match object and call get_chunk_site.
:param value: a chunk size value
:return: chunk size in bytes
"""
option = '-chunked'
if value:
option += ':' + value
match = CHUNK_SIZE_REGEX.match(option)
return get_chunk_size(match)
class TestUploadScript(TestCase):
"""Test cases for upload."""
net = False
def test_regex(self):
"""Test CHUNK_SIZE_REGEX and get_chunk_size function."""
self.assertEqual(match(), 1024 ** 2)
self.assertEqual(match('12345'), 12345)
self.assertEqual(match('4567k'), 4567 * 1000)
self.assertEqual(match('7890m'), 7890 * 10 ** 6)
self.assertEqual(match('987ki'), 987 * 1024)
self.assertEqual(match('654mi'), 654 * 1024 ** 2)
self.assertEqual(match('3mike'), 0)
if __name__ == '__main__': # pragma: no cover
with suppress(SystemExit):
unittest.main()
| 25.893617
| 64
| 0.649137
|
a80fe71def9f07c26f2c7a5084929017e089637d
| 4,324
|
py
|
Python
|
pyam/timeseries.py
|
Rlamboll/pyam
|
0045b119aaa0054d18fed812f5c778d0ab7da4cc
|
[
"Apache-2.0"
] | null | null | null |
pyam/timeseries.py
|
Rlamboll/pyam
|
0045b119aaa0054d18fed812f5c778d0ab7da4cc
|
[
"Apache-2.0"
] | null | null | null |
pyam/timeseries.py
|
Rlamboll/pyam
|
0045b119aaa0054d18fed812f5c778d0ab7da4cc
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
import logging
import numpy as np
from pyam.utils import isstr, to_int
logger = logging.getLogger(__name__)
# %%
def fill_series(x, time):
"""Returns the value of a timeseries (indexed over years) for a year or
datetime by linear interpolation.
Parameters
----------
x: pandas.Series
a timeseries to be interpolated
time: int
year or datetime to interpolate
"""
x = x.dropna()
if time in x.index and not np.isnan(x[time]):
return x[time]
else:
prev = [i for i in x.index if i < time]
nxt = [i for i in x.index if i > time]
if prev and nxt:
p = max(prev)
n = min(nxt)
return ((n - time) * x[p] + (time - p) * x[n]) / (n - p)
else:
return np.nan
def cumulative(x, first_year, last_year):
"""Returns the cumulative sum of a timeseries (indexed over years),
implements linear interpolation between years, ignores nan's in the range.
The function includes the last-year value of the series, and
raises a warning if start_year or last_year is outside of
the timeseries range and returns nan
Parameters
----------
x: pandas.Series
a timeseries to be summed over time
first_year: int
first year of the sum
last_year: int
last year of the sum (inclusive)
"""
# if the timeseries does not cover the range `[first_year, last_year]`,
# return nan to avoid erroneous aggregation
if min(x.index) > first_year:
logger.warning('the timeseries `{}` does not start by {}'.format(
x.name or x, first_year))
return np.nan
if max(x.index) < last_year:
logger.warning('the timeseries `{}` does not extend until {}'
.format(x.name or x, last_year))
return np.nan
# make sure we're using integers
to_int(x, index=True)
x[first_year] = fill_series(x, first_year)
x[last_year] = fill_series(x, last_year)
years = [i for i in x.index if i >= first_year and i <= last_year
and ~np.isnan(x[i])]
years.sort()
# loop over years
if not np.isnan(x[first_year]) and not np.isnan(x[last_year]):
value = 0
for (i, yr) in enumerate(years[:-1]):
next_yr = years[i + 1]
# the summation is shifted to include the first year fully in sum,
# otherwise, would return a weighted average of `yr` and `next_yr`
value += ((next_yr - yr - 1) * x[next_yr] +
(next_yr - yr + 1) * x[yr]) / 2
# the loop above does not include the last element in range
# (`last_year`), therefore added explicitly
value += x[last_year]
return value
def cross_threshold(x, threshold=0, direction=['from above', 'from below']):
"""Returns a list of the years in which a timeseries (indexed over years)
crosses a given threshold
Parameters
----------
x: pandas.Series
a timeseries indexed over years
threshold: float, default 0
the threshold that the timeseries is checked against
direction: str, optional, default `['from above', 'from below']`
whether to return all years where the threshold is crossed
or only where threshold is crossed in a specific direction
"""
prev_yr, prev_val = None, None
years = []
direction = [direction] if isstr(direction) else list(direction)
if not set(direction).issubset(set(['from above', 'from below'])):
raise ValueError('invalid direction `{}`'.format(direction))
for yr, val in zip(x.index, x.values):
if np.isnan(val): # ignore nans in the timeseries
continue
if prev_val is None:
prev_yr, prev_val = yr, val
continue
if not np.sign(prev_val - threshold) == np.sign(val - threshold):
if ('from above' in direction and prev_val > val) \
or ('from below' in direction and prev_val < val):
change = (val - prev_val) / (yr - prev_yr)
# add one because int() rounds down
cross_yr = prev_yr + int((threshold - prev_val) / change) + 1
years.append(cross_yr)
prev_yr, prev_val = yr, val
return years
| 34.592
| 78
| 0.598289
|
f00bdc368aac4a98e6ee7bd50ca6e2fcedf4be01
| 6,112
|
py
|
Python
|
xls/tools/codegen_main_test.py
|
ted-xie/xls
|
ef48ade3403fffc6481ffd779e49aa7082ee268f
|
[
"Apache-2.0"
] | null | null | null |
xls/tools/codegen_main_test.py
|
ted-xie/xls
|
ef48ade3403fffc6481ffd779e49aa7082ee268f
|
[
"Apache-2.0"
] | null | null | null |
xls/tools/codegen_main_test.py
|
ted-xie/xls
|
ef48ade3403fffc6481ffd779e49aa7082ee268f
|
[
"Apache-2.0"
] | null | null | null |
# Lint as: python3
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for xls.tools.codegen_main."""
import subprocess
from google.protobuf import text_format
from absl.testing import absltest
from absl.testing import parameterized
from xls.codegen import module_signature_pb2
from xls.common import runfiles
from xls.common import test_base
CODEGEN_MAIN_PATH = runfiles.get_path('xls/tools/codegen_main')
SHA256_IR_PATH = runfiles.get_path('xls/examples/sha256.opt.ir')
NOT_ADD_IR = """package not_add
fn not_add(x: bits[32], y: bits[32]) -> bits[32] {
add.1: bits[32] = add(x, y)
ret not.2: bits[32] = not(add.1)
}
"""
class CodeGenMainTest(parameterized.TestCase):
def test_combinational(self):
ir_file = self.create_tempfile(content=NOT_ADD_IR)
signature_path = test_base.create_named_output_text_file(
'combinational_sig.textproto')
verilog_path = test_base.create_named_output_text_file('combinational.v')
subprocess.check_call([
CODEGEN_MAIN_PATH, '--generator=combinational', '--alsologtostderr',
'--entry=not_add', '--output_signature_path=' + signature_path,
'--output_verilog_path=' + verilog_path, ir_file.full_path
])
with open(verilog_path, 'r') as f:
self.assertIn('module not_add(', f.read())
with open(signature_path, 'r') as f:
sig_proto = text_format.Parse(f.read(),
module_signature_pb2.ModuleSignatureProto())
self.assertEqual(sig_proto.module_name, 'not_add')
self.assertTrue(sig_proto.HasField('combinational'))
def test_combinational_verilog_to_stdout(self):
ir_file = self.create_tempfile(content=NOT_ADD_IR)
verilog = subprocess.check_output([
CODEGEN_MAIN_PATH, '--generator=combinational', '--alsologtostderr',
'--entry=not_add', ir_file.full_path
]).decode('utf-8')
self.assertIn('module not_add(', verilog)
@parameterized.parameters(range(1, 6))
def test_fixed_pipeline_length(self, pipeline_stages):
signature_path = test_base.create_named_output_text_file(
f'sha256.{pipeline_stages}_stage.sig.textproto')
verilog_path = test_base.create_named_output_text_file(
f'sha256.{pipeline_stages}_stage.v')
subprocess.check_call([
CODEGEN_MAIN_PATH, '--generator=pipeline', '--delay_model=unit',
'--pipeline_stages=' + str(pipeline_stages), '--alsologtostderr',
'--output_signature_path=' + signature_path,
'--output_verilog_path=' + verilog_path, SHA256_IR_PATH
])
with open(verilog_path, 'r') as f:
verilog = f.read()
self.assertIn(f'// ===== Pipe stage {pipeline_stages}', verilog)
self.assertNotIn(f'// ===== Pipe stage {pipeline_stages + 1}', verilog)
with open(signature_path, 'r') as f:
sig_proto = text_format.Parse(f.read(),
module_signature_pb2.ModuleSignatureProto())
self.assertTrue(sig_proto.HasField('pipeline'))
self.assertEqual(sig_proto.pipeline.latency, pipeline_stages + 1)
@parameterized.parameters([500, 1000, 1500])
def test_fixed_clock_period(self, clock_period_ps):
verilog_path = test_base.create_named_output_text_file(
f'sha256.clock_{clock_period_ps}_ps.v')
subprocess.check_call([
CODEGEN_MAIN_PATH, '--generator=pipeline', '--delay_model=unit',
'--clock_period_ps=' + str(clock_period_ps), '--alsologtostderr',
'--output_verilog_path=' + verilog_path, SHA256_IR_PATH
])
def test_clock_period_and_pipeline_stages(self):
pipeline_stages = 5
clock_period_ps = 5000
verilog_path = test_base.create_named_output_text_file(
f'sha256.clock_{clock_period_ps}_ps_pipeline_stages_{pipeline_stages}.v'
)
subprocess.check_call([
CODEGEN_MAIN_PATH, '--generator=pipeline', '--delay_model=unit',
'--pipeline_stages=' + str(pipeline_stages),
'--clock_period_ps=' + str(clock_period_ps), '--alsologtostderr',
'--output_verilog_path=' + verilog_path, SHA256_IR_PATH
])
def test_custom_module_name(self):
ir_file = self.create_tempfile(content=NOT_ADD_IR)
verilog = subprocess.check_output([
CODEGEN_MAIN_PATH, '--generator=pipeline', '--delay_model=unit',
'--pipeline_stages=3', '--clock_period_ps=1500', '--alsologtostderr',
'--entry=not_add', '--module_name=foo_qux_baz', ir_file.full_path
]).decode('utf-8')
self.assertIn('module foo_qux_baz(', verilog)
def test_pipeline_system_verilog(self):
verilog_path = test_base.create_named_output_text_file('sha256.sv')
subprocess.check_call([
CODEGEN_MAIN_PATH, '--use_system_verilog', '--generator=pipeline',
'--delay_model=unit', '--pipeline_stages=10', '--alsologtostderr',
'--output_verilog_path=' + verilog_path, SHA256_IR_PATH
])
with open(verilog_path, 'r') as f:
verilog = f.read()
self.assertIn('always_ff', verilog)
self.assertNotIn('always @ (*)', verilog)
def test_pipeline_no_system_verilog(self):
verilog_path = test_base.create_named_output_text_file('sha256.v')
subprocess.check_call([
CODEGEN_MAIN_PATH, '--nouse_system_verilog', '--generator=pipeline',
'--delay_model=unit', '--pipeline_stages=10', '--alsologtostderr',
'--output_verilog_path=' + verilog_path, SHA256_IR_PATH
])
with open(verilog_path, 'r') as f:
verilog = f.read()
self.assertNotIn('always_ff', verilog)
self.assertIn('always @ (posedge clk)', verilog)
if __name__ == '__main__':
absltest.main()
| 38.929936
| 80
| 0.701734
|
e0e8d535dbe9d49c223e329dbf8f9984300d5c4d
| 295
|
py
|
Python
|
endpoint/urls.py
|
mbp76/tasklist-django
|
e2a092ae6e704d5c4bfcacd0df5e4c6753373d40
|
[
"Apache-2.0"
] | 1
|
2017-04-30T11:08:02.000Z
|
2017-04-30T11:08:02.000Z
|
endpoint/urls.py
|
mbp76/django-endpoint
|
e2a092ae6e704d5c4bfcacd0df5e4c6753373d40
|
[
"Apache-2.0"
] | null | null | null |
endpoint/urls.py
|
mbp76/django-endpoint
|
e2a092ae6e704d5c4bfcacd0df5e4c6753373d40
|
[
"Apache-2.0"
] | 1
|
2020-06-24T15:30:11.000Z
|
2020-06-24T15:30:11.000Z
|
"""
URL Configuration
The `urlpatterns` list routes URLs to views. For more information please, see
https://docs.djangoproject.com/en/1.10/topics/http/urls/
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
| 21.071429
| 77
| 0.735593
|
f2670d778a79fe24a69633e5e663cbcdf3db2444
| 1,994
|
py
|
Python
|
con_Emergence.py
|
wbarfuss/EcoPG
|
6b9dfe0c75f2af973ddc505135ac9ba5dabc37eb
|
[
"BSD-2-Clause"
] | 2
|
2021-10-20T09:27:22.000Z
|
2022-01-14T13:48:11.000Z
|
con_Emergence.py
|
wbarfuss/EcoPG
|
6b9dfe0c75f2af973ddc505135ac9ba5dabc37eb
|
[
"BSD-2-Clause"
] | null | null | null |
con_Emergence.py
|
wbarfuss/EcoPG
|
6b9dfe0c75f2af973ddc505135ac9ba5dabc37eb
|
[
"BSD-2-Clause"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
condition for the emergemence of cooperation out of CLD
"""
# %% imports
from aux_CLDoperations import X, Xg
from aux_EcoPG import N, Nd, qci, qcj, qri, qrj, b, c, f, mi, mj
from aux_EcoPG import R, T
from aux_EcoPG import fc_reward_subs
import aux_CLDoperations as cld
import sympy as sp
# %% parameters
y, m, qc, qr = sp.symbols("\gamma m q_c q_r")
X_0o5 = {X[0, 0, 0]: 0.5, X[1, 0, 0]: 0.5}
# %%
def obtain_conEmergence(qc_vs, qr_vs, m_vs, Xsubs, y_vs=[y, y],
reward_subs=fc_reward_subs, b_v=3, c_v=5, f_v=1.2,
R=R, T=T):
# %% R and T
R = R.subs(reward_subs)
T = T.subs(Nd, 0).subs(N, 2)
R = R.subs(Nd, 0).subs(N, 2)
R = R.subs({b: b_v, c: c_v, f: f_v, mi: m_vs[0], mj: m_vs[1]})
T = T.subs({qci: qc_vs[0], qcj: qc_vs[1], qri: qr_vs[0], qrj: qr_vs[1]})
# %%
V0s = cld.obtain_VIs(R=R, T=T, X=Xg.subs(Xsubs), i=0, ys=y_vs)
V1s = cld.obtain_VIs(R=R, T=T, X=Xg.subs(Xsubs), i=1, ys=y_vs)
# %% NextValue of Agent _sa
V00, V01 = sp.symbols("V^0_0 V^0_1")
V0sGen = sp.Matrix([[V00, V01]])
NextV0sa = cld.obtain_NextV0sa(V0sGen, T, Xg.subs(Xsubs))
NextV0sa.simplify()
V10, V11 = sp.symbols("V^1_0 V^1_1")
V1sGen = sp.Matrix([[V10, V11]])
NextV1sa = cld.obtain_NextV1sa(V1sGen, T, Xg.subs(Xsubs))
NextV1sa.simplify()
# %% Risa
Risa = cld.obtain_Risa(R, T, Xg.subs(Xsubs))
R0sa = sp.Matrix(Risa[0, :, :]).reshape(2, 2)
R0sa.simplify()
R1sa = sp.Matrix(Risa[1, :, :]).reshape(2, 2)
R1sa.simplify()
# %% Temporal difference error
td0sa = (1-y_vs[0])*R0sa + y_vs[0]*NextV0sa
td0sa.simplify()
td1sa = (1-y_vs[1])*R1sa + y_vs[1]*NextV1sa
td1sa.simplify()
# %% Ansatz
cond = sp.Eq(td0sa[1, 0]-td0sa[1, 1], td1sa[1, 1]-td1sa[1, 0])
condition = cond.subs(V00, V0s[0]).subs(V01, V0s[1]).\
subs(V10, V1s[0]).subs(V11, V1s[1])
condition = condition.simplify()
return condition
| 29.323529
| 76
| 0.582748
|
e637ba584daa3755b47a9c0da4c4717b22514b8b
| 23,113
|
py
|
Python
|
scripts/cluster/agent.py
|
aliceUnhinged613/microk8s
|
56a91115b40378952f3b16b8bb9bd4b5ed37901c
|
[
"Apache-2.0"
] | 1
|
2020-08-09T18:58:38.000Z
|
2020-08-09T18:58:38.000Z
|
scripts/cluster/agent.py
|
thegirlintheroom613/microk8s
|
56a91115b40378952f3b16b8bb9bd4b5ed37901c
|
[
"Apache-2.0"
] | 16
|
2020-08-25T17:02:09.000Z
|
2022-03-02T03:03:55.000Z
|
scripts/cluster/agent.py
|
thegirlintheroom613/microk8s
|
56a91115b40378952f3b16b8bb9bd4b5ed37901c
|
[
"Apache-2.0"
] | null | null | null |
#!flask/bin/python
import getopt
import json
import os
import random
import shutil
import socket
import string
import subprocess
import sys
import time
import yaml
from .common.utils import (
try_set_file_permissions,
remove_expired_token_from_file,
is_node_running_dqlite,
get_callback_token,
remove_token_from_file,
is_token_expired,
get_dqlite_port,
get_cluster_agent_port,
try_initialise_cni_autodetect_for_clustering,
)
from flask import Flask, jsonify, request, abort, Response
app = Flask(__name__)
CLUSTER_API = "cluster/api/v1.0"
CLUSTER_API_V2 = "cluster/api/v2.0"
snapdata_path = os.environ.get('SNAP_DATA')
snap_path = os.environ.get('SNAP')
cluster_tokens_file = "{}/credentials/cluster-tokens.txt".format(snapdata_path)
callback_token_file = "{}/credentials/callback-token.txt".format(snapdata_path)
callback_tokens_file = "{}/credentials/callback-tokens.txt".format(snapdata_path)
certs_request_tokens_file = "{}/credentials/certs-request-tokens.txt".format(snapdata_path)
default_port = 25000
dqlite_default_port = 19001
default_listen_interface = "0.0.0.0"
def get_service_name(service):
"""
Returns the service name from its configuration file name.
:param service: the name of the service configuration file
:returns: the service name
"""
if service in ["kube-proxy", "kube-apiserver", "kube-scheduler", "kube-controller-manager"]:
return service[len("kube-"), :]
else:
return service
def update_service_argument(service, key, val):
"""
Adds an argument to the arguments file of the service.
:param service: the service
:param key: the argument to add
:param val: the value for the argument
"""
args_file = "{}/args/{}".format(snapdata_path, service)
args_file_tmp = "{}/args/{}.tmp".format(snapdata_path, service)
found = False
with open(args_file_tmp, "w+") as bfp:
with open(args_file, "r+") as fp:
for _, line in enumerate(fp):
if line.startswith(key):
if val is not None:
bfp.write("{}={}\n".format(key, val))
found = True
else:
bfp.write("{}\n".format(line.rstrip()))
if not found and val is not None:
bfp.write("{}={}\n".format(key, val))
try_set_file_permissions(args_file_tmp)
shutil.move(args_file_tmp, args_file)
def store_callback_token(node, callback_token):
"""
Store a callback token
:param node: the node
:param callback_token: the token
"""
tmp_file = "{}.tmp".format(callback_tokens_file)
if not os.path.isfile(callback_tokens_file):
open(callback_tokens_file, 'a+')
os.chmod(callback_tokens_file, 0o600)
with open(tmp_file, "w") as backup_fp:
os.chmod(tmp_file, 0o600)
found = False
with open(callback_tokens_file, 'r+') as callback_fp:
for _, line in enumerate(callback_fp):
if line.startswith(node):
backup_fp.write("{} {}\n".format(node, callback_token))
found = True
else:
backup_fp.write(line)
if not found:
backup_fp.write("{} {}\n".format(node, callback_token))
try_set_file_permissions(tmp_file)
shutil.move(tmp_file, callback_tokens_file)
def sign_client_cert(cert_request, token):
"""
Sign a certificate request
:param cert_request: the request
:param token: a token acting as a request uuid
:returns: the certificate
"""
req_file = "{}/certs/request.{}.csr".format(snapdata_path, token)
sign_cmd = (
"openssl x509 -sha256 -req -in {csr} -CA {SNAP_DATA}/certs/ca.crt -CAkey"
" {SNAP_DATA}/certs/ca.key -CAcreateserial -out {SNAP_DATA}/certs/server.{token}.crt"
" -days 365".format(csr=req_file, SNAP_DATA=snapdata_path, token=token)
)
with open(req_file, 'w') as fp:
fp.write(cert_request)
subprocess.check_call(sign_cmd.split())
with open(
"{SNAP_DATA}/certs/server.{token}.crt".format(SNAP_DATA=snapdata_path, token=token)
) as fp:
cert = fp.read()
return cert
def add_token_to_certs_request(token):
"""
Add a token to the file holding the nodes we expect a certificate request from
:param token: the token
"""
with open(certs_request_tokens_file, "a+") as fp:
fp.write("{}\n".format(token))
def get_token(name):
"""
Get token from known_tokens file
:param name: the name of the node
:returns: the token or None(if name doesn't exist)
"""
file = "{}/credentials/known_tokens.csv".format(snapdata_path)
with open(file) as fp:
for _, line in enumerate(fp):
if name in line:
parts = line.split(',')
return parts[0].rstrip()
return None
def add_kubelet_token(hostname):
"""
Add a token for a node in the known tokens
:param hostname: the name of the node
:returns: the token added
"""
file = "{}/credentials/known_tokens.csv".format(snapdata_path)
old_token = get_token("system:node:{}".format(hostname))
if old_token:
return old_token.rstrip()
alpha = string.ascii_letters + string.digits
token = ''.join(random.SystemRandom().choice(alpha) for _ in range(32))
uid = ''.join(random.SystemRandom().choice(string.digits) for _ in range(8))
with open(file, 'a') as fp:
# TODO double check this format. Why is userid unique?
line = "{},system:node:{},kubelet-{},\"system:nodes\"".format(token, hostname, uid)
fp.write(line + os.linesep)
return token.rstrip()
def getCA():
"""
Return the CA
:returns: the CA file contents
"""
ca_file = "{}/certs/ca.crt".format(snapdata_path)
with open(ca_file) as fp:
ca = fp.read()
return ca
def get_arg(key, file):
"""
Get an argument from an arguments file
:param key: the argument we look for
:param file: the arguments file to search in
:returns: the value of the argument or None(if the key doesn't exist)
"""
filename = "{}/args/{}".format(snapdata_path, file)
with open(filename) as fp:
for _, line in enumerate(fp):
if line.startswith(key):
args = line.split(' ')
args = args[-1].split('=')
return args[-1].rstrip()
return None
def is_valid(token_line, token_type=cluster_tokens_file):
"""
Check whether a token is valid
:param token: token to be checked
:param token_type: the type of token (bootstrap or signature)
:returns: True for a valid token, False otherwise
"""
token = token_line.strip()
# Ensure token is not empty
if not token:
return False
with open(token_type) as fp:
for _, line in enumerate(fp):
token_in_file = line.strip()
if "|" in line:
if not is_token_expired(line):
token_in_file = line.strip().split('|')[0]
if token == token_in_file:
return True
return False
def read_kubelet_args_file(node=None):
"""
Return the contents of the kubelet arguments file
:param node: node to add a host override (defaults to None)
:returns: the kubelet args file
"""
filename = "{}/args/kubelet".format(snapdata_path)
with open(filename) as fp:
args = fp.read()
if node:
args = "{}--hostname-override {}".format(args, node)
return args
def get_node_ep(hostname, remote_addr):
"""
Return the endpoint to be used for the node based by trying to resolve the hostname provided
:param hostname: the provided hostname
:param remote_addr: the address the request came from
:returns: the node's location
"""
try:
socket.gethostbyname(hostname)
return hostname
except socket.gaierror:
return remote_addr
return remote_addr
@app.route('/{}/join'.format(CLUSTER_API), methods=['POST'])
def join_node_etcd():
"""
Web call to join a node to the cluster
"""
if request.headers['Content-Type'] == 'application/json':
token = request.json['token']
hostname = request.json['hostname']
port = request.json['port']
callback_token = request.json['callback']
else:
token = request.form['token']
hostname = request.form['hostname']
port = request.form['port']
callback_token = request.form['callback']
# Remove expired tokens
remove_expired_token_from_file(cluster_tokens_file)
if not is_valid(token):
error_msg = {"error": "Invalid token"}
return Response(json.dumps(error_msg), mimetype='application/json', status=500)
if is_node_running_dqlite():
msg = (
"Failed to join the cluster. This is an HA dqlite cluster. \n"
"Please, retry after enabling HA on this joining node with 'microk8s enable ha-cluster'."
)
error_msg = {"error": msg}
return Response(json.dumps(error_msg), mimetype='application/json', status=501)
add_token_to_certs_request(token)
# remove token for backwards compatibility way of adding a node
remove_token_from_file(token, cluster_tokens_file)
node_addr = get_node_ep(hostname, request.remote_addr)
node_ep = "{}:{}".format(node_addr, port)
store_callback_token(node_ep, callback_token)
ca = getCA()
etcd_ep = get_arg('--listen-client-urls', 'etcd')
api_port = get_arg('--secure-port', 'kube-apiserver')
proxy_token = get_token('kube-proxy')
kubelet_token = add_kubelet_token(node_addr)
subprocess.check_call("snapctl restart microk8s.daemon-apiserver".split())
if node_addr != hostname:
kubelet_args = read_kubelet_args_file(node_addr)
else:
kubelet_args = read_kubelet_args_file()
return jsonify(
ca=ca,
etcd=etcd_ep,
kubeproxy=proxy_token,
apiport=api_port,
kubelet=kubelet_token,
kubelet_args=kubelet_args,
hostname_override=node_addr,
)
@app.route('/{}/sign-cert'.format(CLUSTER_API), methods=['POST'])
def sign_cert():
"""
Web call to sign a certificate
"""
if request.headers['Content-Type'] == 'application/json':
token = request.json['token']
cert_request = request.json['request']
else:
token = request.form['token']
cert_request = request.form['request']
token = token.strip()
if not is_valid(token, certs_request_tokens_file):
error_msg = {"error": "Invalid token"}
return Response(json.dumps(error_msg), mimetype='application/json', status=500)
if is_node_running_dqlite():
error_msg = {"error": "Not possible to join. This is an HA dqlite cluster."}
return Response(json.dumps(error_msg), mimetype='application/json', status=501)
remove_token_from_file(token, certs_request_tokens_file)
signed_cert = sign_client_cert(cert_request, token)
return jsonify(certificate=signed_cert)
@app.route('/{}/configure'.format(CLUSTER_API), methods=['POST'])
def configure():
"""
Web call to configure the node
"""
if request.headers['Content-Type'] == 'application/json':
callback_token = request.json['callback']
configuration = request.json
else:
callback_token = request.form['callback']
configuration = json.loads(request.form['configuration'])
callback_token = callback_token.strip()
if not is_valid(callback_token, callback_token_file):
error_msg = {"error": "Invalid token"}
return Response(json.dumps(error_msg), mimetype='application/json', status=500)
# We expect something like this:
'''
{
"callback": "xyztoken"
"service":
[
{
"name": "kubelet",
"arguments_remove":
[
"myoldarg"
],
"arguments_update":
[
{"myarg": "myvalue"},
{"myarg2": "myvalue2"},
{"myarg3": "myvalue3"}
],
"restart": False
},
{
"name": "kube-proxy",
"restart": True
}
],
"addon":
[
{
"name": "gpu",
"enable": True
},
{
"name": "gpu",
"disable": True
}
]
}
'''
if "service" in configuration:
for service in configuration["service"]:
print("{}".format(service["name"]))
if "arguments_update" in service:
print("Updating arguments")
for argument in service["arguments_update"]:
for key, val in argument.items():
print("{} is {}".format(key, val))
update_service_argument(service["name"], key, val)
if "arguments_remove" in service:
print("Removing arguments")
for argument in service["arguments_remove"]:
print("{}".format(argument))
update_service_argument(service["name"], argument, None)
if "restart" in service and service["restart"]:
service_name = get_service_name(service["name"])
print("restarting {}".format(service["name"]))
subprocess.check_call(
"snapctl restart microk8s.daemon-{}".format(service_name).split()
)
if "addon" in configuration:
for addon in configuration["addon"]:
print("{}".format(addon["name"]))
if "enable" in addon and addon["enable"]:
print("Enabling {}".format(addon["name"]))
subprocess.check_call(
"{}/microk8s-enable.wrapper {}".format(snap_path, addon["name"]).split()
)
if "disable" in addon and addon["disable"]:
print("Disabling {}".format(addon["name"]))
subprocess.check_call(
"{}/microk8s-disable.wrapper {}".format(snap_path, addon["name"]).split()
)
resp_date = {"result": "ok"}
resp = Response(json.dumps(resp_date), status=200, mimetype='application/json')
return resp
def get_dqlite_voters():
"""
Get the voting members of the dqlite cluster
:param : the list with the voting members
"""
snapdata_path = "/var/snap/microk8s/current"
cluster_dir = "{}/var/kubernetes/backend".format(snapdata_path)
waits = 10
print("Waiting for access to cluster.", end=" ", flush=True)
while waits > 0:
try:
with open("{}/info.yaml".format(cluster_dir)) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
out = subprocess.check_output(
"{snappath}/bin/dqlite -s file://{dbdir}/cluster.yaml -c {dbdir}/cluster.crt "
"-k {dbdir}/cluster.key -f json k8s .cluster".format(
snappath=snap_path, dbdir=cluster_dir
).split(),
timeout=4,
)
if data['Address'] in out.decode():
break
else:
print(".", end=" ", flush=True)
time.sleep(5)
waits -= 1
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
print("..", end=" ", flush=True)
time.sleep(2)
waits -= 1
print(" ")
if waits == 0:
raise Exception("Could not get cluster info")
nodes = json.loads(out.decode())
voters = []
for n in nodes:
if n["Role"] == 0:
voters.append(n["Address"])
return voters
def update_dqlite_ip(host):
"""
Update dqlite so it listens on the default interface and not on localhost
:param : the host others see for this node
"""
dqlite_port = get_dqlite_port()
subprocess.check_call("snapctl stop microk8s.daemon-apiserver".split())
time.sleep(10)
cluster_dir = "{}/var/kubernetes/backend".format(snapdata_path)
# TODO make the port configurable
update_data = {'Address': "{}:{}".format(host, dqlite_port)}
with open("{}/update.yaml".format(cluster_dir), 'w') as f:
yaml.dump(update_data, f)
subprocess.check_call("snapctl start microk8s.daemon-apiserver".split())
time.sleep(10)
attempts = 12
while True:
voters = get_dqlite_voters()
if len(voters) > 0 and not voters[0].startswith("127.0.0.1"):
break
else:
time.sleep(5)
attempts -= 1
if attempts <= 0:
break
def get_cert(certificate):
"""
Return the data of the certificate
:returns: the certificate file contents
"""
cert_file = "{}/certs/{}".format(snapdata_path, certificate)
with open(cert_file) as fp:
cert = fp.read()
return cert
def get_cluster_certs():
"""
Return the cluster certificates
:returns: the cluster certificate files
"""
file = "{}/var/kubernetes/backend/cluster.crt".format(snapdata_path)
with open(file) as fp:
cluster_cert = fp.read()
file = "{}/var/kubernetes/backend/cluster.key".format(snapdata_path)
with open(file) as fp:
cluster_key = fp.read()
return cluster_cert, cluster_key
@app.route('/{}/join'.format(CLUSTER_API_V2), methods=['POST'])
def join_node_dqlite():
"""
Web call to join a node to the cluster
"""
if request.headers['Content-Type'] == 'application/json':
token = request.json['token']
hostname = request.json['hostname']
port = request.json['port']
else:
token = request.form['token']
hostname = request.form['hostname']
port = request.form['port']
if not is_valid(token):
error_msg = {"error": "Invalid token"}
return Response(json.dumps(error_msg), mimetype='application/json', status=500)
if not is_node_running_dqlite():
error_msg = {"error": "Not possible to join. This is not an HA dqlite cluster."}
return Response(json.dumps(error_msg), mimetype='application/json', status=501)
agent_port = get_cluster_agent_port()
if port != agent_port:
error_msg = {
"error": "The port of the cluster agent has to be set to {}.".format(agent_port)
}
return Response(json.dumps(error_msg), mimetype='application/json', status=502)
voters = get_dqlite_voters() # type: List[str]
# Check if we need to set dqlite with external IP
if len(voters) == 1 and voters[0].startswith("127.0.0.1"):
update_dqlite_ip(request.host.split(":")[0])
voters = get_dqlite_voters()
callback_token = get_callback_token()
remove_token_from_file(token, cluster_tokens_file)
node_addr = request.remote_addr
api_port = get_arg('--secure-port', 'kube-apiserver')
kubelet_args = read_kubelet_args_file()
cluster_cert, cluster_key = get_cluster_certs()
# Make sure calico can autodetect the right interface for packet routing
try_initialise_cni_autodetect_for_clustering(node_addr, apply_cni=True)
return jsonify(
ca=get_cert("ca.crt"),
ca_key=get_cert("ca.key"),
service_account_key=get_cert("serviceaccount.key"),
cluster_cert=cluster_cert,
cluster_key=cluster_key,
voters=voters,
callback_token=callback_token,
apiport=api_port,
kubelet_args=kubelet_args,
hostname_override=node_addr,
admin_token=get_token('admin'),
)
@app.route('/{}/upgrade'.format(CLUSTER_API), methods=['POST'])
def upgrade():
"""
Web call to upgrade the node
"""
callback_token = request.json['callback']
callback_token = callback_token.strip()
if not is_valid(callback_token, callback_token_file):
error_msg = {"error": "Invalid token"}
return Response(json.dumps(error_msg), mimetype='application/json', status=500)
upgrade_request = request.json["upgrade"]
phase = request.json["phase"]
# We expect something like this:
'''
{
"callback": "xyztoken"
"phase": "prepare", "commit" or "rollback"
"upgrade": "XYZ-upgrade-name"
}
'''
if phase == "prepare":
upgrade_script = '{}/upgrade-scripts/{}/prepare-node.sh'.format(snap_path, upgrade_request)
if not os.path.isfile(upgrade_script):
print("Not ready to execute {}".format(upgrade_script))
resp_data = {"result": "not ok"}
resp = Response(json.dumps(resp_data), status=404, mimetype='application/json')
return resp
else:
print("Executing {}".format(upgrade_script))
subprocess.check_call(upgrade_script)
resp_data = {"result": "ok"}
resp = Response(json.dumps(resp_data), status=200, mimetype='application/json')
return resp
elif phase == "commit":
upgrade_script = '{}/upgrade-scripts/{}/commit-node.sh'.format(snap_path, upgrade_request)
print("Ready to execute {}".format(upgrade_script))
print("Executing {}".format(upgrade_script))
subprocess.check_call(upgrade_script)
resp_data = {"result": "ok"}
resp = Response(json.dumps(resp_data), status=200, mimetype='application/json')
return resp
elif phase == "rollback":
upgrade_script = '{}/upgrade-scripts/{}/rollback-node.sh'.format(snap_path, upgrade_request)
print("Ready to execute {}".format(upgrade_script))
print("Executing {}".format(upgrade_script))
subprocess.check_call(upgrade_script)
resp_data = {"result": "ok"}
resp = Response(json.dumps(resp_data), status=200, mimetype='application/json')
return resp
def usage():
print("Agent responsible for setting up a cluster. Arguments:")
print(
"-l, --listen: interfaces to listen to (defaults to {})".format(default_listen_interface)
)
print("-p, --port: port to listen to (default {})".format(default_port))
if __name__ == '__main__':
server_cert = "{SNAP_DATA}/certs/server.crt".format(SNAP_DATA=snapdata_path)
server_key = "{SNAP_DATA}/certs/server.key".format(SNAP_DATA=snapdata_path)
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "hl:p:", ["help", "listen=", "port="])
except getopt.GetoptError as err:
print(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
port = default_port
listen = default_listen_interface
for o, a in opts:
if o in ("-l", "--listen"):
listen = a
if o in ("-p", "--port"):
port = a
elif o in ("-h", "--help"):
usage()
sys.exit(1)
else:
assert False, "unhandled option"
app.run(host=listen, port=port, ssl_context=(server_cert, server_key))
| 33.113181
| 101
| 0.613508
|
a392304a1c1e0383a5ceaf94855be9fb866c6c27
| 2,825
|
py
|
Python
|
test/functional/rpc_spork.py
|
CortezDevTeam/encocoin
|
638030888618b8b4572a809706346e3297b5cbb7
|
[
"MIT"
] | 1
|
2020-10-04T15:43:15.000Z
|
2020-10-04T15:43:15.000Z
|
test/functional/rpc_spork.py
|
CortezDevTeam/encocoin
|
638030888618b8b4572a809706346e3297b5cbb7
|
[
"MIT"
] | null | null | null |
test/functional/rpc_spork.py
|
CortezDevTeam/encocoin
|
638030888618b8b4572a809706346e3297b5cbb7
|
[
"MIT"
] | 3
|
2020-06-07T22:05:26.000Z
|
2020-08-31T18:10:54.000Z
|
#!/usr/bin/env python3
# Copyright (c) 2019 The EncoCoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# -*- coding: utf-8 -*-
from time import sleep
from test_framework.test_framework import EncoCoinTestFramework
from test_framework.util import set_node_times, assert_equal
class EncoCoin_RPCSporkTest(EncoCoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args = [['-staking=1']] * self.num_nodes
self.extra_args[0].append('-sporkkey=932HEevBSujW2ud7RfB1YF91AFygbBRQj3de3LyaCRqNzKKgWXi')
def setup_chain(self):
# Start with clean chain
self._initialize_chain_clean()
self.enable_mocktime()
def log_title(self):
title = "*** Starting %s ***" % self.__class__.__name__
underline = "-" * len(title)
description = "Performs tests on the Spork RPC"
self.log.info("\n\n%s\n%s\n%s\n", title, underline, description)
def run_test(self):
self.log_title()
set_node_times(self.nodes, self.mocktime)
sporkName = "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT"
# 0 - check SPORK 8 status from node 1 (must be inactive)
assert_equal(False, self.is_spork_active(1, sporkName))
# 1 - activate SPORK 8 with nodes[0]
assert_equal("success", self.activate_spork(0, sporkName))
sleep(1)
# check SPORK 8 status from nodes[1] (must be active)
assert_equal(True, self.is_spork_active(1, sporkName))
# 2 - Adjust time to 1 sec in the future and deactivate SPORK 8 with node[0]
self.mocktime += 1
set_node_times(self.nodes, self.mocktime)
assert_equal("success", self.deactivate_spork(0, sporkName))
sleep(1)
# check SPORK 8 value from nodes[1] (must be inactive again)
assert_equal(False, self.is_spork_active(1, sporkName))
# 3 - Adjust time to 1 sec in the future and set new value (mocktime) for SPORK 8 with node[0]
self.mocktime += 1
set_node_times(self.nodes, self.mocktime)
assert_equal("success", self.set_spork(0, sporkName, self.mocktime))
sleep(1)
# check SPORK 8 value from nodes[1] (must be equal to mocktime)
assert_equal(self.mocktime, self.get_spork(1, sporkName))
# 4 - Stop nodes and check value again after restart
self.log.info("Stopping nodes...")
self.stop_nodes()
self.log.info("Restarting node 1...")
self.start_node(1, [])
assert_equal(self.mocktime, self.get_spork(1, sporkName))
self.log.info("%s: TEST PASSED" % self.__class__.__name__)
if __name__ == '__main__':
EncoCoin_RPCSporkTest().main()
| 37.666667
| 102
| 0.668319
|
fa5e18ff877a90f22409d67e866a6b4f0b2a7bee
| 4,514
|
py
|
Python
|
tools/hits_ratios_graph.py
|
matus-chochlik/ctcache
|
59f5c6c75a9d204c70cddce81b61d24bb13ef94a
|
[
"BSL-1.0"
] | 9
|
2020-12-17T18:56:03.000Z
|
2022-02-08T08:23:34.000Z
|
tools/hits_ratios_graph.py
|
matus-chochlik/ctcache
|
59f5c6c75a9d204c70cddce81b61d24bb13ef94a
|
[
"BSL-1.0"
] | 3
|
2021-04-12T14:58:58.000Z
|
2021-04-14T15:42:53.000Z
|
tools/hits_ratios_graph.py
|
matus-chochlik/ctcache
|
59f5c6c75a9d204c70cddce81b61d24bb13ef94a
|
[
"BSL-1.0"
] | null | null | null |
#!/usr/bin/python3 -B
# coding=utf8
# Copyright (c) 2020 Matus Chochlik
# Distributed under the Boost Software License, Version 1.0.
# See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt
# ------------------------------------------------------------------------------
# Data from http://ctcache:port/stats/ctcache.json can be used as input.
import os
import sys
import json
import math
import argparse
import matplotlib.pyplot as plt
# ------------------------------------------------------------------------------
class ArgParser(argparse.ArgumentParser):
# --------------------------------------------------------------------------
def _valid_pixdim(self, x):
try:
i = int(x)
assert i > 16
return i
except:
self.error("`%s' is not a valid frame size" % str(x))
# --------------------------------------------------------------------------
def _valid_bands(self, x):
try:
i = int(x)
assert i > 1
return i
except:
self.error("`%s' is not a valid number of bands " % str(x))
# --------------------------------------------------------------------------
def __init__(self, **kw):
argparse.ArgumentParser.__init__(self, **kw)
self.add_argument(
'-i', '--input',
metavar='INPUT-FILE',
dest='input_path',
nargs='?',
type=os.path.realpath
)
self.add_argument(
'-o', '--output',
metavar='OUTPUT-FILE',
dest='output_path',
nargs='?',
type=os.path.realpath,
default="/tmp/ctcache.avi"
)
self.add_argument(
'-W', '--width',
metavar='NUMBER',
dest='width',
nargs='?',
type=self._valid_pixdim,
default=1200
)
self.add_argument(
'-H', '--height',
metavar='NUMBER',
dest='height',
nargs='?',
type=self._valid_pixdim,
default=800
)
self.add_argument(
'-B', '--bands',
metavar='NUMBER',
dest='bands',
nargs='?',
type=self._valid_bands,
default=None
)
# --------------------------------------------------------------------------
def make_options(self):
return self.parse_args()
# ------------------------------------------------------------------------------
def make_argparser():
return ArgParser(prog=os.path.basename(__file__))
# ------------------------------------------------------------------------------
def render_chart(options):
stats = json.load(open(options.input_path, "rt", encoding="utf8"))
get_hist = lambda s: {int(k): v for k, v in s.get("hit_count_histogram", {}).items()}
max_hits = int(max(max(get_hist(s).keys()) for s in stats))
mh_norm = 1.0 / max_hits
clamp = lambda t : tuple(max(min(x, 1), 0) for x in t)
make_color = lambda a,b: clamp((math.sqrt(1.0-a)*b, math.sqrt(a)*b, 0.0))
mh = range(max_hits)
y = [[] for u in mh]
if options.bands is not None:
nb = options.bands
b = [0.8 + 0.2 * math.sqrt((i+1) / nb) for i in range(nb)]
else:
b = [1.0]
c = [make_color((i+1) * mh_norm, b[i % len(b)]) for i in mh]
for stat in stats:
hist = {k-1: k*v for k, v in get_hist(stat).items()}
try:
norm = 1.0 / sum(hist.values())
for i in mh:
y[i].append(hist.get(i, 0.0) * norm)
except ZeroDivisionError:
for i in mh:
y[i].append(1.0 / max_hits)
x = range(len(y[0]))
plt.style.use('dark_background')
fig, spl = plt.subplots()
w_dpi = options.width/float(fig.dpi)
h_dpi = options.height/float(fig.dpi)
fig.set_size_inches(w_dpi, h_dpi)
spl.set_xlabel("Time (non-linear)")
spl.set_ylabel("Hit ratios")
spl.stackplot(x, y, colors=c, edgecolors=(0.5, 0.5, 0.5), linewidth=0.0)
plt.show()
# ------------------------------------------------------------------------------
def main():
render_chart(make_argparser().make_options())
return 0
# ------------------------------------------------------------------------------
if __name__ == "__main__":
exit(main())
# ------------------------------------------------------------------------------
| 31.131034
| 89
| 0.429331
|
643506556a1fb737c7b2351803f1c2bd095e2855
| 1,173
|
py
|
Python
|
runtests.py
|
comandrei/django-shortcircuit
|
a6ab5b5631a753830ae4fe0f6500adf4ea6c4634
|
[
"BSD-3-Clause"
] | 1
|
2019-03-20T10:09:48.000Z
|
2019-03-20T10:09:48.000Z
|
runtests.py
|
comandrei/django-shortcircuit
|
a6ab5b5631a753830ae4fe0f6500adf4ea6c4634
|
[
"BSD-3-Clause"
] | null | null | null |
runtests.py
|
comandrei/django-shortcircuit
|
a6ab5b5631a753830ae4fe0f6500adf4ea6c4634
|
[
"BSD-3-Clause"
] | 1
|
2019-05-09T12:19:57.000Z
|
2019-05-09T12:19:57.000Z
|
import sys
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="shortcircuit.urls",
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"shortcircuit",
],
SITE_ID=1,
MIDDLEWARE_CLASSES=(),
)
try:
import django
setup = django.setup
except AttributeError:
pass
else:
setup()
except ImportError:
import traceback
traceback.print_exc()
raise ImportError("To fix this error, run: pip install -r requirements-test.txt")
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
# Run tests
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests(test_args)
if failures:
sys.exit(bool(failures))
if __name__ == '__main__':
run_tests(*sys.argv[1:])
| 20.946429
| 85
| 0.57971
|
ebacc77b25258106e9a2e66b334ccefd5d535782
| 438
|
py
|
Python
|
meta/scripts/uninstall.py
|
daephx/dotfiles
|
842959c13a000c0f259bdd4df81bbbf8e5f9248e
|
[
"MIT"
] | null | null | null |
meta/scripts/uninstall.py
|
daephx/dotfiles
|
842959c13a000c0f259bdd4df81bbbf8e5f9248e
|
[
"MIT"
] | null | null | null |
meta/scripts/uninstall.py
|
daephx/dotfiles
|
842959c13a000c0f259bdd4df81bbbf8e5f9248e
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
from __future__ import print_function
import yaml
import os
CONFIG="meta/base.yaml"
stream = open(CONFIG, "r")
conf = yaml.load(stream, yaml.FullLoader)
for section in conf:
if 'link' in section:
for target in section['link']:
realpath = os.path.expanduser(target)
if os.path.islink(realpath):
print("Removing ", realpath)
os.unlink(realpath)
| 21.9
| 49
| 0.630137
|
840484af1b52e54ce3caf21cbba5eba67bcdaadc
| 429
|
py
|
Python
|
photo/migrations/0003_image_created_at.py
|
leon-bi/foto_ops
|
3b58cddaa329c2f49124a9a1f2fc8ee85143c189
|
[
"Unlicense"
] | null | null | null |
photo/migrations/0003_image_created_at.py
|
leon-bi/foto_ops
|
3b58cddaa329c2f49124a9a1f2fc8ee85143c189
|
[
"Unlicense"
] | 6
|
2020-06-06T00:24:31.000Z
|
2021-09-08T01:25:04.000Z
|
photo/migrations/0003_image_created_at.py
|
Bchizi/foto_ops
|
3b58cddaa329c2f49124a9a1f2fc8ee85143c189
|
[
"Unlicense"
] | null | null | null |
# Generated by Django 2.2.6 on 2019-11-10 14:59
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photo', '0002_auto_20191108_1237'),
]
operations = [
migrations.AddField(
model_name='image',
name='created_at',
field=models.DateField(blank=True, default=datetime.datetime.now),
),
]
| 21.45
| 78
| 0.622378
|
808673b77dfa909f9dca9be1ad5692b575177df5
| 403
|
py
|
Python
|
backend/writers/serializers.py
|
Nikita-Sherstnev/writers-vue-app
|
f3c9342306d55e0bb503b62d7450c6ee132ca301
|
[
"MIT"
] | null | null | null |
backend/writers/serializers.py
|
Nikita-Sherstnev/writers-vue-app
|
f3c9342306d55e0bb503b62d7450c6ee132ca301
|
[
"MIT"
] | null | null | null |
backend/writers/serializers.py
|
Nikita-Sherstnev/writers-vue-app
|
f3c9342306d55e0bb503b62d7450c6ee132ca301
|
[
"MIT"
] | null | null | null |
from rest_framework import serializers
from writers.models import Writer
class WriterSerializer(serializers.ModelSerializer):
class Meta:
model = Writer
fields = ['id',
'surname',
'name',
'middlename',
'birthYear',
'deathYear',
'amountOfBooks',
'nobel']
| 23.705882
| 52
| 0.486352
|
6d2b35fe36eef1f9bbdc595b24f63012ef94578d
| 132
|
py
|
Python
|
scripts/portal/market13.py
|
Snewmy/swordie
|
ae01ed4ec0eb20a18730e8cd209eea0b84a8dd17
|
[
"MIT"
] | 9
|
2021-04-26T11:59:29.000Z
|
2021-12-20T13:15:27.000Z
|
scripts/portal/market13.py
|
Snewmy/swordie
|
ae01ed4ec0eb20a18730e8cd209eea0b84a8dd17
|
[
"MIT"
] | null | null | null |
scripts/portal/market13.py
|
Snewmy/swordie
|
ae01ed4ec0eb20a18730e8cd209eea0b84a8dd17
|
[
"MIT"
] | 6
|
2021-07-14T06:32:05.000Z
|
2022-02-06T02:32:56.000Z
|
# Magatia (261000000) / NLC Town Center (600000000) => Free Market
sm.setReturnField()
sm.setReturnPortal()
sm.warp(910000000, 36)
| 26.4
| 67
| 0.742424
|
0ed3f86649af2eb513851d355928e9c4ddd76d3e
| 3,404
|
py
|
Python
|
script.module.streamlink.base/resources/lib/streamlink/plugins/tga.py
|
bobbybark/tantrumrepo
|
1451c481254d3fedec9f430139d18db7312a9b1a
|
[
"Beerware"
] | 3
|
2020-03-03T13:21:44.000Z
|
2021-07-21T09:53:31.000Z
|
script.module.streamlink.base/resources/lib/streamlink/plugins/tga.py
|
eggman19/tantrumrepo
|
1451c481254d3fedec9f430139d18db7312a9b1a
|
[
"Beerware"
] | null | null | null |
script.module.streamlink.base/resources/lib/streamlink/plugins/tga.py
|
eggman19/tantrumrepo
|
1451c481254d3fedec9f430139d18db7312a9b1a
|
[
"Beerware"
] | 1
|
2018-08-30T20:04:34.000Z
|
2018-08-30T20:04:34.000Z
|
#coding: utf-8
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http, validate
from streamlink.plugin.api.utils import parse_query
from streamlink.stream import HLSStream, HTTPStream, RTMPStream
CHANNEL_INFO_URL = "http://api.plu.cn/tga/streams/%s"
QQ_STREAM_INFO_URL = "http://info.zb.qq.com/?cnlid=%d&cmd=2&stream=%d&system=1&sdtfrom=113"
PLU_STREAM_INFO_URL = "http://livestream.plu.cn/live/getlivePlayurl?roomId=%d"
_quality_re = re.compile(r"\d+x(\d+)$")
_url_re = re.compile(r"http://(star|y)\.longzhu\.(?:tv|com)/(m\/)?(?P<domain>[a-z0-9]+)")
_channel_schema = validate.Schema(
{
"data": validate.any(None, {
"channel": validate.any(None, {
"id": int,
"vid": int
})
})
},
validate.get("data")
)
_plu_schema = validate.Schema(
{
"playLines": [{
"urls": [{
"securityUrl": validate.url(scheme=validate.any("rtmp", "http")),
"resolution": validate.text,
"ext": validate.text
}]
}]
}
)
_qq_schema = validate.Schema(
{
validate.optional("playurl"): validate.url(scheme="http")
},
validate.get("playurl")
)
STREAM_WEIGHTS = {
"middle": 540,
"source": 1080
}
class Tga(Plugin):
@classmethod
def can_handle_url(self, url):
return _url_re.match(url)
@classmethod
def stream_weight(cls, stream):
if stream in STREAM_WEIGHTS:
return STREAM_WEIGHTS[stream], "tga"
return Plugin.stream_weight(stream)
def _get_quality(self, label):
match = _quality_re.search(label)
if match:
return match.group(1) + "p"
else:
return "live"
def _get_channel_id(self, domain):
channel_info = http.get(CHANNEL_INFO_URL % str(domain))
info = http.json(channel_info, schema=_channel_schema)
if info is None:
return 0, 0
return info['channel']['vid'], info['channel']['id']
def _get_qq_streams(self, vid):
res = http.get(QQ_STREAM_INFO_URL % (vid, 1))
info = http.json(res, schema=_qq_schema)
yield "live", HTTPStream(self.session, info)
res = http.get(QQ_STREAM_INFO_URL % (vid, 2))
info = http.json(res, schema=_qq_schema)
yield "live", HLSStream(self.session, info)
def _get_plu_streams(self, cid):
res = http.get(PLU_STREAM_INFO_URL % cid)
info = http.json(res, schema=_plu_schema)
for source in info["playLines"][0]["urls"]:
quality = self._get_quality(source["resolution"])
if source["ext"] == "m3u8":
yield quality, HLSStream(self.session, source["securityUrl"])
elif source["ext"] == "flv":
yield quality, HTTPStream(self.session, source["securityUrl"])
elif source["ext"] == "rtmp":
yield quality, RTMPStream(self.session, {
"rtmp": source["securityUrl"],
"live": True
})
def _get_streams(self):
match = _url_re.match(self.url)
domain = match.group('domain')
vid, cid = self._get_channel_id(domain)
if vid != 0:
return self._get_qq_streams(vid)
elif cid != 0:
return self._get_plu_streams(cid)
__plugin__ = Tga
| 29.344828
| 91
| 0.583431
|
ccd1909529709cf366ae1acac1353e850ce4488e
| 23,550
|
py
|
Python
|
conjureup/utils.py
|
iMichka/conjure-up
|
8e4599e6f58b52163384150d8d71e7802462d126
|
[
"MIT"
] | 1
|
2015-11-09T17:21:22.000Z
|
2015-11-09T17:21:22.000Z
|
conjureup/utils.py
|
iMichka/conjure-up
|
8e4599e6f58b52163384150d8d71e7802462d126
|
[
"MIT"
] | null | null | null |
conjureup/utils.py
|
iMichka/conjure-up
|
8e4599e6f58b52163384150d8d71e7802462d126
|
[
"MIT"
] | null | null | null |
import asyncio
import codecs
import errno
import json
import logging
import os
import pty
import re
import shutil
import socket
import subprocess
import sys
import uuid
from collections import Mapping
from contextlib import contextmanager
from functools import partial
from itertools import chain
from pathlib import Path
from subprocess import PIPE, Popen, check_call, check_output
import aiofiles
from pkg_resources import parse_version
from raven.processors import SanitizePasswordsProcessor
from termcolor import cprint
from conjureup import consts
from conjureup.app_config import app
from conjureup.models.metadata import SpellMetadata
from conjureup.telemetry import track_event
@contextmanager
def chdir(directory):
"""Change the current working directory to a different directory for a code
block and return the previous directory after the block exits. Useful to
run commands from a specificed directory.
:param str directory: The directory path to change to for this context.
"""
cur = os.getcwd()
try:
yield os.chdir(directory)
finally:
os.chdir(cur)
def run(cmd, **kwargs):
""" Compatibility function to support python 3.4
"""
try:
from subprocess import run as _run
return _run(cmd, **kwargs)
except ImportError:
if 'check' in kwargs:
del kwargs['check']
return check_call(cmd, **kwargs)
else:
return check_output(cmd, **kwargs)
def run_script(path, stderr=PIPE, stdout=PIPE):
return run(path, shell=True, stderr=stderr, stdout=stdout, env=app.env)
def run_attach(cmd, output_cb=None):
""" run command and attach output to cb
Arguments:
cmd: shell command
output_cb: where to display output
"""
stdoutmaster, stdoutslave = pty.openpty()
subproc = Popen(cmd, shell=True,
stdout=stdoutslave,
stderr=PIPE)
os.close(stdoutslave)
decoder = codecs.getincrementaldecoder('utf-8')()
def last_ten_lines(s):
chunk = s[-1500:]
lines = chunk.splitlines(True)
return ''.join(lines[-10:]).replace('\r', '')
decoded_output = ""
try:
while subproc.poll() is None:
try:
b = os.read(stdoutmaster, 512)
except OSError as e:
if e.errno != errno.EIO:
raise
break
else:
final = False
if not b:
final = True
decoded_chars = decoder.decode(b, final)
if decoded_chars is None:
continue
decoded_output += decoded_chars
if output_cb:
ls = last_ten_lines(decoded_output)
output_cb(ls)
if final:
break
finally:
os.close(stdoutmaster)
if subproc.poll() is None:
subproc.kill()
subproc.wait()
errors = [l.decode('utf-8') for l in subproc.stderr.readlines()]
if output_cb:
output_cb(last_ten_lines(decoded_output))
errors = ''.join(errors)
if subproc.returncode == 0:
return decoded_output.strip()
else:
raise Exception("Problem running {0} "
"{1}:{2}".format(cmd,
subproc.returncode,
errors))
async def arun(cmd, input=None, check=False, env=None, encoding='utf8',
stdin=PIPE, stdout=PIPE, stderr=PIPE, cb_stdout=None,
cb_stderr=None, **kwargs):
""" Run a command using asyncio.
If ``stdout`` or ``stderr`` are strings, they will treated as filenames
and the data from the proces will be written (streamed) to them. In this
case, ``cb_stdout`` and ``cb_stderr`` can be given as callbacks to call
with each line from the respective handle.
:param list cmd: List containing the command to run, plus any args.
:param dict **kwargs:
"""
env = dict(app.env, **(env or {}))
outf = None
errf = None
try:
if isinstance(stdout, str):
outf = await aiofiles.open(stdout, 'w')
stdout = PIPE
if isinstance(stderr, str):
errf = await aiofiles.open(stderr, 'w')
stderr = PIPE
proc = await asyncio.create_subprocess_exec(*cmd,
stdin=stdin,
stdout=stdout,
stderr=stderr,
env=env,
**kwargs)
data = {}
async def tstream(source_name, sink, ui_cb):
source = getattr(proc, source_name)
while proc.returncode is None:
async for line in source:
line = line.decode(encoding)
if ui_cb:
ui_cb(line)
data.setdefault(source_name, []).append(line)
if sink:
await sink.write(line)
await sink.flush()
await asyncio.sleep(0.01)
tasks = []
if input:
if isinstance(input, str):
input = input.encode(encoding)
tasks.append(proc._feed_stdin(input))
if proc.stdout:
tasks.append(tstream('stdout', outf, cb_stdout))
if proc.stderr:
tasks.append(tstream('stderr', errf, cb_stderr))
await asyncio.gather(*tasks)
await proc.wait()
finally:
if outf:
await outf.close()
if errf:
await errf.close()
stdout_data = ''.join(data.get('stdout', [])) if proc.stdout else None
stderr_data = ''.join(data.get('stderr', [])) if proc.stderr else None
if check and proc.returncode != 0:
raise subprocess.CalledProcessError(proc.returncode,
cmd, stdout_data, stderr_data)
return (proc.returncode, stdout_data, stderr_data)
def sentry_report(message=None, exc_info=None, tags=None, **kwargs):
app.loop.run_in_executor(None, partial(_sentry_report,
message, exc_info, tags, **kwargs))
def _sentry_report(message=None, exc_info=None, tags=None, **kwargs):
if app.no_report:
return
try:
default_tags = {
'spell': app.config.get('spell'),
'cloud_type': app.provider.cloud_type if app.provider else None,
'region': app.provider.region if app.provider else None,
'jaas': app.is_jaas,
'headless': app.headless,
'juju_version': juju_version()
}
if message is not None and exc_info is None:
event_type = 'raven.events.Message'
kwargs['message'] = message
if 'level' not in kwargs:
kwargs['level'] = logging.WARNING
else:
event_type = 'raven.events.Exception'
if exc_info is None or exc_info is True:
kwargs['exc_info'] = sys.exc_info()
else:
kwargs['exc_info'] = exc_info
if 'level' not in kwargs:
kwargs['level'] = logging.ERROR
kwargs['tags'] = dict(default_tags, **(tags or {}))
app.sentry.capture(event_type, **kwargs)
except Exception:
pass
async def can_sudo(password=None):
if not password and app.sudo_pass:
password = app.sudo_pass
if password:
opt = '-S' # stdin
password = '{}\n'.format(password).encode('utf8')
else:
opt = '-n' # non-interactive
proc = await asyncio.create_subprocess_exec('sudo', opt, '/bin/true',
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
if password:
await proc.communicate(password)
else:
await proc.wait()
return proc.returncode == 0
def juju_version():
""" Get current Juju version
"""
cmd = run_script('{} version'.format(app.juju.bin_path))
if cmd.returncode == 0:
return parse_version(cmd.stdout.decode().strip())
else:
raise Exception("Could not determine Juju version.")
def snap_version():
""" Get snap version
"""
cmd = run_script('snap version')
if cmd.returncode == 0:
name_version_str = cmd.stdout.decode().splitlines()[0]
try:
name, version = name_version_str.split()
if '~' in version:
version, series = version.split('~')
return parse_version(version)
except:
raise Exception("Could not determine Snap version.")
def send_msg(msg, label, color, attrs=['bold']):
if app.conjurefile['color'] == 'auto':
colorized = sys.__stdout__.isatty()
elif app.conjurefile['color'] == 'always':
colorized = True
else:
colorized = False
if app.conjurefile['debug']:
print("[{}] {}".format(label, msg))
elif colorized:
cprint("[{}] ".format(label),
color,
attrs=attrs,
end="{}\n".format(msg), flush=True)
else:
print("[{}] {}".format(label, msg), flush=True)
def info(msg):
send_msg(msg, 'info', 'green')
def error(msg):
send_msg(msg, 'error', 'red')
def warning(msg):
send_msg(msg, 'warning', 'yellow')
def install_home():
""" returns installer user home
"""
return os.path.expanduser("~" + install_user())
def juju_path():
""" returns juju path for $user
"""
return os.getenv('JUJU_DATA',
os.path.expanduser('~/.local/share/juju'))
def mkdir(path):
if not os.path.isdir(path):
os.makedirs(path)
chown(path, install_user(), recursive=True)
def _normalize_bundle(original_bundle, overlay_bundle):
""" Normalizes top level application/services keys
"""
if 'applications' in original_bundle and 'services' in overlay_bundle:
overlay_bundle['applications'] = overlay_bundle.pop('services')
if 'services' in original_bundle and 'applications' in overlay_bundle:
overlay_bundle['services'] = overlay_bundle.pop('applications')
def merge_dicts(*dicts):
"""
Return a new dictionary that is the result of merging the arguments
together.
In case of conflicts, later arguments take precedence over earlier
arguments.
ref: http://stackoverflow.com/a/8795331/3170835
"""
updated = {}
# grab all keys
keys = set()
for d in dicts:
keys = keys.union(set(d))
for key in keys:
values = [d[key] for d in dicts if key in d]
# which ones are mapping types? (aka dict)
maps = [value for value in values if isinstance(value, Mapping)]
lists = [value for value in values if isinstance(value, (list, tuple))]
if maps:
# if we have any mapping types, call recursively to merge them
updated[key] = merge_dicts(*maps)
elif lists:
# if any values are lists, we want to merge them (non-recursively)
# first, ensure all values are lists
for i in range(len(values)):
if not isinstance(values[i], (list, tuple)):
values[i] = [values[i]]
# then, merge all of the lists into a single list
updated[key] = list(chain.from_iterable(values))
else:
# otherwise, just grab the last value we have, since later
# arguments take precedence over earlier arguments
updated[key] = values[-1]
return updated
def subtract_dicts(*dicts):
"""
Return a new dictionary that is the result of subtracting each dict
from the previous. Except for mappings, the values of the subsequent
are ignored and simply all matching keys are removed. If the value is
a mapping, however, then only the keys from the sub-mapping are removed,
recursively.
"""
result = merge_dicts(dicts[0], {}) # make a deep copy
for d in dicts[1:]:
for key, value in d.items():
if key not in result:
continue
if isinstance(value, Mapping):
result[key] = subtract_dicts(result[key], value)
if not result[key]:
# we removed everything from the mapping,
# so remove the whole thing
del result[key]
elif isinstance(value, (list, tuple)):
if not isinstance(result[key], (list, tuple)):
# if the original value isn't a list, then remove it
# if it matches any of the values in the given list
if result[key] in value:
del result[key]
else:
# for lists, remove any matching items (non-recursively)
result[key] = [item
for item in result[key]
if item not in value]
if not result[key]:
# we removed everything from the list,
# so remove the whole thing
del result[key]
else:
del result[key]
return result
def chown(path, user, group=None, recursive=False):
""" Change user/group ownership of file
Arguments:
path: path of file or directory
user: new owner username
group: new owner group name
recursive: set files/dirs recursively
"""
if group is None:
group = user
try:
if not recursive or os.path.isfile(path):
shutil.chown(path, user, group)
else:
for root, dirs, files in os.walk(path):
shutil.chown(root, user, group)
for item in dirs:
shutil.chown(os.path.join(root, item), user, group)
for item in files:
shutil.chown(os.path.join(root, item), user, group)
except OSError as e:
raise e
def spew(path, data, owner=None):
""" Writes data to path
Arguments:
path: path of file to write to
data: contents to write
owner: optional owner of file
"""
with open(path, 'w') as f:
f.write(data)
if owner:
try:
chown(path, owner)
except:
raise Exception(
"Unable to set ownership of {}".format(path))
def slurp(path):
""" Reads data from path
Arguments:
path: path of file
"""
try:
with path.open() as f:
return f.read().strip()
except IOError:
raise IOError
def install_user():
""" returns current user
"""
user = os.getenv('USER', None)
if user is None:
raise Exception("Unable to determine current user.")
return user
def set_chosen_spell(spell_name, spell_dir):
track_event("Spell Choice", spell_name, "")
app.env['CONJURE_UP_SPELL'] = spell_name
app.config.update({'spell-dir': spell_dir,
'spell': spell_name})
def set_spell_metadata():
app.metadata = SpellMetadata.load(
Path(app.config['spell-dir']) / 'metadata.yaml')
def get_spell_metadata(spell):
""" Returns metadata about spell
"""
metadata_path = Path(app.config['spells-dir']) / spell / 'metadata.yaml'
return SpellMetadata.load(metadata_path)
def __available_on_darwin(key):
""" Returns True if spell is available on macOS
"""
metadata = get_spell_metadata(key)
if metadata.cloud_whitelist \
and 'localhost' in metadata.cloud_whitelist:
return False
if metadata.spell_type == consts.spell_types.SNAP:
return False
return True
def find_spells():
""" Find spells, excluding localhost only and snap spells if not linux
"""
_spells = []
for category, cat_dict in app.spells_index.items():
for sd in cat_dict['spells']:
if is_darwin() and not __available_on_darwin(sd['key']):
continue
_spells.append((category, sd))
return _spells
def find_addons_matching(key):
if key in app.addons_aliases:
return app.addons_aliases[key]
return {}
def find_spells_matching(key):
if key in app.spells_index:
_spells = []
for sd in app.spells_index[key]['spells']:
if is_darwin() and not __available_on_darwin(sd['key']):
continue
_spells.append((key, sd))
return _spells
for category, d in app.spells_index.items():
for spell in d['spells']:
if spell['key'] == key:
if is_darwin() and not __available_on_darwin(spell['key']):
continue
return [(category, spell)]
return []
def get_options_whitelist(service_name):
"""returns list of whitelisted option names.
If there is no whitelist, returns []
"""
metadata = app.metadata
if metadata is None:
return []
options_whitelist = metadata.options_whitelist
if options_whitelist is None:
return []
svc_opts_whitelist = options_whitelist.get(service_name, [])
return svc_opts_whitelist
def gen_hash():
""" generates a UUID
"""
return str(uuid.uuid4()).split('-')[0][:3]
def gen_model():
""" generates a unique model name
"""
name = "conjure-{}".format(app.env['CONJURE_UP_SPELL'])
return "{}-{}".format(name[:24], gen_hash())
def gen_cloud():
""" generates a unique cloud
"""
name = "cloud-{}".format(app.provider.cloud_type)
return "{}-{}".format(name[:24], gen_hash())
def is_darwin():
""" Checks if host platform is macOS
"""
return sys.platform.startswith('darwin')
def is_linux():
""" Checks if host platform is linux
"""
return sys.platform.startswith('linux')
def is_valid_hostname(hostname):
""" Checks if a hostname is valid
Graciously taken from http://stackoverflow.com/a/2532344/3170835
"""
if len(hostname) > 255:
return False
if hostname[-1] == ".":
# strip exactly one dot from the right, if present
hostname = hostname[:-1]
allowed = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE)
return all(allowed.match(x) for x in hostname.split("."))
def set_terminal_title(title):
""" Sets the terminal title
"""
sys.stdout.write("\x1b]2;{}\x07".format(title))
def get_physical_network_interfaces():
""" Returns a list of physical network interfaces
We whitelist eth due to some instances where users run
conjure-up inside a single LXD container. At that point
all devices are considered virtual and all network device
naming follows the ethX pattern.
"""
sys_class_net = Path('/sys/class/net')
devices = []
for device in sys_class_net.glob("*"):
parts = str(device.resolve()).split('/')
if "virtual" in parts and not parts[-1].startswith('eth'):
continue
try:
if not get_physical_network_ipaddr(device.name):
continue
except Exception:
continue
devices.append(device.name)
if len(devices) == 0:
raise Exception(
"Could not find a suitable physical network interface "
"to create a LXD bridge on. Please check your network "
"configuration.")
return sorted(devices)
def get_physical_network_ipaddr(iface):
""" Gets an IP Address for network device, ipv4 only
Arguments:
iface: interface to query
"""
out = run_script('ip addr show {}'.format(iface))
if out.returncode != 0:
raise Exception(
"Could not determine an IPv4 address for {}".format(iface))
app.log.debug("Parsing {} for IPv4 address".format(
out.stdout.decode('utf8')))
try:
ipv4_addr = out.stdout.decode(
'utf8').split('inet ')[1].split('/')[0]
except IndexError:
return None
return ipv4_addr
def get_open_port():
""" Gets an unused port
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
s.listen(1)
port = s.getsockname()[1]
s.close()
return port
class IterQueue(asyncio.Queue):
"""
Queue subclass that supports the ``async for`` syntax.
When the producer is done adding items, it must call `close` to
notify the consumer.
Example::
queue = IterQueue()
async def consumer():
async for line in queue:
print(line)
async def producer():
with open('filename') as fp:
for line in fp:
await queue.put(line)
queue.close()
"""
def __init__(self, *args, **kwargs):
self.sentinal = []
super().__init__(*args, **kwargs)
def __aiter__(self):
return self
async def __anext__(self):
item = await self.get()
if item is self.sentinal:
raise StopAsyncIteration
return item
async def close(self):
await self.put(self.sentinal)
class SanitizeDataProcessor(SanitizePasswordsProcessor):
"""
Sanitize data sent to Sentry.
Performs the same santiziations as the SanitizePasswordsProcessor, but
also sanitizes values.
"""
def sanitize(self, key, value):
value = super().sanitize(key, value)
if value is None:
return value
def _check_str(s):
sl = s.lower()
for field in self.KEYS:
if field not in sl:
continue
if 'invalid' in s or 'error' in s:
return '***(contains invalid {})***'.format(field)
else:
return '***(contains {})***'.format(field)
return s
if isinstance(value, str):
# handle basic strings
value = _check_str(value)
elif isinstance(value, bytes):
# handle bytes
value = _check_str(value.decode('utf8', 'replace'))
elif isinstance(value, (list, tuple, set)):
# handle list-like
orig_type = type(value)
value = list(value)
for i, item in enumerate(value):
value[i] = self.sanitize(key, item)
value = orig_type(value)
elif isinstance(value, dict):
# handle dicts
for key, value in value.items():
value[key] = self.sanitize(key, value)
else:
# handle everything else by sanitizing its JSON encoding
# note that we don't want to use the JSON encoded value if it's
# not being santizied, because it will end up double-encoded
value_json = json.dumps(value)
sanitized = _check_str(value_json)
if sanitized != value_json:
value = sanitized
return value
class TestError(Exception):
def __init__(self):
super().__init__('This is a dummy error for testing reporting')
class SudoError(Exception):
pass
class UtilsHTTPError(Exception):
pass
| 29.77244
| 79
| 0.573036
|
ba507421d8f9c3f1233785244e5dbc1354d0f23e
| 866
|
py
|
Python
|
var/spack/repos/builtin/packages/py-pep517/package.py
|
jeanbez/spack
|
f4e51ce8f366c85bf5aa0eafe078677b42dae1ba
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null |
var/spack/repos/builtin/packages/py-pep517/package.py
|
jeanbez/spack
|
f4e51ce8f366c85bf5aa0eafe078677b42dae1ba
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 8
|
2021-11-09T20:28:40.000Z
|
2022-03-15T03:26:33.000Z
|
var/spack/repos/builtin/packages/py-pep517/package.py
|
jeanbez/spack
|
f4e51ce8f366c85bf5aa0eafe078677b42dae1ba
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 2
|
2019-02-08T20:37:20.000Z
|
2019-03-31T15:19:26.000Z
|
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class PyPep517(PythonPackage):
"""Wrappers to build Python packages using PEP 517 hooks."""
homepage = "https://github.com/pypa/pep517"
pypi = "pep517/pep517-0.12.0.tar.gz"
version('0.12.0', sha256='931378d93d11b298cf511dd634cf5ea4cb249a28ef84160b3247ee9afb4e8ab0')
depends_on('py-flit-core@2:3', type='build')
depends_on('py-toml', when='^python@:3.5', type=('build', 'run'))
depends_on('py-tomli@1.1:', when='^python@3.6:', type=('build', 'run'))
depends_on('py-importlib-metadata', when='^python@:3.7', type=('build', 'run'))
depends_on('py-zipp', when='^python@:3.7', type=('build', 'run'))
| 39.363636
| 96
| 0.683603
|
dd720c816d93af55600e1f69aa4f28e34dfc5a53
| 989
|
py
|
Python
|
hub/sensorhub/migrations/0005_user_agent.py
|
kblum/sensor-hub
|
6b766ca59be74ae1a8d3d42afe048d04b6a0c546
|
[
"MIT"
] | null | null | null |
hub/sensorhub/migrations/0005_user_agent.py
|
kblum/sensor-hub
|
6b766ca59be74ae1a8d3d42afe048d04b6a0c546
|
[
"MIT"
] | null | null | null |
hub/sensorhub/migrations/0005_user_agent.py
|
kblum/sensor-hub
|
6b766ca59be74ae1a8d3d42afe048d04b6a0c546
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sensorhub', '0004_deployment_description'),
]
operations = [
migrations.CreateModel(
name='UserAgent',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
('created', models.DateTimeField(editable=False)),
('modified', models.DateTimeField(editable=False)),
('user_agent_string', models.TextField(unique=True, db_index=True)),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='reading',
name='user_agent',
field=models.ForeignKey(blank=True, null=True, to='sensorhub.UserAgent', on_delete=models.SET_NULL),
),
]
| 30.90625
| 114
| 0.57634
|
45e352c25d2731ce5e6b7174f320c27cc01a4286
| 3,222
|
py
|
Python
|
src/core/annotate.py
|
1stDayHack/1stdaykit
|
ce381cfb24a1a60a72624cb7d57d4bf8a1420c83
|
[
"MIT"
] | 5
|
2020-12-05T02:27:23.000Z
|
2021-06-28T00:50:20.000Z
|
src/core/annotate.py
|
1stDayHack/1stdaykit
|
ce381cfb24a1a60a72624cb7d57d4bf8a1420c83
|
[
"MIT"
] | 1
|
2020-12-04T05:03:59.000Z
|
2020-12-26T06:22:23.000Z
|
src/core/annotate.py
|
1stDayHack/1stdaykit
|
ce381cfb24a1a60a72624cb7d57d4bf8a1420c83
|
[
"MIT"
] | 6
|
2020-12-04T06:16:01.000Z
|
2020-12-06T03:57:57.000Z
|
### Import modules
import torch
import torch.nn.functional as F
import numpy as np
import json
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import skimage.transform
import argparse
import warnings
from imageio import imread
from PIL import Image
from pprint import pprint
from .base_libs.ImageCaptioner.caption import visualize_att, caption_image_beam_search
from .utils import utils
from .base import BaseClass
class ImageAnnotater(BaseClass):
def __init__(self, name='Show_Attend_Tell Image Annotation', beam_size=5, device="cpu"):
super().__init__(name)
print("Warning! Module broken due to PyTorch 1.7 upgrades. Depracated for now.")
#Init name and metadata
self.name = name
self.device = device.lower()
# self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
self.beam_size = beam_size
#Suppress annoying printouts | Dangerous :p
warnings.filterwarnings("ignore")
#Define paths
self.base_pth = 'src/core/base_libs/ImageCaptioner/weights/'
self.encoder_pth = self.base_pth + 'encoder.pth'
self.decoder_pth = self.base_pth + 'decoder.pth'
self.wordmap_pth = self.base_pth + 'WORDMAP_coco_5_cap_per_img_5_min_word_freq.json'
#Create net, decoder and encoder.
self.decoder = torch.load(self.decoder_pth)
self.decoder = self.decoder.to(self.device)
self.decoder.eval()
self.encoder = torch.load(self.encoder_pth)
self.encoder = self.encoder.to(self.device)
self.encoder.eval()
#Load word map (word2ix)
with open(self.wordmap_pth, 'r') as j: self.word_map = json.load(j)
self.rev_word_map = {v: k for k, v in self.word_map.items()} # ix2word
def predict(self,image):
"""
Does image annotation on a single image. In order to perform batch inference,
you can either call this predict() function in a for-loop or alternatively (advanced)
try to modify this predict() function to perform batch-inferencing.
Input:
image: PIL Image in array format.
Output:
predictions: list object. Generated text.
"""
#Infer | Encode, decode with attention and beam search
seq, alphas = caption_image_beam_search(self.encoder,
self.decoder,
image,
self.word_map,
self.beam_size)
#Parse
alphas = torch.FloatTensor(alphas)
words = [self.rev_word_map[ind] for ind in seq]
output = (words,alphas)
return output
def visualize(self,image,output):
"""
Simple function to call pretty-print for a neater text representation.
Input:
image: PIL object.
output: tuple of (seq,alphas) from predict() function.
Output:
None
"""
#Visualize
words,alphas = output
visualize_att(image, words, alphas, True)
| 28.767857
| 93
| 0.616698
|
b8b7c6da12e0bbb4139ec3f25764bf3e03ffaf59
| 6,542
|
py
|
Python
|
dojo/tools/arachni/parser.py
|
sebbrandt87/django-DefectDojo
|
e8c152a4270d0ee4701db3804ea1de9bf58a0fe5
|
[
"BSD-3-Clause"
] | 11
|
2018-02-25T09:51:58.000Z
|
2022-02-18T13:42:32.000Z
|
dojo/tools/arachni/parser.py
|
sebbrandt87/django-DefectDojo
|
e8c152a4270d0ee4701db3804ea1de9bf58a0fe5
|
[
"BSD-3-Clause"
] | 102
|
2016-09-12T03:47:41.000Z
|
2022-01-20T07:34:18.000Z
|
dojo/tools/arachni/parser.py
|
sebbrandt87/django-DefectDojo
|
e8c152a4270d0ee4701db3804ea1de9bf58a0fe5
|
[
"BSD-3-Clause"
] | 40
|
2015-11-23T12:58:29.000Z
|
2022-01-20T06:41:16.000Z
|
from __future__ import with_statement
import json
import re
from base64 import b64encode
from urlparse import urlparse
import html2text
from dojo.models import Finding, Endpoint
from django.utils.encoding import smart_text, force_str
__author__ = "Jay Paz"
class ArachniJSONParser(object):
def __init__(self, json_output, test):
self.target = None
self.port = "80"
self.host = None
tree = self.parse_json(json_output)
if tree:
self.items = [data for data in self.get_items(tree, test)]
else:
self.items = []
def parse_json(self, json_output):
try:
tree = json.load(json_output)
except:
raise Exception("Invalid format")
return tree
def get_items(self, tree, test):
bugtype = ""
items = {}
issues = tree['issues']
for node in issues:
item = get_item(node, test)
dupe_key = str(item.url) + item.severity + item.title
if dupe_key in items:
items[dupe_key].unsaved_endpoints = items[dupe_key].unsaved_endpoints + item.unsaved_endpoints
items[dupe_key].unsaved_req_resp = items[dupe_key].unsaved_req_resp + item.unsaved_req_resp
# make sure only unique endpoints are retained
unique_objs = []
new_list = []
for o in items[dupe_key].unsaved_endpoints:
if o.__unicode__() in unique_objs:
continue
new_list.append(o)
unique_objs.append(o.__unicode__())
items[dupe_key].unsaved_endpoints = new_list
else:
items[dupe_key] = item
return items.values()
def do_clean(value):
myreturn = ""
if value is not None:
if len(value) > 0:
for x in value:
myreturn += x.text
return myreturn
def get_item(item_node, test):
if 'vector' in item_node and 'action' in item_node['vector']:
url = item_node['vector']['action']
else:
url = item_node['response']['url']
o = urlparse(url)
"""
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
params='', query='', fragment='')
"""
rhost = re.search(
"(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))[\:]*([0-9]+)*([/]*($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+)).*?$",
url)
protocol = o.scheme
host = o.netloc
path = o.path
query = o.query
fragment = o.fragment
port = 80
if protocol == 'https':
port = 443
if rhost.group(11) is not None:
port = rhost.group(11)
request = item_node['request']
#
req = ''
#
for key, value in request.iteritems():
req += str(key) + ": " + str(value) + "\n\n"
#
respz = item_node['response']
resp = ''
for key, value in respz.iteritems():
if key != 'body':
resp += str(key) + ": " + str(value) + "\n\n"
resp += "\n\n\n" + force_str(respz['body'])
unsaved_req_resp = list()
if request is not None and respz is not None:
unsaved_req_resp.append({"req": b64encode(req), "resp": b64encode(resp)})
try:
dupe_endpoint = Endpoint.objects.get(protocol=protocol,
host=host + (":" + port) if port is not None else "",
query=query,
fragment=fragment,
path=path,
product=test.engagement.product)
except:
dupe_endpoint = None
if not dupe_endpoint:
endpoint = Endpoint(protocol=protocol,
host=host + (":" + str(port)) if port is not None else "",
query=query,
fragment=fragment,
path=path,
product=test.engagement.product)
else:
endpoint = dupe_endpoint
if not dupe_endpoint:
endpoints = [endpoint]
else:
endpoints = [endpoint, dupe_endpoint]
background = item_node['description'] if 'description' in item_node else None
if background:
background = html2text.html2text(background)
remediation = item_node['remedy_guidance'] if 'remedy_guidance' in item_node else 'n/a'
if remediation:
remediation = html2text.html2text(remediation)
references = item_node['references'].values() if 'references' in item_node else None
references = '<br/><br/>'.join(reference for reference in references)
if references:
references = html2text.html2text(references)
severity = item_node['severity'].capitalize() if 'severity' in item_node else 'Info'
if severity == 'Informational':
severity == 'Info'
cwe = item_node['cwe'] if 'cwe' in item_node else None
tags = item_node['tags'] if 'tags' in item_node else None
if tags:
tags = ', '.join(tag for tag in tags)
digest = item_node['digest']
# Finding and Endpoint objects returned have not been saved to the database
finding = Finding(title=item_node['name'] + " (" + str(digest) + ")",
url=url,
test=test,
severity=severity,
description=background + "\n\n",
mitigation=remediation,
references=references,
active=False,
verified=False,
false_p=False,
duplicate=False,
out_of_scope=False,
mitigated=None,
impact="No impact provided",
numerical_severity=Finding.get_numerical_severity(severity),
cwe=cwe)
finding.unsaved_endpoints = endpoints
finding.unsaved_req_resp = unsaved_req_resp
finding.unsaved_tags = tags
return finding
| 32.874372
| 530
| 0.535005
|
5d2cfa96734abe2fa38608836f127e5906847e25
| 2,061
|
py
|
Python
|
decisiontree/multitenancy/utils.py
|
datamade/rapidsms-decisiontree-app
|
7613a43f1bb17ffcd6d5a5d6d6f93ad9c09bd2a6
|
[
"BSD-3-Clause"
] | 1
|
2018-08-23T06:29:23.000Z
|
2018-08-23T06:29:23.000Z
|
decisiontree/multitenancy/utils.py
|
datamade/rapidsms-decisiontree-app
|
7613a43f1bb17ffcd6d5a5d6d6f93ad9c09bd2a6
|
[
"BSD-3-Clause"
] | 9
|
2018-08-07T20:37:52.000Z
|
2018-12-28T17:17:16.000Z
|
decisiontree/multitenancy/utils.py
|
datamade/rapidsms-decisiontree-app
|
7613a43f1bb17ffcd6d5a5d6d6f93ad9c09bd2a6
|
[
"BSD-3-Clause"
] | null | null | null |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db.models import Q
def multitenancy_enabled():
return "decisiontree.multitenancy" in settings.INSTALLED_APPS
def get_tenants_for_user(user):
"""Return all tenants that the user can manage."""
from multitenancy.models import Tenant
tenants = Tenant.objects.all()
if not user.is_superuser:
user_is_manager = Q(tenantrole__user=user) | Q(group__tenantrole__user=user)
tenants = tenants.filter(user_is_manager)
return tenants
def get_link_class_from_model(model):
"""Get the tenant link model associated with the model class."""
# ModelClass.tenantlink is the reverse of a OneToOneField.
# Traverse the field hierarchy to try to retrieve the link model.
model_class = model if isinstance(model, type) else type(model)
link_field = getattr(model_class, 'tenantlink', None)
if link_field:
related = getattr(link_field, 'related', None)
if related:
link_model = getattr(related, 'model', None)
from multitenancy.models import TenantEnabled
if link_model and issubclass(link_model, TenantEnabled):
return link_model
raise TypeError("This method should only be used on tenant-enabled models.")
def is_multitent_model(model):
"""Return whether the model class is for a multitenancy model."""
try:
get_link_class_from_model(model)
except TypeError:
return False
else:
return True
def tenancy_reverse(request, url_name, *args, **kwargs):
"""Add tenancy information to the URL reversal if multitenancy is enabled."""
if multitenancy_enabled():
# reverse disallows mixing *args and **kwargs.
if args:
args = (request.group_slug, request.tenant_slug) + tuple(args)
else:
kwargs.setdefault('group_slug', request.group_slug)
kwargs.setdefault('tenant_slug', request.tenant_slug)
return reverse(url_name, args=args, kwargs=kwargs)
| 36.803571
| 84
| 0.701116
|
7ba964928cc146e05a45a13a5d911e2295db5d1a
| 769
|
py
|
Python
|
110. Balanced Binary Tree.py
|
rohitpatwa/leetcode
|
f4826763e8f154cac9134d53b154b8299acd39a8
|
[
"Xnet",
"X11",
"CECILL-B"
] | 1
|
2020-07-15T20:48:27.000Z
|
2020-07-15T20:48:27.000Z
|
110. Balanced Binary Tree.py
|
rohitpatwa/leetcode
|
f4826763e8f154cac9134d53b154b8299acd39a8
|
[
"Xnet",
"X11",
"CECILL-B"
] | null | null | null |
110. Balanced Binary Tree.py
|
rohitpatwa/leetcode
|
f4826763e8f154cac9134d53b154b8299acd39a8
|
[
"Xnet",
"X11",
"CECILL-B"
] | null | null | null |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
return False if self.helper(root)==-1 else True
def helper(self, node):
if not node:
return 0
left_height = self.helper(node.left)
if left_height == -1:
return -1
right_height = self.helper(node.right)
if right_height == -1:
return -1
if abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1
| 26.517241
| 55
| 0.514954
|
1811394daa51cb9b4bb63b7a6cc3f83a3728d5ca
| 1,307
|
py
|
Python
|
tests/views.py
|
WoLpH/django-debug-toolbar
|
9763d109babc2ca67fd28592d7d253d8a50dd046
|
[
"BSD-3-Clause"
] | null | null | null |
tests/views.py
|
WoLpH/django-debug-toolbar
|
9763d109babc2ca67fd28592d7d253d8a50dd046
|
[
"BSD-3-Clause"
] | null | null | null |
tests/views.py
|
WoLpH/django-debug-toolbar
|
9763d109babc2ca67fd28592d7d253d8a50dd046
|
[
"BSD-3-Clause"
] | null | null | null |
# coding: utf-8
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.template.response import TemplateResponse
from django.views.decorators.cache import cache_page
def execute_sql(request):
list(User.objects.all())
return HttpResponse()
def regular_view(request, title):
return render(request, 'basic.html', {'title': title})
def template_response_view(request, title):
return TemplateResponse(request, 'basic.html', {'title': title})
def new_user(request, username='joe'):
User.objects.create_user(username=username)
return render(request, 'basic.html', {'title': 'new user'})
def resolving_view(request, arg1, arg2):
# see test_url_resolving in tests.py
return HttpResponse()
@cache_page(60)
def cached_view(request):
return HttpResponse()
def regular_jinjia_view(request, title):
return render(request, 'jinja2/basic.jinja', {'title': title})
def listcomp_view(request):
lst = [i for i in range(50000) if i % 2 == 0]
return render(request, 'basic.html', {'title': 'List comprehension', 'lst': lst})
def redirect_view(request):
return HttpResponseRedirect('/regular/redirect/')
| 25.627451
| 85
| 0.739862
|
2b8d573c5f31e71a51d277352d2f953a81bde2cc
| 2,324
|
py
|
Python
|
test.py
|
vliu15/dialogue-seq2seq
|
d78354cdb568963f8e85fce1202e85690535f01c
|
[
"MIT"
] | 27
|
2019-04-17T11:02:39.000Z
|
2021-12-16T09:42:41.000Z
|
test.py
|
lixinyu-up/dialogue-seq2seq
|
d78354cdb568963f8e85fce1202e85690535f01c
|
[
"MIT"
] | 1
|
2019-03-01T09:21:09.000Z
|
2019-03-02T22:49:48.000Z
|
test.py
|
vliu15/transformer-rnn-pytorch
|
d78354cdb568963f8e85fce1202e85690535f01c
|
[
"MIT"
] | 13
|
2019-03-31T05:16:49.000Z
|
2021-07-09T13:08:14.000Z
|
''' Translate input text with trained model '''
import torch
import torch.utils.data
import argparse
from tqdm import tqdm
import pickle
from utils.dataset import collate_fn, TranslationDataset
from seq2seq.Translator import Translator
def main():
''' Main function '''
parser = argparse.ArgumentParser(description='translate.py')
parser.add_argument('-model', required=True, help='Path to model .chkpt file')
parser.add_argument('-test_file', required=True, help='Test pickle file for validation')
parser.add_argument('-output', default='outputs.txt', help='Path to output the predictions (each line will be the decoded sequence')
parser.add_argument('-beam_size', type=int, default=5, help='Beam size')
parser.add_argument('-batch_size', type=int, default=16, help='Batch size')
parser.add_argument('-n_best', type=int, default=1, help='If verbose is set, will output the n_best decoded sentences')
parser.add_argument('-no_cuda', action='store_true')
opt = parser.parse_args()
opt.cuda = not opt.no_cuda
#- Prepare Translator
translator = Translator(opt)
print('[Info] Model opts: {}'.format(translator.model_opt))
#- Prepare DataLoader
test_data = torch.load(opt.test_file)
test_src_insts = test_data['test']['src']
test_tgt_insts = test_data['test']['tgt']
test_loader = torch.utils.data.DataLoader(
TranslationDataset(
src_word2idx=test_data['dict']['src'],
tgt_word2idx=test_data['dict']['tgt'],
src_insts=test_src_insts),
num_workers=2,
batch_size=opt.batch_size,
drop_last=True,
collate_fn=collate_fn)
print('[Info] Evaluate on test set.')
with open(opt.output, 'w') as f:
for batch in tqdm(test_loader, mininterval=2, desc=' - (Testing)', leave=False):
all_hyp, all_scores = translator.translate_batch(*batch) # structure: List[batch, seq, pos]
for inst in all_hyp:
f.write('[')
for seq in inst:
seq = seq[0]
pred_seq = ' '.join([test_loader.dataset.tgt_idx2word[word] for word in seq])
f.write('\t' + pred_seq + '\n')
f.write(']\n')
print('[Info] Finished.')
if __name__ == "__main__":
main()
| 37.483871
| 136
| 0.648451
|
3f22e005a43c983631444babc97e8fbb35b0b0a3
| 6,882
|
py
|
Python
|
examples/from-wiki/light_field_3d_viewer.py
|
hesom/pycuda
|
f2f999f51617fcf3deb77f2104b5051885cae498
|
[
"Apache-2.0"
] | 1,264
|
2015-01-01T15:38:32.000Z
|
2022-03-31T22:30:21.000Z
|
examples/from-wiki/light_field_3d_viewer.py
|
hesom/pycuda
|
f2f999f51617fcf3deb77f2104b5051885cae498
|
[
"Apache-2.0"
] | 262
|
2015-01-18T20:52:48.000Z
|
2022-03-30T15:57:50.000Z
|
examples/from-wiki/light_field_3d_viewer.py
|
hesom/pycuda
|
f2f999f51617fcf3deb77f2104b5051885cae498
|
[
"Apache-2.0"
] | 289
|
2015-01-14T04:30:00.000Z
|
2022-03-19T19:58:49.000Z
|
#!python
"""
3D display of Light Field images.
Example images can be download from:
http://graphics.stanford.edu/software/LFDisplay/LFDisplay-samples.zip
Use:
>> python LFview.py <path to light-field image>
Prerequisites:
- Python 2.7
- Enthought Tool Suite (ETS)
- PIL
- Jinja
Author: Amit Aides. amitibo at technion . ac . il
"""
from enthought.traits.api import HasTraits, Range, on_trait_change
from enthought.traits.ui.api import View, Item
from enthought.chaco.api import Plot, ArrayPlotData, gray
from enthought.enable.component_editor import ComponentEditor
import numpy as np
import Image
import argparse
import os.path
import math
import pycuda.driver as cuda
import pycuda.compiler
import pycuda.autoinit
from jinja2 import Template
_kernel_tpl = Template("""
{% if NCHANNELS == 3 %}
texture<float4, 2> tex;
{% else %}
texture<float, 2> tex;
{% endif %}
__global__ void LFview_kernel(
float x_angle,
float y_angle,
unsigned char* data
)
{
//
// calculate pixel idx
//
unsigned int x = blockIdx.x * blockDim.x + threadIdx.x;
unsigned int y = blockIdx.y * blockDim.y + threadIdx.y;
//
// We might be outside the reachable pixels. Don't do anything
//
if( (x >= {{newiw}}) || (y >= {{newih}}) )
return;
//
// calculate offset into destination array
//
unsigned int didx = (y * {{newiw}} + x) * {{NCHANNELS}};
//
// calculate offset into source array (be aware of rotation and scaling)
//
float sx = {{x_start}} + tan(x_angle)*{{x_ratio}} + {{x_step}}*x;
float sy = {{y_start}} + tan(y_angle)*{{y_ratio}} + {{y_step}}*y;
if( (sx < 0) || (sx >= {{oldiw}}) || (sy < 0) || (sy >= {{oldih}}) ) {
{% for channel in range(NCHANNELS) %}
data[didx+{{channel}}] = 0;
{% endfor %}
return;
}
{% if NCHANNELS == 3 %}
float4 texval = tex2D(tex, sx, sy);
data[didx] = texval.x;
data[didx+1] = texval.y;
data[didx+2] = texval.z;
{% else %}
data[didx] = tex2D(tex, sx, sy);
{% endif %}
}
""")
def ceil(x):
return int(x + 0.5)
class LFapplication(HasTraits):
traits_view = View(
Item('LF_img', editor=ComponentEditor(), show_label=False),
Item('X_angle', label='Angle in the X axis'),
Item('Y_angle', label='Angle in the Y axis'),
resizable = True,
title="LF Image"
)
def __init__(self, img_path):
super().__init__()
#
# Load image data
#
base_path = os.path.splitext(img_path)[0]
lenslet_path = base_path + '-lenslet.txt'
optics_path = base_path + '-optics.txt'
with open(lenslet_path) as f:
tmp = eval(f.readline())
x_offset, y_offset, right_dx, right_dy, down_dx, down_dy = \
np.array(tmp, dtype=np.float32)
with open(optics_path) as f:
for line in f:
name, val = line.strip().split()
try:
setattr(self, name, np.float32(val))
except:
pass
max_angle = math.atan(self.pitch/2/self.flen)
#
# Prepare image
#
im_pil = Image.open(img_path)
if im_pil.mode == 'RGB':
self.NCHANNELS = 3
w, h = im_pil.size
im = np.zeros((h, w, 4), dtype=np.float32)
im[:, :, :3] = np.array(im_pil).astype(np.float32)
self.LF_dim = (ceil(h/down_dy), ceil(w/right_dx), 3)
else:
self.NCHANNELS = 1
im = np.array(im_pil.getdata()).reshape(im_pil.size[::-1]).astype(np.float32)
h, w = im.shape
self.LF_dim = (ceil(h/down_dy), ceil(w/right_dx))
x_start = x_offset - int(x_offset / right_dx) * right_dx
y_start = y_offset - int(y_offset / down_dy) * down_dy
x_ratio = self.flen * right_dx / self.pitch
y_ratio = self.flen * down_dy / self.pitch
#
# Generate the cuda kernel
#
mod_LFview = pycuda.compiler.SourceModule(
_kernel_tpl.render(
newiw=self.LF_dim[1],
newih=self.LF_dim[0],
oldiw=w,
oldih=h,
x_start=x_start,
y_start=y_start,
x_ratio=x_ratio,
y_ratio=y_ratio,
x_step=right_dx,
y_step=down_dy,
NCHANNELS=self.NCHANNELS
)
)
self.LFview_func = mod_LFview.get_function("LFview_kernel")
self.texref = mod_LFview.get_texref("tex")
#
# Now generate the cuda texture
#
if self.NCHANNELS == 3:
cuda.bind_array_to_texref(
cuda.make_multichannel_2d_array(im, order="C"),
self.texref
)
else:
cuda.matrix_to_texref(im, self.texref, order="C")
#
# We could set the next if we wanted to address the image
# in normalized coordinates ( 0 <= coordinate < 1.)
# texref.set_flags(cuda.TRSF_NORMALIZED_COORDINATES)
#
self.texref.set_filter_mode(cuda.filter_mode.LINEAR)
#
# Prepare the traits
#
self.add_trait('X_angle', Range(-max_angle, max_angle, 0.0))
self.add_trait('Y_angle', Range(-max_angle, max_angle, 0.0))
self.plotdata = ArrayPlotData(LF_img=self.sampleLF())
self.LF_img = Plot(self.plotdata)
if self.NCHANNELS == 3:
self.LF_img.img_plot("LF_img")
else:
self.LF_img.img_plot("LF_img", colormap=gray)
def sampleLF(self):
#
# Get the output image
#
output = np.zeros(self.LF_dim, dtype=np.uint8)
#
# Calculate the gridsize. This is entirely given by the size of our image.
#
blocks = (16, 16, 1)
gridx = ceil(self.LF_dim[1]/blocks[1])
gridy = ceil(self.LF_dim[0]/blocks[0])
grid = (gridx, gridy)
#
# Call the kernel
#
self.LFview_func(
np.float32(self.X_angle),
np.float32(self.Y_angle),
cuda.Out(output),
texrefs=[self.texref],
block=blocks,
grid=grid
)
return output
@on_trait_change('X_angle, Y_angle')
def updateImge(self):
self.plotdata.set_data('LF_img', self.sampleLF())
def main(img_path):
"""Main function"""
app = LFapplication(img_path)
app.configure_traits()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='View an LF image')
parser.add_argument('img_path', type=str, help='Path to LF image')
args = parser.parse_args()
main(args.img_path)
| 26.988235
| 89
| 0.555217
|
4fcd9cded2f739414028ba21ae3b5427bd153f63
| 608
|
py
|
Python
|
datamegh/util/types.py
|
yankeexe/datamegh
|
f5a95f493d2dba2c8f9ff22a94b2ff9afc7f0d6e
|
[
"MIT"
] | 3
|
2020-02-25T09:28:40.000Z
|
2020-02-28T04:18:23.000Z
|
datamegh/util/types.py
|
yankeexe/datamegh
|
f5a95f493d2dba2c8f9ff22a94b2ff9afc7f0d6e
|
[
"MIT"
] | 21
|
2020-02-12T15:32:19.000Z
|
2020-03-20T06:48:02.000Z
|
datamegh/util/types.py
|
yankeexe/datamegh
|
f5a95f493d2dba2c8f9ff22a94b2ff9afc7f0d6e
|
[
"MIT"
] | 1
|
2020-02-20T08:18:48.000Z
|
2020-02-20T08:18:48.000Z
|
""" Type utility functions. """
def is_string(obj):
""" Check if the object is a string. """
try:
basestring
except NameError:
basestring = str
return isinstance(obj, basestring)
def is_iterable(obj):
""" Check if the object is iterable. """
has_iter = hasattr(obj, "__iter__")
has_get_item = hasattr(obj, "__getitem__")
return has_iter or has_get_item
def is_dict(obj):
""" Check if the object is a dict. """
return type(obj) == type({})
def is_list(value):
""" Check if the given value is a list. """
return isinstance(value, list)
| 20.266667
| 47
| 0.625
|
44d28a0fe9c0e324efbea306df7edfdf5cce171f
| 278
|
py
|
Python
|
src/utils.py
|
tech-sketch/fiware-gamepad-controller
|
d09ec58d8dc642550ffb13806b0a1134aec60e04
|
[
"Apache-2.0"
] | 2
|
2019-02-16T14:18:20.000Z
|
2019-02-18T02:35:43.000Z
|
src/utils.py
|
RoboticBase/fiware-gamepad-controller
|
d09ec58d8dc642550ffb13806b0a1134aec60e04
|
[
"Apache-2.0"
] | null | null | null |
src/utils.py
|
RoboticBase/fiware-gamepad-controller
|
d09ec58d8dc642550ffb13806b0a1134aec60e04
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
def find_item(obj, cond):
if not isinstance(obj, (tuple, list,)):
return None
if not callable(cond):
return None
try:
return next((item for item in obj if cond(item)), None)
except Exception:
return None
| 21.384615
| 63
| 0.579137
|
e23e05f2a97104066ed6fc93458de8b4696b4611
| 1,576
|
py
|
Python
|
tests/test_engine_bf.py
|
shahinsba/angr-platforms
|
86f9ea90c396fb5561d0196a2d1a873e573b0294
|
[
"BSD-2-Clause"
] | null | null | null |
tests/test_engine_bf.py
|
shahinsba/angr-platforms
|
86f9ea90c396fb5561d0196a2d1a873e573b0294
|
[
"BSD-2-Clause"
] | null | null | null |
tests/test_engine_bf.py
|
shahinsba/angr-platforms
|
86f9ea90c396fb5561d0196a2d1a873e573b0294
|
[
"BSD-2-Clause"
] | null | null | null |
import os
import logging
import pyvex
import angr
from angr_platforms.bf.engine_bf import UberEngineWithBF
def test_hello():
lifters = pyvex.lifting.lifters['BF']
pyvex.lifting.lifters['BF'] = []
try:
hellobf = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../test_programs/bf/hello.bf'))
p = angr.Project(hellobf, engine=UberEngineWithBF)
entry = p.factory.entry_state()
smgr = p.factory.simulation_manager(entry)
smgr.explore()
assert smgr.deadended[0].posix.dumps(1) == b'Hello World!\n'
finally:
pyvex.lifting.lifters['BF'] = lifters
def test_1bytecrackme_good():
lifters = pyvex.lifting.lifters['BF']
pyvex.lifting.lifters['BF'] = []
try:
crackme = str(os.path.join(os.path.dirname(os.path.realpath(__file__)),
'../test_programs/bf/1bytecrackme-good.bf'))
bad_states = lambda state: b"-" in state.posix.dumps(1)
p = angr.Project(crackme, engine=UberEngineWithBF)
p.arch.vex_arch = None # force test with engine
entry = p.factory.entry_state(remove_options={angr.options.LAZY_SOLVES})
smgr = p.factory.simulation_manager(entry)
smgr.run(until=lambda lsmgr: len(lsmgr.active) == 0)
smgr.stash(from_stash="deadended", to_stash="bad", filter_func=bad_states)
assert b"\n" == smgr.deadended[0].posix.dumps(0)
finally:
pyvex.lifting.lifters['BF'] = lifters
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
test_hello()
test_1bytecrackme_good()
| 36.651163
| 112
| 0.666878
|
0264389a6d97de2e60d69120df2d6843910df099
| 917
|
py
|
Python
|
setup.py
|
arjun-zeiss/apeer-python-sdk
|
d42f1cd5b3ddc444122fda2e09eb2ac376ae3b27
|
[
"MIT"
] | null | null | null |
setup.py
|
arjun-zeiss/apeer-python-sdk
|
d42f1cd5b3ddc444122fda2e09eb2ac376ae3b27
|
[
"MIT"
] | null | null | null |
setup.py
|
arjun-zeiss/apeer-python-sdk
|
d42f1cd5b3ddc444122fda2e09eb2ac376ae3b27
|
[
"MIT"
] | null | null | null |
from setuptools import setup
setup(name='apeer-dev-kit',
version='1.1.0',
description='Development kit for creating modules on apeer',
url='https://github.com/apeer-micro/apeer-python-sdk',
author='apeer-micro',
packages=['apeer_dev_kit'],
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
long_description="""
APEER Python SDK aka (ADK) is a Python library for reading inputs and writing outputs of APEER(https://www.apeer.com) modules.
The ADK will take care of reading inputs from previous modules in APEER and writing your outputs in the correct format for the next mod ule.
This project is hosted at https://github.com/apeer-micro/apeer-python-sdk
The documentation can be found at https://github.com/apeer-micro/apeer-python-sdk/blob/master/README.md
""")
| 48.263158
| 140
| 0.706652
|
9c6bb2f78d74586cc4fa3c52e61553d78ac2b196
| 8,464
|
py
|
Python
|
equality/wallet/cc_wallet/cc_utils.py
|
grayfallstown/equality-blockchain
|
019425b703f6b013e441481ac43389a80415f2f1
|
[
"Apache-2.0"
] | 10
|
2021-07-04T15:14:12.000Z
|
2021-10-17T14:52:56.000Z
|
equality/wallet/cc_wallet/cc_utils.py
|
grayfallstown/equality-blockchain
|
019425b703f6b013e441481ac43389a80415f2f1
|
[
"Apache-2.0"
] | 11
|
2021-07-04T19:31:36.000Z
|
2022-01-11T02:46:23.000Z
|
equality/wallet/cc_wallet/cc_utils.py
|
grayfallstown/equality-blockchain
|
019425b703f6b013e441481ac43389a80415f2f1
|
[
"Apache-2.0"
] | 11
|
2021-07-04T21:49:17.000Z
|
2021-10-04T17:45:38.000Z
|
import dataclasses
from typing import List, Optional, Tuple
from blspy import AugSchemeMPL, G2Element
from equality.types.blockchain_format.coin import Coin
from equality.types.blockchain_format.program import Program, INFINITE_COST
from equality.types.blockchain_format.sized_bytes import bytes32
from equality.types.condition_opcodes import ConditionOpcode
from equality.types.spend_bundle import CoinSolution, SpendBundle
from equality.util.condition_tools import conditions_dict_for_solution
from equality.util.ints import uint64
from equality.wallet.puzzles.cc_loader import CC_MOD, LOCK_INNER_PUZZLE
from equality.wallet.puzzles.genesis_by_coin_id_with_0 import (
genesis_coin_id_for_genesis_coin_checker,
lineage_proof_for_coin,
lineage_proof_for_genesis,
lineage_proof_for_zero,
)
NULL_SIGNATURE = G2Element()
ANYONE_CAN_SPEND_PUZZLE = Program.to(1) # simply return the conditions
# information needed to spend a cc
# if we ever support more genesis conditions, like a re-issuable coin,
# we may need also to save the `genesis_coin_mod` or its hash
@dataclasses.dataclass
class SpendableCC:
coin: Coin
genesis_coin_id: bytes32
inner_puzzle: Program
lineage_proof: Program
def cc_puzzle_for_inner_puzzle(mod_code, genesis_coin_checker, inner_puzzle) -> Program:
"""
Given an inner puzzle, generate a puzzle program for a specific cc.
"""
return mod_code.curry(mod_code.get_tree_hash(), genesis_coin_checker, inner_puzzle)
# return mod_code.curry([mod_code.get_tree_hash(), genesis_coin_checker, inner_puzzle])
def cc_puzzle_hash_for_inner_puzzle_hash(mod_code, genesis_coin_checker, inner_puzzle_hash) -> bytes32:
"""
Given an inner puzzle hash, calculate a puzzle program hash for a specific cc.
"""
gcc_hash = genesis_coin_checker.get_tree_hash()
return mod_code.curry(mod_code.get_tree_hash(), gcc_hash, inner_puzzle_hash).get_tree_hash(
gcc_hash, inner_puzzle_hash
)
def lineage_proof_for_cc_parent(parent_coin: Coin, parent_inner_puzzle_hash: bytes32) -> Program:
return Program.to(
(
1,
[parent_coin.parent_coin_info, parent_inner_puzzle_hash, parent_coin.amount],
)
)
def subtotals_for_deltas(deltas) -> List[int]:
"""
Given a list of deltas corresponding to input coins, create the "subtotals" list
needed in solutions spending those coins.
"""
subtotals = []
subtotal = 0
for delta in deltas:
subtotals.append(subtotal)
subtotal += delta
# tweak the subtotals so the smallest value is 0
subtotal_offset = min(subtotals)
subtotals = [_ - subtotal_offset for _ in subtotals]
return subtotals
def coin_solution_for_lock_coin(
prev_coin: Coin,
subtotal: int,
coin: Coin,
) -> CoinSolution:
puzzle_reveal = LOCK_INNER_PUZZLE.curry(prev_coin.as_list(), subtotal)
coin = Coin(coin.name(), puzzle_reveal.get_tree_hash(), uint64(0))
coin_solution = CoinSolution(coin, puzzle_reveal, Program.to(0))
return coin_solution
def bundle_for_spendable_cc_list(spendable_cc: SpendableCC) -> Program:
pair = (spendable_cc.coin.as_list(), spendable_cc.lineage_proof)
return Program.to(pair)
def spend_bundle_for_spendable_ccs(
mod_code: Program,
genesis_coin_checker: Program,
spendable_cc_list: List[SpendableCC],
inner_solutions: List[Program],
sigs: Optional[List[G2Element]] = [],
) -> SpendBundle:
"""
Given a list of `SpendableCC` objects and inner solutions for those objects, create a `SpendBundle`
that spends all those coins. Note that it the signature is not calculated it, so the caller is responsible
for fixing it.
"""
N = len(spendable_cc_list)
if len(inner_solutions) != N:
raise ValueError("spendable_cc_list and inner_solutions are different lengths")
input_coins = [_.coin for _ in spendable_cc_list]
# figure out what the output amounts are by running the inner puzzles & solutions
output_amounts = []
for cc_spend_info, inner_solution in zip(spendable_cc_list, inner_solutions):
error, conditions, cost = conditions_dict_for_solution(
cc_spend_info.inner_puzzle, inner_solution, INFINITE_COST
)
total = 0
if conditions:
for _ in conditions.get(ConditionOpcode.CREATE_COIN, []):
total += Program.to(_.vars[1]).as_int()
output_amounts.append(total)
coin_solutions = []
deltas = [input_coins[_].amount - output_amounts[_] for _ in range(N)]
subtotals = subtotals_for_deltas(deltas)
if sum(deltas) != 0:
raise ValueError("input and output amounts don't match")
bundles = [bundle_for_spendable_cc_list(_) for _ in spendable_cc_list]
for index in range(N):
cc_spend_info = spendable_cc_list[index]
puzzle_reveal = cc_puzzle_for_inner_puzzle(mod_code, genesis_coin_checker, cc_spend_info.inner_puzzle)
prev_index = (index - 1) % N
next_index = (index + 1) % N
prev_bundle = bundles[prev_index]
my_bundle = bundles[index]
next_bundle = bundles[next_index]
solution = [
inner_solutions[index],
prev_bundle,
my_bundle,
next_bundle,
subtotals[index],
]
coin_solution = CoinSolution(input_coins[index], puzzle_reveal, Program.to(solution))
coin_solutions.append(coin_solution)
if sigs is None or sigs == []:
return SpendBundle(coin_solutions, NULL_SIGNATURE)
else:
return SpendBundle(coin_solutions, AugSchemeMPL.aggregate(sigs))
def is_cc_mod(inner_f: Program):
"""
You may want to generalize this if different `CC_MOD` templates are supported.
"""
return inner_f == CC_MOD
def check_is_cc_puzzle(puzzle: Program):
r = puzzle.uncurry()
if r is None:
return False
inner_f, args = r
return is_cc_mod(inner_f)
def uncurry_cc(puzzle: Program) -> Optional[Tuple[Program, Program, Program]]:
"""
Take a puzzle and return `None` if it's not a `CC_MOD` cc, or
a triple of `mod_hash, genesis_coin_checker, inner_puzzle` if it is.
"""
r = puzzle.uncurry()
if r is None:
return r
inner_f, args = r
if not is_cc_mod(inner_f):
return None
mod_hash, genesis_coin_checker, inner_puzzle = list(args.as_iter())
return mod_hash, genesis_coin_checker, inner_puzzle
def get_lineage_proof_from_coin_and_puz(parent_coin, parent_puzzle):
r = uncurry_cc(parent_puzzle)
if r:
mod_hash, genesis_checker, inner_puzzle = r
lineage_proof = lineage_proof_for_cc_parent(parent_coin, inner_puzzle.get_tree_hash())
else:
if parent_coin.amount == 0:
lineage_proof = lineage_proof_for_zero(parent_coin)
else:
lineage_proof = lineage_proof_for_genesis(parent_coin)
return lineage_proof
def spendable_cc_list_from_coin_solution(coin_solution: CoinSolution, hash_to_puzzle_f) -> List[SpendableCC]:
"""
Given a `CoinSolution`, extract out a list of `SpendableCC` objects.
Since `SpendableCC` needs to track the inner puzzles and a `Coin` only includes
puzzle hash, we also need a `hash_to_puzzle_f` function that turns puzzle hashes into
the corresponding puzzles. This is generally either a `dict` or some kind of DB
(if it's large or persistent).
"""
spendable_cc_list = []
coin = coin_solution.coin
puzzle = Program.from_bytes(bytes(coin_solution.puzzle_reveal))
r = uncurry_cc(puzzle)
if r:
mod_hash, genesis_coin_checker, inner_puzzle = r
lineage_proof = lineage_proof_for_cc_parent(coin, inner_puzzle.get_tree_hash())
else:
lineage_proof = lineage_proof_for_coin(coin)
for new_coin in coin_solution.additions():
puzzle = hash_to_puzzle_f(new_coin.puzzle_hash)
if puzzle is None:
# we don't recognize this puzzle hash, skip it
continue
r = uncurry_cc(puzzle)
if r is None:
# this isn't a cc puzzle
continue
mod_hash, genesis_coin_checker, inner_puzzle = r
genesis_coin_id = genesis_coin_id_for_genesis_coin_checker(genesis_coin_checker)
cc_spend_info = SpendableCC(new_coin, genesis_coin_id, inner_puzzle, lineage_proof)
spendable_cc_list.append(cc_spend_info)
return spendable_cc_list
| 33.454545
| 110
| 0.71302
|
4edd364399d169071cb79a83e69d08df5c3b37c1
| 284
|
py
|
Python
|
tests/models/base/models.py
|
beproud/bpcommons
|
c24aed4143d743b1af6c621630ed9faa7e1ccaa4
|
[
"BSD-2-Clause"
] | 2
|
2016-03-07T01:52:12.000Z
|
2017-08-30T06:14:43.000Z
|
tests/models/base/models.py
|
beproud/bpcommons
|
c24aed4143d743b1af6c621630ed9faa7e1ccaa4
|
[
"BSD-2-Clause"
] | 18
|
2015-03-08T13:52:18.000Z
|
2022-01-25T02:46:09.000Z
|
tests/models/base/models.py
|
beproud/bpcommons
|
c24aed4143d743b1af6c621630ed9faa7e1ccaa4
|
[
"BSD-2-Clause"
] | 2
|
2015-02-07T01:33:00.000Z
|
2015-09-08T14:57:44.000Z
|
#:coding=utf-8:
from beproud.django.commons.models import (
DatedModel as DatedModelBase,
BaseModel as BaseModelBase
)
class DatedModel(DatedModelBase):
class Meta:
app_label = 'base'
class BaseModel(BaseModelBase):
class Meta:
app_label = 'base'
| 16.705882
| 43
| 0.690141
|
133f0df421911c2bf437f8e0fda3199424aad81a
| 15,621
|
py
|
Python
|
piazza_api/rpc.py
|
jlumbroso/piazza-api
|
e52b1909fd9df0db262651df56a3f06b3d5773ee
|
[
"MIT"
] | null | null | null |
piazza_api/rpc.py
|
jlumbroso/piazza-api
|
e52b1909fd9df0db262651df56a3f06b3d5773ee
|
[
"MIT"
] | null | null | null |
piazza_api/rpc.py
|
jlumbroso/piazza-api
|
e52b1909fd9df0db262651df56a3f06b3d5773ee
|
[
"MIT"
] | null | null | null |
import getpass
import json
import requests
import six.moves
from piazza_api.exceptions import AuthenticationError, NotAuthenticatedError, \
RequestError
from piazza_api.nonce import nonce as _piazza_nonce
class PiazzaRPC(object):
"""Unofficial Client for Piazza's Internal API
Example:
>>> p = PiazzaRPC("hl5qm84dl4t3x2")
>>> p.user_login()
Email: ...
Password: ...
>>> p.content_get(181)
...
:type network_id: str|None
:param network_id: This is the ID of the network (or class) from which
to query posts
"""
def __init__(self, network_id=None):
self._nid = network_id
self.base_api_urls = {
"logic": "https://piazza.com/logic/api",
"main": "https://piazza.com/main/api",
}
self.cookies = None
def user_login(self, email=None, password=None):
"""Login with email, password and get back a session cookie
:type email: str
:param email: The email used for authentication
:type password: str
:param password: The password used for authentication
"""
email = six.moves.input("Email: ") if email is None else email
password = getpass.getpass() if password is None else password
login_data = {
"method": "user.login",
"params": {"email": email,
"pass": password}
}
# If the user/password match, the server respond will contain a
# session cookie that you can use to authenticate future requests.
r = requests.post(
self.base_api_urls["logic"],
data=json.dumps(login_data),
)
if r.json()["result"] not in ["OK"]:
raise AuthenticationError("Could not authenticate.\n{}"
.format(r.json()))
self.cookies = r.cookies
def demo_login(self, auth=None, url=None):
"""Authenticate with a "Share Your Class" URL using a demo user.
You may provide either the entire ``url`` or simply the ``auth``
parameter.
:param url: Example - "https://piazza.com/demo_login?nid=hbj11a1gcvl1s6&auth=06c111b"
:param auth: Example - "06c111b"
"""
assert all([
auth or url, # Must provide at least one
not (auth and url) # Cannot provide more than one
])
if url is None:
url = "https://piazza.com/demo_login"
params = dict(nid=self._nid, auth=auth)
res = requests.get(url, params=params)
else:
res = requests.get(url)
self.cookies = res.cookies
def content_get(self, cid, nid=None):
"""Get data from post `cid` in network `nid`
:type nid: str
:param nid: This is the ID of the network (or class) from which
to query posts. This is optional and only to override the existing
`network_id` entered when created the class
:type cid: str|int
:param cid: This is the post ID which we grab
:returns: Python object containing returned data
"""
r = self.request(
method="content.get",
data={"cid": cid},
nid=nid
)
return self._handle_error(r, "Could not get post {}.".format(cid))
def content_create(self, params):
"""Create a post or followup.
:type params: dict
:param params: A dict of options to pass to the endpoint. Depends on
the specific type of content being created.
:returns: Python object containing returned data
"""
r = self.request(
method="content.create",
data=params
)
return self._handle_error(
r,
"Could not create object {}.".format(repr(params))
)
def content_instructor_answer(self, params):
"""Answer a post as an instructor.
:type params: dict
:param params: A dict of options to pass to the endpoint. Depends on
the specific type of content being created.
:returns: Python object containing returned data
"""
r = self.request(
method="content.answer",
data=params
)
return self._handle_error(r, "Could not create object {}.".format(
repr(params)))
def content_mark_duplicate(self, params):
"""Mark a post as duplicate to another.
:type params: dict
:param params: the parameters to be passed in
"""
r = self.request(
method="content.duplicate",
data=params
)
return self._handle_error(r, "Could not create object {}.".format(
repr(params)))
def add_students(self, student_emails, nid=None):
"""Enroll students in a network `nid`.
Piazza will email these students with instructions to
activate their account.
:type student_emails: list of str
:param student_emails: A listing of email addresses to enroll
in the network (or class). This can be a list of length one.
:type nid: str
:param nid: This is the ID of the network to add students
to. This is optional and only to override the existing
`network_id` entered when created the class
:returns: Python object containing returned data, a list
of dicts of user data of all of the users in the network
including the ones that were just added.
"""
r = self.request(
method="network.update",
data={
"from": "ClassSettingsPage",
"add_students": student_emails
},
nid=nid,
nid_key="id"
)
return self._handle_error(r, "Could not add users.")
def get_all_users(self, nid=None):
"""Get a listing of data for each user in a network `nid`
:type nid: str
:param nid: This is the ID of the network to get users
from. This is optional and only to override the existing
`network_id` entered when created the class
:returns: Python object containing returned data, a list
of dicts containing user data.
"""
r = self.request(
method="network.get_all_users",
nid=nid
)
return self._handle_error(r, "Could not get users.")
def get_users(self, user_ids, nid=None):
"""Get a listing of data for specific users `user_ids` in
a network `nid`
:type user_ids: list of str
:param user_ids: a list of user ids. These are the same
ids that are returned by get_all_users.
:type nid: str
:param nid: This is the ID of the network to get students
from. This is optional and only to override the existing
`network_id` entered when created the class
:returns: Python object containing returned data, a list
of dicts containing user data.
"""
r = self.request(
method="network.get_users",
data={"ids": user_ids},
nid=nid
)
return self._handle_error(r, "Could not get users.")
def remove_users(self, user_ids, nid=None):
"""Remove users from a network `nid`
:type user_ids: list of str
:param user_ids: a list of user ids. These are the same
ids that are returned by get_all_users.
:type nid: str
:param nid: This is the ID of the network to remove students
from. This is optional and only to override the existing
`network_id` entered when created the class
:returns: Python object containing returned data, a list
of dicts of user data of all of the users remaining in
the network after users are removed.
"""
r = self.request(
method="network.update",
data={"remove_users": user_ids},
nid=nid,
nid_key="id"
)
return self._handle_error(r, "Could not remove users.")
def get_my_feed(self, limit=150, offset=20, sort="updated", nid=None):
"""Get my feed
:type limit: int
:param limit: Number of posts from feed to get, starting from ``offset``
:type offset: int
:param offset: Offset starting from bottom of feed
:type sort: str
:param sort: How to sort feed that will be retrieved; only current
known value is "updated"
:type nid: str
:param nid: This is the ID of the network to get the feed
from. This is optional and only to override the existing
`network_id` entered when created the class
"""
r = self.request(
method="network.get_my_feed",
nid=nid,
data=dict(
limit=limit,
offset=offset,
sort=sort
)
)
return self._handle_error(r, "Could not retrieve your feed.")
def filter_feed(self, updated=False, following=False, folder=False,
filter_folder="", sort="updated", nid=None):
"""Get filtered feed
Only one filter type (updated, following, folder) is possible.
:type nid: str
:param nid: This is the ID of the network to get the feed
from. This is optional and only to override the existing
`network_id` entered when created the class
:type sort: str
:param sort: How to sort feed that will be retrieved; only current
known value is "updated"
:type updated: bool
:param updated: Set to filter through only posts which have been updated
since you last read them
:type following: bool
:param following: Set to filter through only posts which you are
following
:type folder: bool
:param folder: Set to filter through only posts which are in the
provided ``filter_folder``
:type filter_folder: str
:param filter_folder: Name of folder to show posts from; required
only if ``folder`` is set
"""
assert sum([updated, following, folder]) == 1
if folder:
assert filter_folder
if updated:
filter_type = dict(updated=1)
elif following:
filter_type = dict(following=1)
else:
filter_type = dict(folder=1, filter_folder=filter_folder)
r = self.request(
nid=nid,
method="network.filter_feed",
data=dict(
sort=sort,
**filter_type
)
)
return self._handle_error(r, "Could not retrieve filtered feed.")
def search(self, query, nid=None):
"""Search for posts with ``query``
:type nid: str
:param nid: This is the ID of the network to get the feed
from. This is optional and only to override the existing
`network_id` entered when created the class
:type query: str
:param query: The search query; should just be keywords for posts
that you are looking for
"""
r = self.request(
method="network.search",
nid=nid,
data=dict(query=query)
)
return self._handle_error(r, "Search with query '{}' failed."
.format(query))
def get_stats(self, nid=None):
"""Get statistics for class
:type nid: str
:param nid: This is the ID of the network to get stats
from. This is optional and only to override the existing
`network_id` entered when created the class
"""
r = self.request(
api_type="main",
method="network.get_stats",
nid=nid,
)
return self._handle_error(r, "Could not retrieve stats for class.")
def get_user_profile(self):
"""Get profile of the current user"""
r = self.request(method="user_profile.get_profile")
return self._handle_error(r, "Could not get user profile.")
def get_user_status(self):
"""
Get global status of the current user, which contains information on
the relationship of the user with respect to all their enrolled classes.
"""
r = self.request(method="user.status")
return self._handle_error(r, "Could not get user status.")
def request(self, method, data=None, nid=None, nid_key='nid',
api_type="logic", return_response=False):
"""Get data from arbitrary Piazza API endpoint `method` in network `nid`
:type method: str
:param method: An internal Piazza API method name like `content.get`
or `network.get_users`
:type data: dict
:param data: Key-value data to pass to Piazza in the request
:type nid: str
:param nid: This is the ID of the network to which the request
should be made. This is optional and only to override the
existing `network_id` entered when creating the class
:type nid_key: str
:param nid_key: Name expected by Piazza for `nid` when making request.
(Usually and by default "nid", but sometimes "id" is expected)
:returns: Python object containing returned data
:type return_response: bool
:param return_response: If set, returns whole :class:`requests.Response`
object rather than just the response body
"""
self._check_authenticated()
nid = nid if nid else self._nid
if data is None:
data = {}
headers = {}
if "session_id" in self.cookies:
headers["CSRF-Token"] = self.cookies["session_id"]
# Adding a nonce to the request
endpoint = self.base_api_urls[api_type]
if api_type == "logic":
endpoint += "?method={}&aid={}".format(
method,
_piazza_nonce()
)
response = requests.post(
endpoint,
data=json.dumps({
"method": method,
"params": dict({nid_key: nid}, **data)
}),
cookies=self.cookies,
headers=headers
)
return response if return_response else response.json()
###################
# Private Methods #
###################
def _check_authenticated(self):
"""Check that we're logged in and raise an exception if not.
:raises: NotAuthenticatedError
"""
if self.cookies is None:
raise NotAuthenticatedError("You must authenticate before "
"making any other requests.")
def _handle_error(self, result, err_msg):
"""Check result for error
:type result: dict
:param result: response body
:type err_msg: str
:param err_msg: The message given to the :class:`RequestError` instance
raised
:returns: Actual result from result
:raises RequestError: If result has error
"""
if result.get(u'error'):
raise RequestError("{}\nResponse: {}".format(
err_msg,
json.dumps(result, indent=2)
))
else:
return result.get(u'result')
| 35.910345
| 93
| 0.574227
|
584bfdd2a0cda92c1233b152da60fc75964e98df
| 8,892
|
py
|
Python
|
private/upload_pwfile.py
|
noraj/Kvasir
|
a5b3775184a8343240e1154a1f762f75df04dc0a
|
[
"BSD-3-Clause"
] | 194
|
2015-01-04T23:06:42.000Z
|
2022-02-11T17:39:28.000Z
|
private/upload_pwfile.py
|
The-L0st-Technocrat/Kvasir
|
ac04512546685cbe814d3eabf644ee3161b6052c
|
[
"BSD-3-Clause"
] | 26
|
2015-01-02T19:15:39.000Z
|
2020-11-11T17:58:34.000Z
|
private/upload_pwfile.py
|
The-L0st-Technocrat/Kvasir
|
ac04512546685cbe814d3eabf644ee3161b6052c
|
[
"BSD-3-Clause"
] | 65
|
2015-01-19T08:30:51.000Z
|
2020-12-28T23:53:31.000Z
|
#!/usr/bin/env python
# encoding: utf-8
__version__ = "1.0"
"""
##--------------------------------------#
## Kvasir
##
## (c) 2010-2014 Cisco Systems, Inc.
## (c) 2015 Kurt Grutzmacher
##
## Sends the password file(s) via Kvasir API
##
##--------------------------------------#
"""
from optparse import OptionParser, OptionGroup, OptionValueError
import sys, os, glob, re
sys.path.append('/opt/SPA/tools/lib/python')
from AutoSPAngAPI import Accounts, Services
# this is a mess... should use ipaddr library instead
IPV4_REGEX = re.compile("^(?P<ipv4>((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d))")
IPV6_REGEX = re.compile("^(?P<ipv6>\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?)")
# grab the ASPANG_URI if defined
ASPANG_URI = os.environ.get('ASPANG_URI', "http://localhost:8000/kvasir/api/call/jsonrpc")
PW_TYPES = ('PWDUMP', 'MSCa$h Dump', 'UNIX Passwd', 'UNIX Shadow', 'Medusa', 'Hydra', 'Username:Password', 'Usernames')
##--------------------------------------------------------------------
def process_pwfiles(options):
"""Processes each options.pw_file_infos record"""
for pw_file_info in options.pw_file_infos:
print("----------------------------------------------------------------")
print(" [*] Processing password file: %s" % (pw_file_info['full_path']))
try:
pw_data = open(pw_file_info['full_path'], "r").readlines()
except Exception, e:
print " [!] Unable to load file: %s" % (e)
return False
acct_api = Accounts(options.aspanguri)
svc_rec = get_svc_rec(options, pw_file_info['ipaddr'])
if type(svc_rec) == type(int()):
res = acct_api.upload_file(
filename=pw_file_info['filename'],
pw_data=pw_data,
service_rec=svc_rec,
add_to_evidence=options.add_to_evidence,
f_type=options.f_type,
)
for line in res[1].split("\n"):
if len(line) > 0:
print(" [-] %s" % (line))
else:
print(" [!] No service record found and none added for %s %s/%s" % (
pw_file_info['ipaddr'], options.proto, options.port
))
##--------------------------------------------------------------------
def get_address(options, filename):
if options.ipaddr is None:
address = get_ipv4(filename)
if address is None:
address = get_ipv6(filename)
if address is None:
print " [!] No IPv4/IPv6 address provided or found in the filename: %s" % (filename)
else:
address = ipv6_addr
else:
address = options.ipaddr
return address
##--------------------------------------------------------------------
def get_svc_rec(options, address):
"""Calls the Services.info() API to find the service record id"""
svc_api = Services(options.aspanguri)
svc = svc_api.info_or_add(ipaddr=address, proto=options.proto, port=options.port)
if svc:
return svc[0][0]
else:
# No service record found, lets try to add it if desired
if options.add_to_services:
retval = svc_api.add(ipaddr=address, proto=options.proto, port=options.port)
if not retval[0]:
print(retval[1])
return None
else:
return retval[1]
##--------------------------------------------------------------------
def get_ipv4(filename):
ipv4_addr = IPV4_REGEX.match(filename)
if ipv4_addr:
return ipv4_addr.group('ipv4')
else:
return
##--------------------------------------------------------------------
def get_ipv6(filename):
ipv6_addr = IPV6_REGEX.match(filename)
if ipv6_addr:
return ipv6_addr.group('ipv6')
else:
return
##--------------------------------------------------------------------
def Run(options):
options.pw_file_infos = []
if options.directory is not None and options.filename is None:
print " [*] Processing directory: %s" % (options.directory)
for file_path, dirs, filenames in os.walk(options.directory):
for filename in filenames:
address = get_address(options, filename)
if address:
full_path_filename = os.path.join(file_path, filename)
options.pw_file_infos.append({
'ipaddr': address,
'full_path': full_path_filename,
'filename': filename
})
elif options.filename is not None:
(file_path, options.filename) = os.path.split(options.filename)
if not file_path:
file_path = os.getcwd()
full_path_filename = os.path.join(file_path, options.filename)
address = get_address(options, options.filename)
options.pw_file_infos.append({
'ipaddr': address,
'full_path': full_path_filename,
'filename': options.filename
})
process_pwfiles(options)
return
##--------------------------------------------------------------------
def check_pwtypes(options, opt_str, value, parser):
if value in PW_TYPES:
parser.values.f_type = value
else:
raise OptionValueError(" [!] Invalid password file type: %s\nValid entries are:\n\n%s" % (value, ', '.join(PW_TYPES)))
##--------------------------------------------------------------------
if __name__=='__main__':
# set up commandline arguments
optparser = OptionParser(version=__version__)
optparser.add_option("-p", "--port", dest="port",
action="store", default=None, help="Protocol/Port (info/0, tcp/445) for all files")
optparser.add_option("-e", "--add_evidence", dest="add_to_evidence",
action="store_true", help="Add to evidence table")
optparser.add_option("-a", "--add_service", dest="add_to_services",
action="store_true", help="Add to services DB if not found")
optparser.add_option('-u', '--uri', dest='aspanguri',
action="store", default=ASPANG_URI, help="Kvasir API URI (eg: %s)" % (ASPANG_URI))
file_group = OptionGroup(optparser, "File-based Options")
file_group.add_option("-i", "--ip", dest="ipaddr",
action="store", default=None, help="IPv4/IPv6 Address (if non-std filename)")
file_group.add_option("-f", "--file", dest="filename",
action="store", default=None, help="Filename to insert/update")
file_group.add_option('-t', '--type', dest='f_type', type='string',
action='callback', callback=check_pwtypes, help='Password file type: %s' % (', '.join(PW_TYPES)))
optparser.add_option_group(file_group)
directory_group = OptionGroup(optparser, "Directory-based Options")
directory_group.add_option("-d", "--dir", dest="directory",
action="store", default=None, help="Directory location, all files should be named <ipdadr>-value")
optparser.add_option_group(directory_group)
(options, params) = optparser.parse_args()
print " ----------------------------------------------------------"
print " -- Password file upload, Kvasir master pwner edition --"
print " ----------------------------------------------------------\n"
if options.f_type is None:
raise OptionValueError("\n [!] Must provide a password file type\nValid entries are:\n\n%s" % (', '.join(PW_TYPES)))
if options.filename is None and options.directory is None:
raise OptionValueError("\n [!] Must provide a filename or directory of files to upload.\n")
try:
(options.proto, options.port) = options.port.split('/')
except Exception:
raise OptionValueError("\n [!] Invalid port provided. Must be something like info/0 or tcp/22\n")
Run(options)
| 43.37561
| 1,112
| 0.52834
|
f07b12824ee3722e5badbb911a58502d06fb5448
| 166
|
py
|
Python
|
python_api/machine_common_sense/mcs_pose.py
|
bzinberg/MCS
|
495562a0d4d0b1e3679b78f0f6fb568a1b9a9ae2
|
[
"Apache-2.0"
] | 1
|
2020-03-19T18:44:01.000Z
|
2020-03-19T18:44:01.000Z
|
python_api/machine_common_sense/mcs_pose.py
|
bzinberg/MCS
|
495562a0d4d0b1e3679b78f0f6fb568a1b9a9ae2
|
[
"Apache-2.0"
] | null | null | null |
python_api/machine_common_sense/mcs_pose.py
|
bzinberg/MCS
|
495562a0d4d0b1e3679b78f0f6fb568a1b9a9ae2
|
[
"Apache-2.0"
] | null | null | null |
from enum import Enum, unique
@unique
class MCS_Pose(Enum):
CRAWL = "CRAWL"
LIE = "LIE"
SQUAT = "SQUAT"
STAND = "STAND"
UNDEFINED = "UNDEFINED"
| 15.090909
| 29
| 0.608434
|
8f1c17992035c2d83fd70c3c6da4c33ebfe1da77
| 6,313
|
py
|
Python
|
umpnet/spherical_sampling.py
|
harryzhangOG/umpnet
|
25dabcfbd36ff59a6a2c8c77f52ce6bd307d705e
|
[
"MIT"
] | 18
|
2022-02-09T07:31:26.000Z
|
2022-03-18T01:25:50.000Z
|
umpnet/spherical_sampling.py
|
harryzhangOG/umpnet
|
25dabcfbd36ff59a6a2c8c77f52ce6bd307d705e
|
[
"MIT"
] | 2
|
2022-02-15T21:32:23.000Z
|
2022-03-22T01:43:08.000Z
|
umpnet/spherical_sampling.py
|
harryzhangOG/umpnet
|
25dabcfbd36ff59a6a2c8c77f52ce6bd307d705e
|
[
"MIT"
] | 4
|
2022-02-14T20:26:00.000Z
|
2022-03-04T18:53:34.000Z
|
# https://github.com/marc1701/area-beamforming/blob/SRP_dev/utilities.py
import numpy as np
from scipy.spatial.distance import cdist
# golden ratio
R = (1 + np.sqrt(5)) / 2
def cart_to_sph(cart_co_ords, return_r=False):
# transformation between co-ordinate systems
x, y, z = cart_co_ords[:,0], cart_co_ords[:,1], cart_co_ords[:,2]
r = np.linalg.norm(cart_co_ords, axis=1)
theta = np.arctan2(y,x) % (2*np.pi)
phi = np.arccos(z/r)
if return_r:
return np.array([r, theta, phi]).T
else:
return np.array([theta, phi]).T
def sph_to_cart(sph_co_ords):
# allow for lack of r value (i.e. for unit sphere)
if sph_co_ords.shape[1] < 3:
theta, phi = sph_co_ords[:,0], sph_co_ords[:,1]
r = 1
else:
r, theta, phi = sph_co_ords[:,0], sph_co_ords[:,1], sph_co_ords[:,2]
x = r * np.cos(theta) * np.sin(phi)
y = r * np.sin(theta) * np.sin(phi)
z = r * np.cos(phi)
return np.array([x, y, z]).T
def normalise(x, axis=None):
return x / np.linalg.norm(x, axis=axis).reshape(-1,1)
def regular(N, co_ords='sph'):
# find N for each dimension, resulting in smallest possible
# whole number of points above input N
N = np.ceil(np.sqrt(N))
# meshgrid of points
x, y = np.meshgrid(np.linspace(0, 2*np.pi, N),#[:-1],
np.linspace(0, np.pi, N))#[1:-1])
# [1:-1] avoids duplicate points at poles and wraparound
# reshape into a list of points
points = np.stack((x, y)).reshape(2,-1).T
if co_ords == 'cart':
return sph_to_cart(points)
elif co_ords == 'sph':
return np.array(points)
def geodesic(N_interp, return_points='vertices', co_ords='sph'):
# DEFINE INITIAL ICOSAHEDRON
# using orthogonal rectangle method
# http://sinestesia.co/blog/tutorials/python-icospheres/
vertices = np.array([[-1,R,0],
[1,R,0],
[-1,-R,0],
[1,-R,0],
[0,-1,R],
[0,1,R],
[0,-1,-R],
[0,1,-R],
[R,0,-1],
[R,0,1],
[-R,0,-1],
[-R,0,1]])
for n in range(N_interp + 1):
# CALCULATION OF SIDES
# find euclidian distances between all points -
# gives us a matrix of distances
euclid_dists = cdist(vertices, vertices)
# find list of adjacent vertices
sides_idx = np.where(
euclid_dists == np.min(euclid_dists[euclid_dists > 0]))
# concatenate output locations into one array
sides_idx = np.concatenate(
(sides_idx[0].reshape(-1,1), sides_idx[1].reshape(-1,1)), axis=1)
# remove duplicate sides_idx (there are many)
_, idx = np.unique(np.sort(sides_idx), axis=0, return_index=True)
sides_idx = sides_idx[idx]
# CALCULATION OF FACES
# set up empty array
faces_idx = np.array([], dtype=int)
for i in np.unique(sides_idx[:,0]):
# extract sides_idx related to each vertex
a = sides_idx[np.where(sides_idx[:,0] == i),1]
for j in a:
for l in j:
# find 3rd adjacent vertices common to both points
b = sides_idx[np.where(sides_idx[:,0] == l), 1]
intersect = np.intersect1d(a,b).reshape(-1,1)
for m in intersect:
# add faces_idx to array
faces_idx = np.append(faces_idx, np.array([i,l,m]))
# output is a 1D list, so we need to reshape it
faces_idx = faces_idx.reshape(-1,3)
# 3D matrix with xyz co-ordnates for vertices of all faces
v = vertices[faces_idx]
# if N_interp has been reached, break off here
if n == N_interp:
# FIND MIDPOINTS OF EACH FACE
# this finds the dodecahedron-like relation to the
# icosahedron at different interpolation levels
facepoints = v.sum(axis=1)/3
if return_points == 'faces':
vertices = facepoints
elif return_points == 'both':
vertices = np.append(vertices, facepoints, axis=0)
# move vertices to unit sphere
vertices = normalise(vertices, axis=1)
if co_ords == 'cart':
return vertices
elif co_ords == 'sph':
return cart_to_sph(vertices)
# INTERPOLATE AND CALCULATE NEW VERTEX LOCATIONS
# finding the midpoints all in one go
midpoints = ((v + np.roll(v,1,axis=1)) / 2).reshape(-1,3)
# # add new vertices to list
vertices = np.append(vertices, midpoints, axis=0)
# # find duplicate vertices
_, idx = np.unique(vertices, axis=0, return_index=True)
# # remove duplicates and re-sort vertices
vertices = vertices[np.sort(idx)]
def random(N, co_ords='sph'):
# random sampling, uniform distribution over spherical surface
theta = 2*np.pi * np.random.random(N)
phi = np.arccos(2*np.random.random(N) - 1)
if co_ords == 'cart':
return sph_to_cart(np.array([theta, phi]).T)
elif co_ords == 'sph':
return np.array([theta, phi]).T
def fibonacci(N, co_ords='sph'):
# quasi-regular sampling using fibonacci spiral
i = np.arange(N)
theta = 2*np.pi*i/R
# arccos as we use spherical co-ordinates rather than lat-lon
phi = np.arccos(-(2*i/N-1))
if co_ords == 'cart':
return sph_to_cart(np.array([theta, phi]).T)
elif co_ords == 'sph':
return np.array([theta, phi]).T % (2*np.pi)
if __name__=='__main__':
verts = fibonacci(16, co_ords='cart')
print(verts)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.array([p[0] for p in verts])
y = np.array([p[1] for p in verts])
z = np.array([p[2] for p in verts])
d = x ** 2 + y ** 2 + z ** 2
print(d)
ax.scatter(x, y, z, c='r', marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
| 28.436937
| 77
| 0.556629
|
9bd19c2a51f7692bf186dac80985f36a839194a1
| 10,783
|
py
|
Python
|
qa/rpc-tests/maxuploadtarget.py
|
mirzaei-ce/linux-shiabit
|
1c0e7371d1bb41e3efe20add0819d4e5050a3a0f
|
[
"MIT"
] | null | null | null |
qa/rpc-tests/maxuploadtarget.py
|
mirzaei-ce/linux-shiabit
|
1c0e7371d1bb41e3efe20add0819d4e5050a3a0f
|
[
"MIT"
] | null | null | null |
qa/rpc-tests/maxuploadtarget.py
|
mirzaei-ce/linux-shiabit
|
1c0e7371d1bb41e3efe20add0819d4e5050a3a0f
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import ShiabitTestFramework
from test_framework.util import *
from test_framework.comptool import wait_until
import time
'''
Test behavior of -maxuploadtarget.
* Verify that getdata requests for old blocks (>1week) are dropped
if uploadtarget has been reached.
* Verify that getdata requests for recent blocks are respecteved even
if uploadtarget has been reached.
* Verify that the upload counters are reset after 24 hours.
'''
# TestNode: bare-bones "peer". Used mostly as a conduit for a test to sending
# p2p messages to a node, generating the messages in the main testing logic.
class TestNode(NodeConnCB):
def __init__(self):
NodeConnCB.__init__(self)
self.connection = None
self.ping_counter = 1
self.last_pong = msg_pong()
self.block_receive_map = {}
def add_connection(self, conn):
self.connection = conn
self.peer_disconnected = False
def on_inv(self, conn, message):
pass
# Track the last getdata message we receive (used in the test)
def on_getdata(self, conn, message):
self.last_getdata = message
def on_block(self, conn, message):
message.block.calc_sha256()
try:
self.block_receive_map[message.block.sha256] += 1
except KeyError as e:
self.block_receive_map[message.block.sha256] = 1
# Spin until verack message is received from the node.
# We use this to signal that our test can begin. This
# is called from the testing thread, so it needs to acquire
# the global lock.
def wait_for_verack(self):
def veracked():
return self.verack_received
return wait_until(veracked, timeout=10)
def wait_for_disconnect(self):
def disconnected():
return self.peer_disconnected
return wait_until(disconnected, timeout=10)
# Wrapper for the NodeConn's send_message function
def send_message(self, message):
self.connection.send_message(message)
def on_pong(self, conn, message):
self.last_pong = message
def on_close(self, conn):
self.peer_disconnected = True
# Sync up with the node after delivery of a block
def sync_with_ping(self, timeout=30):
def received_pong():
return (self.last_pong.nonce == self.ping_counter)
self.connection.send_message(msg_ping(nonce=self.ping_counter))
success = wait_until(received_pong, timeout)
self.ping_counter += 1
return success
class MaxUploadTest(ShiabitTestFramework):
def __init__(self):
self.utxo = []
self.txouts = gen_return_txouts()
def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("SHIABITD", "shiabitd"),
help="shiabitd binary to test")
def setup_chain(self):
initialize_chain_clean(self.options.tmpdir, 2)
def setup_network(self):
# Start a node with maxuploadtarget of 200 MB (/24h)
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-maxuploadtarget=200", "-blockmaxsize=999000"]))
def mine_full_block(self, node, address):
# Want to create a full block
# We'll generate a 66k transaction below, and 14 of them is close to the 1MB block limit
for j in xrange(14):
if len(self.utxo) < 14:
self.utxo = node.listunspent()
inputs=[]
outputs = {}
t = self.utxo.pop()
inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
remchange = t["amount"] - Decimal("0.001000")
outputs[address]=remchange
# Create a basic transaction that will send change back to ourself after account for a fee
# And then insert the 128 generated transaction outs in the middle rawtx[92] is where the #
# of txouts is stored and is the only thing we overwrite from the original transaction
rawtx = node.createrawtransaction(inputs, outputs)
newtx = rawtx[0:92]
newtx = newtx + self.txouts
newtx = newtx + rawtx[94:]
# Appears to be ever so slightly faster to sign with SIGHASH_NONE
signresult = node.signrawtransaction(newtx,None,None,"NONE")
txid = node.sendrawtransaction(signresult["hex"], True)
# Mine a full sized block which will be these transactions we just created
node.generate(1)
def run_test(self):
# Before we connect anything, we first set the time on the node
# to be in the past, otherwise things break because the CNode
# time counters can't be reset backward after initialization
old_time = int(time.time() - 2*60*60*24*7)
self.nodes[0].setmocktime(old_time)
# Generate some old blocks
self.nodes[0].generate(130)
# test_nodes[0] will only request old blocks
# test_nodes[1] will only request new blocks
# test_nodes[2] will test resetting the counters
test_nodes = []
connections = []
for i in xrange(3):
test_nodes.append(TestNode())
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_nodes[i]))
test_nodes[i].add_connection(connections[i])
NetworkThread().start() # Start up network handling in another thread
[x.wait_for_verack() for x in test_nodes]
# Test logic begins here
# Now mine a big block
self.mine_full_block(self.nodes[0], self.nodes[0].getnewaddress())
# Store the hash; we'll request this later
big_old_block = self.nodes[0].getbestblockhash()
old_block_size = self.nodes[0].getblock(big_old_block, True)['size']
big_old_block = int(big_old_block, 16)
# Advance to two days ago
self.nodes[0].setmocktime(int(time.time()) - 2*60*60*24)
# Mine one more block, so that the prior block looks old
self.mine_full_block(self.nodes[0], self.nodes[0].getnewaddress())
# We'll be requesting this new block too
big_new_block = self.nodes[0].getbestblockhash()
new_block_size = self.nodes[0].getblock(big_new_block)['size']
big_new_block = int(big_new_block, 16)
# test_nodes[0] will test what happens if we just keep requesting the
# the same big old block too many times (expect: disconnect)
getdata_request = msg_getdata()
getdata_request.inv.append(CInv(2, big_old_block))
max_bytes_per_day = 200*1024*1024
daily_buffer = 144 * 1000000
max_bytes_available = max_bytes_per_day - daily_buffer
success_count = max_bytes_available / old_block_size
# 144MB will be reserved for relaying new blocks, so expect this to
# succeed for ~70 tries.
for i in xrange(success_count):
test_nodes[0].send_message(getdata_request)
test_nodes[0].sync_with_ping()
assert_equal(test_nodes[0].block_receive_map[big_old_block], i+1)
assert_equal(len(self.nodes[0].getpeerinfo()), 3)
# At most a couple more tries should succeed (depending on how long
# the test has been running so far).
for i in xrange(3):
test_nodes[0].send_message(getdata_request)
test_nodes[0].wait_for_disconnect()
assert_equal(len(self.nodes[0].getpeerinfo()), 2)
print "Peer 0 disconnected after downloading old block too many times"
# Requesting the current block on test_nodes[1] should succeed indefinitely,
# even when over the max upload target.
# We'll try 200 times
getdata_request.inv = [CInv(2, big_new_block)]
for i in xrange(200):
test_nodes[1].send_message(getdata_request)
test_nodes[1].sync_with_ping()
assert_equal(test_nodes[1].block_receive_map[big_new_block], i+1)
print "Peer 1 able to repeatedly download new block"
# But if test_nodes[1] tries for an old block, it gets disconnected too.
getdata_request.inv = [CInv(2, big_old_block)]
test_nodes[1].send_message(getdata_request)
test_nodes[1].wait_for_disconnect()
assert_equal(len(self.nodes[0].getpeerinfo()), 1)
print "Peer 1 disconnected after trying to download old block"
print "Advancing system time on node to clear counters..."
# If we advance the time by 24 hours, then the counters should reset,
# and test_nodes[2] should be able to retrieve the old block.
self.nodes[0].setmocktime(int(time.time()))
test_nodes[2].sync_with_ping()
test_nodes[2].send_message(getdata_request)
test_nodes[2].sync_with_ping()
assert_equal(test_nodes[2].block_receive_map[big_old_block], 1)
print "Peer 2 able to download old block"
[c.disconnect_node() for c in connections]
#stop and start node 0 with 1MB maxuploadtarget, whitelist 127.0.0.1
print "Restarting nodes with -whitelist=127.0.0.1"
stop_node(self.nodes[0], 0)
self.nodes[0] = start_node(0, self.options.tmpdir, ["-debug", "-whitelist=127.0.0.1", "-maxuploadtarget=1", "-blockmaxsize=999000"])
#recreate/reconnect 3 test nodes
test_nodes = []
connections = []
for i in xrange(3):
test_nodes.append(TestNode())
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_nodes[i]))
test_nodes[i].add_connection(connections[i])
NetworkThread().start() # Start up network handling in another thread
[x.wait_for_verack() for x in test_nodes]
#retrieve 20 blocks which should be enough to break the 1MB limit
getdata_request.inv = [CInv(2, big_new_block)]
for i in xrange(20):
test_nodes[1].send_message(getdata_request)
test_nodes[1].sync_with_ping()
assert_equal(test_nodes[1].block_receive_map[big_new_block], i+1)
getdata_request.inv = [CInv(2, big_old_block)]
test_nodes[1].send_message(getdata_request)
test_nodes[1].wait_for_disconnect()
assert_equal(len(self.nodes[0].getpeerinfo()), 3) #node is still connected because of the whitelist
print "Peer 1 still connected after trying to download old block (whitelisted)"
[c.disconnect_node() for c in connections]
if __name__ == '__main__':
MaxUploadTest().main()
| 40.385768
| 140
| 0.65594
|
3b376bc44618f8291c753440b800e755b21088be
| 182
|
py
|
Python
|
gogamechen3/api/wsgi/__init__.py
|
lolizeppelin/gogamechen3
|
4ff06f9042f1bb0cc22e1cc0b342967a829ae0f8
|
[
"MIT"
] | null | null | null |
gogamechen3/api/wsgi/__init__.py
|
lolizeppelin/gogamechen3
|
4ff06f9042f1bb0cc22e1cc0b342967a829ae0f8
|
[
"MIT"
] | null | null | null |
gogamechen3/api/wsgi/__init__.py
|
lolizeppelin/gogamechen3
|
4ff06f9042f1bb0cc22e1cc0b342967a829ae0f8
|
[
"MIT"
] | null | null | null |
from simpleutil.config import cfg
from gogamechen3.api.wsgi.config import register_opts
from gogamechen3 import common
CONF = cfg.CONF
register_opts(CONF.find_group(common.NAME))
| 20.222222
| 53
| 0.82967
|
7764ea891b4fc690e8bab5d9469e656c10c3a727
| 8,514
|
py
|
Python
|
game_control-master/controlling_steer.py
|
thedeveloperss/Gesture
|
02acb6954f7545e3e868714e90fd4b46e30a2db0
|
[
"Apache-2.0"
] | 1
|
2022-03-03T17:57:50.000Z
|
2022-03-03T17:57:50.000Z
|
game_control-master/controlling_steer.py
|
shivansh-mishraa/Gesture
|
dac29cfc6510b1ad1530cbcfaeef1b94daf9dbdd
|
[
"Apache-2.0"
] | null | null | null |
game_control-master/controlling_steer.py
|
shivansh-mishraa/Gesture
|
dac29cfc6510b1ad1530cbcfaeef1b94daf9dbdd
|
[
"Apache-2.0"
] | 1
|
2020-10-01T03:52:15.000Z
|
2020-10-01T03:52:15.000Z
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat July 11 2020
@author: Chanchal Choudhary
@discription: Game control by a steering wheel using openCV
This code is inspired by a project by Patel Digant https://github.com/pateldigant/gesture-gaming-python
"""
# directkeys.py is taken from https://stackoverflow.com/questions/14489013/simulate-python-keypresses-for-controlling-a-game
# inspired from pyimagesearch ball tracking https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/
from imutils.video import VideoStream
import numpy as np
import cv2
import imutils
import time
#importing directkeys for using press key and release key functions
from directkeys import W, A, S, D
from directkeys import PressKey, ReleaseKey
# define the lower and upper boundaries of the "blue" object in the HSV color space
#https://stackoverflow.com/questions/10948589/choosing-the-correct-upper-and-lower-hsv-boundaries-for-color-detection-withcv
blueLower = np.array([53, 187, 0])
blueUpper = np.array([180,255,255])
#Staring the webcam
video = VideoStream(src=0).start()
# allow the camera or video file to warm up
time.sleep(2.0)
initial = True
flag = False
current_key_pressed = set()
circle_radius = 30
#Defining window boundaries for each logically divided region
windowSize = 80
windowSize2 = 100
lr_counter = 0
# keep looping
while True:
keyPressed = False
keyPressed_lr = False
# grab the current frame
frame = video.read()
#My video frame was flipped horizontally. If your video is not flipped by default you can ommit this
frame = cv2.flip(frame,1);
# resize the frame, blur it, and convert it to the HSV color space
frame = imutils.resize(frame, width=600)
frame = imutils.resize(frame, height=300)
#storing height and width in varibles
height = frame.shape[0]
width = frame.shape[1]
blurred = cv2.GaussianBlur(frame, (11, 11), 0)
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
# crteate a mask for the blue color and perform opening and closing to remove any small
# blobs left in the mask
mask = cv2.inRange(hsv, blueLower, blueUpper)
kernel = np.ones((5,5),np.uint8)
#inspired by https://pythonprogramming.net/morphological-transformation-python-opencv-tutorial/
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
# find contours in the mask and initialize the current
# (x, y) center of the blue object
# divide the frame into seperate halves so that we can have one half control the turning/steering
# and other half control the forward and reverse.
up_mask = mask[0:height//2,0:width,]
down_mask = mask[height//2:height,width//4:3*width//4,]
#find the contours(blue object's boundary) in the left and right frame to find the center of the object
#syntax: (img,mode,method)
cnts_up = cv2.findContours(up_mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts_up = imutils.grab_contours(cnts_up)
center_up = None
cnts_down = cv2.findContours(down_mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts_down = imutils.grab_contours(cnts_down)
center_down = None
# only proceed if at least one contour was found
if len(cnts_up) > 0:
# find the largest contour in the mask, then use
# it to compute the minimum enclosing circle and centroid
c = max(cnts_up, key=cv2.contourArea)
#find circle of minimum area eclosing a 2D point set
((x, y), radius) = cv2.minEnclosingCircle(c)
#The function cv2.moments() gives a dictionary of all moment values calculated.
#Moments can be used to calculate COM,area,centroid,etc
M = cv2.moments(c)
# find the center from the moments 0.000001 is added to the denominator so that divide by
# zero exception doesn't occur
center_up = (int(M["m10"] / (M["m00"]+0.000001)), int(M["m01"] / (M["m00"]+0.000001)))
# only proceed if the radius meets a minimum size
if radius > circle_radius:
# draw the circle and centroid on the frame,
cv2.circle(frame, (int(x), int(y)), int(radius),
(0, 255, 255), 2)
cv2.circle(frame, center_up, 5, (0, 0, 255), -1)
#TOP LEFT is "A" key pressed and TOP RIGHT is for "D" key pressed
#the window size is kept 160 pixels in the center of the frame(80 pixels above the center and 80 below)
if center_up[0] < (width//2 - windowSize//2):
#cv2.putText(frame,'LEFT',(20,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255))
PressKey(A)
current_key_pressed.add(A)
keyPressed = True
keyPressed_lr = True
elif center_up[0] > (width//2 + windowSize//2):
#cv2.putText(frame,'RIGHT',(20,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255))
PressKey(D)
current_key_pressed.add(D)
keyPressed = True
keyPressed_lr = True
# only proceed if at least one contour was found
if len(cnts_down) > 0:
c2 = max(cnts_down, key=cv2.contourArea)
((x2, y2), radius2) = cv2.minEnclosingCircle(c2)
M2 = cv2.moments(c2)
center_down = (int(M2["m10"] / (M2["m00"]+0.000001)), int(M2["m01"] / (M2["m00"]+0.000001)))
center_down = (center_down[0]+width//4,center_down[1]+height//2)
# only proceed if the radius meets a minimum size
if radius2 > circle_radius:
# draw the circle and centroid on the frame,
cv2.circle(frame, (int(x2)+width//4, int(y2)+height//2), int(radius2),
(0, 255, 255), 2)
cv2.circle(frame, center_down, 5, (0, 0, 255), -1)
#Upper half of bottom half is "W" key pressed and bottom part of bottom half is for "s" key pressed
if (height//2) < center_down[1] < ((3*height)//4) and (width//4) < center_down[0] < ((3*width)//4):
#cv2.putText(frame,'UP',(200,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255))
PressKey(W)
keyPressed = True
current_key_pressed.add(W)
elif center_down[1] > ((3*height)//4 + 20) and (width//4) < center_down[0] < ((3*width)//4):
#cv2.putText(frame,'DOWN',(200,50),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255))
PressKey(S)
keyPressed = True
current_key_pressed.add(S)
# show the frame to our screen
frame_copy = frame.copy()
#draw box for left (A)
frame_copy = cv2.rectangle(frame_copy,(0,0),(width//2- windowSize//2,height//2 ),(255,255,255),1)
cv2.putText(frame_copy,'LEFT',(10,30),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255))
#draw box for left (D)
frame_copy = cv2.rectangle(frame_copy,(width//2 + windowSize//2,0),(width-2,height//2 ),(255,255,255),1)
cv2.putText(frame_copy,'RIGHT',(438,30),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255))
#draw box for left (W)
frame_copy = cv2.rectangle(frame_copy,(width//4,(height//2)+5),(3*width//4,3*height//4),(255,255,255),1)
cv2.putText(frame_copy,'UP',(width//4,(height//2)+33),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255))
#draw box for left (S)
frame_copy = cv2.rectangle(frame_copy,(width//4,((3*height)//4)+5),(3*width//4,height),(255,255,255),1)
cv2.putText(frame_copy,'DOWN',((3*width//4)-100,(height//2)+108),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255))
#display final frame
cv2.imshow("Frame", frame_copy)
#We need to release the pressed key if none of the key is pressed else the program will keep on sending
# the presskey command
if not keyPressed and len(current_key_pressed) != 0:
for key in current_key_pressed:
ReleaseKey(key)
current_key_pressed = set()
#to release keys for left/right with keys of up/down remain pressed
if not keyPressed_lr and ((A in current_key_pressed) or (D in current_key_pressed)):
if A in current_key_pressed:
ReleaseKey(A)
current_key_pressed.remove(A)
elif D in current_key_pressed:
ReleaseKey(D)
current_key_pressed.remove(D)
key = cv2.waitKey(1) & 0xFF
# if the 'q' key is pressed, stop the loop
if key == ord("q"):
break
video.stop()
# close all windows
cv2.destroyAllWindows()
| 40.932692
| 124
| 0.646934
|
a5126bc856b182ee5af1fb7c62be5d64686b19c6
| 7,159
|
py
|
Python
|
trinity/protocol/eth/proto.py
|
Uxio0/trinity
|
38fa6826b80bbda4f608e6dca366e468c362e3c2
|
[
"MIT"
] | null | null | null |
trinity/protocol/eth/proto.py
|
Uxio0/trinity
|
38fa6826b80bbda4f608e6dca366e468c362e3c2
|
[
"MIT"
] | null | null | null |
trinity/protocol/eth/proto.py
|
Uxio0/trinity
|
38fa6826b80bbda4f608e6dca366e468c362e3c2
|
[
"MIT"
] | null | null | null |
from typing import (
List,
Tuple,
TYPE_CHECKING,
Union,
)
from eth_typing import (
Hash32,
BlockNumber,
)
from eth.rlp.headers import BlockHeader
from eth.rlp.receipts import Receipt
from eth.rlp.transactions import BaseTransactionFields
from lahja import (
BroadcastConfig,
)
from p2p.kademlia import (
Node,
)
from p2p.protocol import (
Protocol,
)
from trinity.endpoint import TrinityEventBusEndpoint
from trinity.protocol.common.peer import ChainInfo
from trinity.rlp.block_body import BlockBody
from .commands import (
BlockBodies,
BlockHeaders,
GetBlockBodies,
GetBlockHeaders,
GetNodeData,
GetReceipts,
NewBlock,
NewBlockHashes,
NodeData,
Receipts,
Status,
Transactions,
)
from .events import (
SendBlockBodiesEvent,
SendBlockHeadersEvent,
SendNodeDataEvent,
SendReceiptsEvent,
SendTransactionsEvent,
)
from trinity._utils.logging import HasExtendedDebugLogger
if TYPE_CHECKING:
from .peer import ETHPeer # noqa: F401
# HasExtendedDebugLogger must come before Protocol so there's self.logger.debug2()
class ETHProtocol(HasExtendedDebugLogger, Protocol):
name = 'eth'
version = 63
_commands = (
Status,
NewBlockHashes,
Transactions,
GetBlockHeaders, BlockHeaders,
GetBlockBodies, BlockBodies,
NewBlock,
GetNodeData, NodeData,
GetReceipts, Receipts,
)
cmd_length = 17
peer: 'ETHPeer'
def send_handshake(self, chain_info: ChainInfo) -> None:
resp = {
'protocol_version': self.version,
'network_id': chain_info.network_id,
'td': chain_info.total_difficulty,
'best_hash': chain_info.block_hash,
'genesis_hash': chain_info.genesis_hash,
}
cmd = Status(self.cmd_id_offset, self.snappy_support)
self.logger.debug2("Sending ETH/Status msg: %s", resp)
self.transport.send(*cmd.encode(resp))
#
# Node Data
#
def send_get_node_data(self, node_hashes: Tuple[Hash32, ...]) -> None:
cmd = GetNodeData(self.cmd_id_offset, self.snappy_support)
header, body = cmd.encode(node_hashes)
self.transport.send(header, body)
def send_node_data(self, nodes: Tuple[bytes, ...]) -> None:
cmd = NodeData(self.cmd_id_offset, self.snappy_support)
header, body = cmd.encode(nodes)
self.transport.send(header, body)
#
# Block Headers
#
def send_get_block_headers(
self,
block_number_or_hash: Union[BlockNumber, Hash32],
max_headers: int,
skip: int,
reverse: bool) -> None:
"""Send a GetBlockHeaders msg to the remote.
This requests that the remote send us up to max_headers, starting from
block_number_or_hash if reverse is False or ending at block_number_or_hash if reverse is
True.
"""
cmd = GetBlockHeaders(self.cmd_id_offset, self.snappy_support)
data = {
'block_number_or_hash': block_number_or_hash,
'max_headers': max_headers,
'skip': skip,
'reverse': reverse
}
header, body = cmd.encode(data)
self.transport.send(header, body)
def send_block_headers(self, headers: Tuple[BlockHeader, ...]) -> None:
cmd = BlockHeaders(self.cmd_id_offset, self.snappy_support)
header, body = cmd.encode(headers)
self.transport.send(header, body)
#
# Block Bodies
#
def send_get_block_bodies(self, block_hashes: Tuple[Hash32, ...]) -> None:
cmd = GetBlockBodies(self.cmd_id_offset, self.snappy_support)
header, body = cmd.encode(block_hashes)
self.transport.send(header, body)
def send_block_bodies(self, blocks: List[BlockBody]) -> None:
cmd = BlockBodies(self.cmd_id_offset, self.snappy_support)
header, body = cmd.encode(blocks)
self.transport.send(header, body)
#
# Receipts
#
def send_get_receipts(self, block_hashes: Tuple[Hash32, ...]) -> None:
cmd = GetReceipts(self.cmd_id_offset, self.snappy_support)
header, body = cmd.encode(block_hashes)
self.transport.send(header, body)
def send_receipts(self, receipts: List[List[Receipt]]) -> None:
cmd = Receipts(self.cmd_id_offset, self.snappy_support)
header, body = cmd.encode(receipts)
self.transport.send(header, body)
#
# Transactions
#
def send_transactions(self, transactions: List[BaseTransactionFields]) -> None:
cmd = Transactions(self.cmd_id_offset, self.snappy_support)
header, body = cmd.encode(transactions)
self.transport.send(header, body)
class ProxyETHProtocol:
"""
An ``ETHProtocol`` that can be used outside of the process that runs the peer pool. Any
action performed on this class is delegated to the process that runs the peer pool.
"""
def __init__(self,
remote: Node,
event_bus: TrinityEventBusEndpoint,
broadcast_config: BroadcastConfig):
self.remote = remote
self._event_bus = event_bus
self._broadcast_config = broadcast_config
#
# Node Data
#
def send_get_node_data(self, node_hashes: Tuple[Hash32, ...]) -> None:
raise NotImplementedError("Not yet implemented")
def send_node_data(self, nodes: Tuple[bytes, ...]) -> None:
self._event_bus.broadcast_nowait(
SendNodeDataEvent(self.remote, nodes),
self._broadcast_config,
)
#
# Block Headers
#
def send_get_block_headers(
self,
block_number_or_hash: Union[BlockNumber, Hash32],
max_headers: int,
skip: int,
reverse: bool) -> None:
raise NotImplementedError("Not yet implemented")
def send_block_headers(self, headers: Tuple[BlockHeader, ...]) -> None:
self._event_bus.broadcast_nowait(
SendBlockHeadersEvent(self.remote, headers),
self._broadcast_config,
)
#
# Block Bodies
#
def send_get_block_bodies(self, block_hashes: Tuple[Hash32, ...]) -> None:
raise NotImplementedError("Not yet implemented")
def send_block_bodies(self, blocks: List[BlockBody]) -> None:
self._event_bus.broadcast_nowait(
SendBlockBodiesEvent(self.remote, blocks),
self._broadcast_config,
)
#
# Receipts
#
def send_get_receipts(self, block_hashes: Tuple[Hash32, ...]) -> None:
raise NotImplementedError("Not yet implemented")
def send_receipts(self, receipts: List[List[Receipt]]) -> None:
self._event_bus.broadcast_nowait(
SendReceiptsEvent(self.remote, receipts),
self._broadcast_config,
)
#
# Transactions
#
def send_transactions(self, transactions: List[BaseTransactionFields]) -> None:
self._event_bus.broadcast_nowait(
SendTransactionsEvent(self.remote, transactions),
self._broadcast_config,
)
| 29.705394
| 96
| 0.645062
|
e5ad1fbba95f740fa623f281120a97fce30af287
| 384
|
py
|
Python
|
ai/python/dailyPy/2019/py1118_iter_extend.py
|
littlepoem/learning
|
00b46b09c9ee496addf604bee8b349bc0cf7e6ff
|
[
"Apache-2.0"
] | null | null | null |
ai/python/dailyPy/2019/py1118_iter_extend.py
|
littlepoem/learning
|
00b46b09c9ee496addf604bee8b349bc0cf7e6ff
|
[
"Apache-2.0"
] | null | null | null |
ai/python/dailyPy/2019/py1118_iter_extend.py
|
littlepoem/learning
|
00b46b09c9ee496addf604bee8b349bc0cf7e6ff
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 反向迭代
list1 = list(range(10))
print(list1)
list2 = list(reversed(list1))
print(list2)
# 同时迭代 zip
# zip(a, b) 会生成一个可返回元组 (x, y) 的迭代器,其中 x 来自 a,y 来自 b
# 迭代长度跟参数中最短序列长度一致
names = ['Kate', 'Tom', 'Jim']
ages = [18, 19, 20]
for name, age in zip(names, ages):
print(name,age)
dict1= dict(zip(names,ages))
print(dict1)
| 10.666667
| 51
| 0.609375
|
14d02c4ad629ee91d9d12d86e0f6b56778b61b36
| 16,701
|
py
|
Python
|
test/test_parameter_bytes_conversion.py
|
yochaytz/py-c3d
|
215a92be036b5c56839cdcf16264440da3e1a3ee
|
[
"MIT"
] | null | null | null |
test/test_parameter_bytes_conversion.py
|
yochaytz/py-c3d
|
215a92be036b5c56839cdcf16264440da3e1a3ee
|
[
"MIT"
] | null | null | null |
test/test_parameter_bytes_conversion.py
|
yochaytz/py-c3d
|
215a92be036b5c56839cdcf16264440da3e1a3ee
|
[
"MIT"
] | null | null | null |
import c3d
import struct
import unittest
import numpy as np
def genByteWordArr(word, shape):
''' Generate a multi-dimensional byte array from a specific word.
'''
arr = np.array(word)
for d in shape[::-1]:
arr = arr[np.newaxis].repeat(d, 0)
return arr, [len(word)] + [d for d in shape]
def genRndByteArr(wordlen, shape, pad):
''' Generate a multi-dimensional byte array with random data.
'''
tot_len = wordlen + pad*wordlen
arr = np.empty(shape, dtype=np.dtype('S'+str(tot_len)))
for i in np.ndindex(arr.shape):
bytes = np.random.randint(21, 126, wordlen).astype(np.uint8)
if pad:
bytes = np.hstack((bytes, np.array([b'255']*wordlen, dtype=np.uint8)))
arr[i] = bytes.tobytes()
return arr, [tot_len] + [d for d in shape]
def genRndFloatArr(shape, rnd, range=(-1e6, 1e6)):
''' Generate a multi-dimensional array of 32 bit floating point data.
'''
return rnd.uniform(range[0], range[1], shape)
class ParameterValueTest(unittest.TestCase):
''' Test read Parameter arrays
'''
RANGE_8_BIT = (-127, 127)
RANGE_16_BIT = (-1e4, 1e4)
RANGE_32_BIT = (-1e6, 1e6)
RANGE_8_UNSIGNED_BIT = (0, 255)
RANGE_16_UNSIGNED_BIT = (0, 1e4)
RANGE_32_UNSIGNED_BIT = (0, 1e6)
TEST_ITERATIONS = 1000
def setUp(self):
self.rnd = np.random.default_rng()
self.dtypes = c3d.DataTypes(c3d.PROCESSOR_INTEL)
def test_a_param_float32(self):
''' Verify a single 32 bit floating point value is parsed correctly
'''
for i in range(ParameterValueTest.TEST_ITERATIONS):
value = np.float32(self.rnd.uniform(*ParameterValueTest.RANGE_32_BIT))
bytes = struct.pack('<f', value)
P = c3d.Param('FLOAT_TEST', self.dtypes, bytes_per_element=4, dimensions=[1], bytes=bytes)
value_out = P.float_value
assert value == value_out, 'Parameter float was not read correctly. Was %f, expected %f' %\
(value_out, value)
def test_b_param_int32(self):
''' Verify a single 32 bit integer value is parsed correctly
'''
for i in range(ParameterValueTest.TEST_ITERATIONS):
value = np.int32(self.rnd.uniform(*ParameterValueTest.RANGE_32_BIT))
bytes = struct.pack('<i', value)
P = c3d.Param('INT32_TEST', self.dtypes, bytes_per_element=4, dimensions=[1], bytes=bytes)
value_out = P.int32_value
assert value == value_out, 'Parameter int32 was not read correctly. Was %f, expected %f' %\
(value_out, value)
def test_b_param_uint32(self):
''' Verify a single 32 bit unsigned integer value is parsed correctly
'''
for i in range(ParameterValueTest.TEST_ITERATIONS):
value = np.uint32(self.rnd.uniform(*ParameterValueTest.RANGE_32_UNSIGNED_BIT))
bytes = struct.pack('<I', value)
P = c3d.Param('UINT32_TEST', self.dtypes, bytes_per_element=4, dimensions=[1], bytes=bytes)
value_out = P.int32_value
assert value == value_out, 'Parameter uint32 was not read correctly. Was %f, expected %f' %\
(value_out, value)
def test_b_param_int16(self):
''' Verify a single 16 bit integer value is parsed correctly
'''
for i in range(ParameterValueTest.TEST_ITERATIONS):
value = np.int16(self.rnd.uniform(*ParameterValueTest.RANGE_16_BIT))
bytes = struct.pack('<h', value)
P = c3d.Param('INT16_TEST', self.dtypes, bytes_per_element=2, dimensions=[1], bytes=bytes)
value_out = P.int16_value
assert value == value_out, 'Parameter int16 was not read correctly. Was %f, expected %f' %\
(value_out, value)
def test_b_param_uint16(self):
''' Verify a single 16 bit unsigned integer value is parsed correctly
'''
for i in range(ParameterValueTest.TEST_ITERATIONS):
value = np.uint16(self.rnd.uniform(*ParameterValueTest.RANGE_16_UNSIGNED_BIT))
bytes = struct.pack('<H', value)
P = c3d.Param('UINT16_TEST', self.dtypes, bytes_per_element=2, dimensions=[1], bytes=bytes)
value_out = P.uint16_value
assert value == value_out, 'Parameter uint16 was not read correctly. Was %f, expected %f' %\
(value_out, value)
def test_b_param_int8(self):
''' Verify a single 8 bit integer value is parsed correctly
'''
for i in range(ParameterValueTest.TEST_ITERATIONS):
value = np.int8(self.rnd.uniform(*ParameterValueTest.RANGE_8_BIT))
bytes = struct.pack('<b', value)
P = c3d.Param('INT8_TEST', self.dtypes, bytes_per_element=1, dimensions=[1], bytes=bytes)
value_out = P.int8_value
assert value == value_out, 'Parameter int8 was not read correctly. Was %f, expected %f' %\
(value_out, value)
def test_b_param_uint8(self):
''' Verify a single 8 bit unsigned integer value is parsed correctly
'''
for i in range(ParameterValueTest.TEST_ITERATIONS):
value = np.uint8(self.rnd.uniform(*ParameterValueTest.RANGE_8_UNSIGNED_BIT))
bytes = struct.pack('<B', value)
P = c3d.Param('UINT8_TEST', self.dtypes, bytes_per_element=1, dimensions=[1], bytes=bytes)
value_out = P.uint8_value
assert value == value_out, 'Parameter uint8 was not read correctly. Was %f, expected %f' %\
(value_out, value)
class ParameterArrayTest(unittest.TestCase):
''' Test read Parameter arrays
'''
SHAPES = [[7, 6, 5], [7, 5, 3], [7, 3], [19]]
def setUp(self):
self.rnd = np.random.default_rng()
self.dtypes = c3d.DataTypes(c3d.PROCESSOR_INTEL)
def test_a_parse_float32_array(self):
''' Verify array of 32 bit floating point values are parsed correctly
'''
flt_range = (-1e6, 1e6)
for shape in ParameterArrayTest.SHAPES:
arr = self.rnd.uniform(flt_range[0], flt_range[1], size=shape).astype(np.float32)
P = c3d.Param('FLOAT_TEST', self.dtypes, bytes_per_element=4, dimensions=arr.shape, bytes=arr.T.tobytes())
arr_out = P.float32_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'float_array' converted shape"
assert np.all(arr.T == arr_out), 'Value mismatch when reading float array'
def test_b_parse_float64_array(self):
''' Verify array of 64 bit floating point values are parsed correctly
'''
flt_range = (-1e6, 1e6)
for shape in ParameterArrayTest.SHAPES:
arr = self.rnd.uniform(flt_range[0], flt_range[1], size=shape).astype(np.float64)
P = c3d.Param('FLOAT_TEST', self.dtypes, bytes_per_element=4, dimensions=arr.shape, bytes=arr.T.tobytes())
arr_out = P.float64_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'float_array' converted shape"
assert np.all(arr.T == arr_out), 'Value mismatch when reading float array'
def test_c_parse_int32_array(self):
''' Verify array of 32 bit integer values are parsed correctly
'''
flt_range = (-1e6, 1e6)
for shape in ParameterArrayTest.SHAPES:
arr = self.rnd.uniform(flt_range[0], flt_range[1], size=shape).astype(np.int32)
P = c3d.Param('INT32_TEST', self.dtypes, bytes_per_element=4, dimensions=arr.shape, bytes=arr.T.tobytes())
arr_out = P.int32_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'int32_array' converted shape"
assert np.all(arr.T == arr_out), 'Value mismatch when reading int32 array'
def test_d_parse_uint32_array(self):
''' Verify array of 32 bit unsigned integer values are parsed correctly
'''
flt_range = (0, 1e6)
for shape in ParameterArrayTest.SHAPES:
arr = self.rnd.uniform(flt_range[0], flt_range[1], size=shape).astype(np.uint32)
P = c3d.Param('UINT32_TEST', self.dtypes, bytes_per_element=4, dimensions=arr.shape, bytes=arr.T.tobytes())
arr_out = P.uint32_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'uint32_array' converted shape"
assert np.all(arr.T == arr_out), 'Value mismatch when reading uint32 array'
def test_e_parse_int16_array(self):
''' Verify array of 16 bit integer values are parsed correctly
'''
flt_range = (-1e4, 1e4)
for shape in ParameterArrayTest.SHAPES:
arr = self.rnd.uniform(flt_range[0], flt_range[1], size=shape).astype(np.int16)
P = c3d.Param('INT16_TEST', self.dtypes, bytes_per_element=2, dimensions=arr.shape, bytes=arr.T.tobytes())
arr_out = P.int16_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'int32_array' converted shape"
assert np.all(arr.T == arr_out), 'Value mismatch when reading int32 array'
def test_f_parse_uint16_array(self):
''' Verify array of 16 bit unsigned integer values are parsed correctly
'''
flt_range = (0, 1e4)
for shape in ParameterArrayTest.SHAPES:
arr = self.rnd.uniform(flt_range[0], flt_range[1], size=shape).astype(np.uint16)
P = c3d.Param('UINT16_TEST', self.dtypes, bytes_per_element=2, dimensions=arr.shape, bytes=arr.T.tobytes())
arr_out = P.uint16_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'uint32_array' converted shape"
assert np.all(arr.T == arr_out), 'Value mismatch when reading uint32 array'
def test_g_parse_int8_array(self):
''' Verify array of 8 bit integer values are parsed correctly
'''
flt_range = (-127, 127)
for shape in ParameterArrayTest.SHAPES:
arr = self.rnd.uniform(flt_range[0], flt_range[1], size=shape).astype(np.int8)
P = c3d.Param('INT8_TEST', self.dtypes, bytes_per_element=1, dimensions=arr.shape, bytes=arr.T.tobytes())
arr_out = P.int8_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'int32_array' converted shape"
assert np.all(arr.T == arr_out), 'Value mismatch when reading int32 array'
def test_h_parse_uint8_array(self):
''' Verify array of 8 bit unsigned integer values are parsed correctly
'''
flt_range = (0, 255)
for shape in ParameterArrayTest.SHAPES:
arr = self.rnd.uniform(flt_range[0], flt_range[1], size=shape).astype(np.uint8)
P = c3d.Param('UINT8_TEST', self.dtypes, bytes_per_element=1, dimensions=arr.shape, bytes=arr.T.tobytes())
arr_out = P.uint8_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'uint32_array' converted shape"
assert np.all(arr.T == arr_out), 'Value mismatch when reading uint32 array'
def test_i_parse_byte_array(self):
''' Verify byte arrays are parsed correctly
'''
word = b'WRIST'
# 1 dims
arr = np.array(word).repeat(3).repeat(3).repeat(3)
P = c3d.Param('BYTE_TEST', self.dtypes, bytes_per_element=1, dimensions=arr.shape, bytes=arr.T.tobytes())
arr_out = P.bytes_array
assert arr.shape[1:] == arr_out.shape, "Mismatch in 'bytes_array' converted shape"
assert np.all(arr.tobytes() == arr_out), 'Mismatch in reading single dimensional byte array'
# 4 dims
arr, shape = genByteWordArr(word, [5, 4, 3])
P = c3d.Param('BYTE_TEST', self.dtypes, bytes_per_element=1, dimensions=shape, bytes=arr.T.tobytes())
arr_out = P.bytes_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'bytes_array' converted shape. Was %s, expected %s" %\
(str(arr_out.shape), str(arr.T.shape))
for i in np.ndindex(arr_out.shape):
assert np.all(arr[i[::-1]] == arr_out[i]), "Mismatch in 'bytes_array' converted value at index %s" % str(i)
# 5 dims
arr, shape = genByteWordArr(word, [6, 5, 4, 3])
P = c3d.Param('BYTE_TEST', self.dtypes, bytes_per_element=1, dimensions=shape, bytes=arr.T.tobytes())
arr_out = P.bytes_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'bytes_array' converted shape. Was %s, expected %s" %\
(str(arr_out.shape), str(arr.T.shape))
for i in np.ndindex(arr_out.shape):
assert np.all(arr[i[::-1]] == arr_out[i]), "Mismatch in 'bytes_array' converted value at index %s" % str(i)
def test_j_parse_string_array(self):
''' Verify repeated word arrays are parsed correctly
'''
word = b'ANCLE'
# 3 dims
arr, shape = genByteWordArr(word, [7, 3])
P = c3d.Param('STRING_TEST', self.dtypes, bytes_per_element=-1, dimensions=shape, bytes=arr.T.tobytes())
arr_out = P.string_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'string_array' converted shape. Was %s, expected %s" %\
(str(arr_out.shape), str(arr.T.shape))
for i in np.ndindex(arr_out.shape):
assert self.dtypes.decode_string(arr[i[::-1]]) == arr_out[i],\
"Mismatch in 'string_array' converted value at index %s" % str(i)
# 4 dims
arr, shape = genByteWordArr(word, [5, 4, 3])
P = c3d.Param('STRING_TEST', self.dtypes, bytes_per_element=-1, dimensions=shape, bytes=arr.T.tobytes())
arr_out = P.string_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'string_array' converted shape. Was %s, expected %s" %\
(str(arr_out.shape), str(arr.T.shape))
for i in np.ndindex(arr_out.shape):
assert self.dtypes.decode_string(arr[i[::-1]]) == arr_out[i],\
"Mismatch in 'string_array' converted value at index %s" % str(i)
# 5 dims
arr, shape = genByteWordArr(word, [6, 5, 4, 3])
P = c3d.Param('STRING_TEST', self.dtypes, bytes_per_element=-1, dimensions=shape, bytes=arr.T.tobytes())
arr_out = P.string_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'string_array' converted shape. Was %s, expected %s" %\
(str(arr_out.shape), str(arr.T.shape))
for i in np.ndindex(arr_out.shape):
assert self.dtypes.decode_string(arr[i[::-1]]) == arr_out[i],\
"Mismatch in 'string_array' converted value at index %s" % str(i)
def test_k_parse_random_string_array(self):
''' Verify random word arrays are parsed correctly
'''
##
# RND
# 3 dims
for wlen in range(10):
arr, shape = genRndByteArr(wlen, [7, 3], wlen > 5)
P = c3d.Param('STRING_TEST', self.dtypes, bytes_per_element=-1, dimensions=shape, bytes=arr.T.tobytes())
arr_out = P.string_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'string_array' converted shape. Was %s, expected %s" %\
(str(arr_out.shape), str(arr.T.shape))
for i in np.ndindex(arr_out.shape):
assert self.dtypes.decode_string(arr[i[::-1]]) == arr_out[i],\
"Mismatch in 'string_array' converted value at index %s" % str(i)
# 4 dims
for wlen in range(10):
arr, shape = genRndByteArr(wlen, [7, 5, 3], wlen > 5)
P = c3d.Param('STRING_TEST', self.dtypes, bytes_per_element=-1, dimensions=shape, bytes=arr.T.tobytes())
arr_out = P.string_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'string_array' converted shape. Was %s, expected %s" %\
(str(arr_out.shape), str(arr.T.shape))
for i in np.ndindex(arr_out.shape):
assert self.dtypes.decode_string(arr[i[::-1]]) == arr_out[i],\
"Mismatch in 'string_array' converted value at index %s" % str(i)
# 5 dims
for wlen in range(10):
arr, shape = genRndByteArr(wlen, [7, 6, 5, 3], wlen > 5)
P = c3d.Param('STRING_TEST', self.dtypes, bytes_per_element=-1, dimensions=shape, bytes=arr.T.tobytes())
arr_out = P.string_array
assert arr.T.shape == arr_out.shape, "Mismatch in 'string_array' converted shape. Was %s, expected %s" %\
(str(arr_out.shape), str(arr.T.shape))
for i in np.ndindex(arr_out.shape):
assert self.dtypes.decode_string(arr[i[::-1]]) == arr_out[i],\
"Mismatch in 'string_array' converted value at index %s" % str(i)
if __name__ == '__main__':
unittest.main()
| 47.717143
| 119
| 0.619663
|
cc6f22a21ce13c643d10ca6ca4cbbcb6c15c15fb
| 13,572
|
py
|
Python
|
saleor/dashboard/supplier/views.py
|
glosoftgroup/ps254-backend
|
f9c9d798ae8eba29a3a502c6913c2238c4d3906c
|
[
"BSD-3-Clause"
] | null | null | null |
saleor/dashboard/supplier/views.py
|
glosoftgroup/ps254-backend
|
f9c9d798ae8eba29a3a502c6913c2238c4d3906c
|
[
"BSD-3-Clause"
] | 6
|
2021-02-08T20:20:06.000Z
|
2022-03-11T23:18:59.000Z
|
saleor/dashboard/supplier/views.py
|
glosoftgroup/ps254-backend
|
f9c9d798ae8eba29a3a502c6913c2238c4d3906c
|
[
"BSD-3-Clause"
] | null | null | null |
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import JsonResponse
from django.db.models import Q
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.template.response import TemplateResponse
from django.utils.http import is_safe_url
from django.utils.translation import pgettext_lazy
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import make_password
from django.contrib.auth.decorators import login_required, permission_required
from django.core.paginator import Paginator, PageNotAnInteger, InvalidPage, EmptyPage
from ...core.utils import get_paginator_items
from ..views import staff_member_required
from ...userprofile.models import User, UserTrail
from ...customer.models import Customer
from ...supplier.models import Supplier, AddressBook
from ...decorators import permission_decorator, user_trail
import logging
debug_logger = logging.getLogger('debug_logger')
info_logger = logging.getLogger('info_logger')
error_logger = logging.getLogger('error_logger')
def users(request):
try:
users = Supplier.objects.all().order_by('-id')
page = request.GET.get('page', 1)
paginator = Paginator(users, 10)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except InvalidPage:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
user_trail(request.user.name, 'accessed suppliers list page', 'view')
info_logger.info('User: ' + str(request.user.name) + ' accessed the view users page')
if request.GET.get('initial'):
return HttpResponse(paginator.num_pages)
else:
ctx = {'users': users, 'pn': paginator.num_pages}
return TemplateResponse(request, 'dashboard/supplier/pagination/users2.html', ctx)
except TypeError as e:
error_logger.error(e)
return HttpResponse('error accessing users')
@staff_member_required
def user_paginate(request):
page = int(request.GET.get('page', 1))
list_sz = request.GET.get('size')
p2_sz = request.GET.get('psize')
select_sz = request.GET.get('select_size')
if request.GET.get('gid'):
users = Supplier.objects.filter(groups__id=request.GET.get('gid'))
if p2_sz:
paginator = Paginator(users, int(p2_sz))
users = paginator.page(page)
return TemplateResponse(request,'dashboard/supplier/pagination/paginate.html',{'users':users})
paginator = Paginator(users, 10)
users = paginator.page(page)
return TemplateResponse(request,'dashboard/supplier/pagination/p2.html',{'users':users, 'pn':paginator.num_pages,'sz':10,'gid':request.GET.get('gid')})
else:
users = Supplier.objects.all().order_by('-id')
if list_sz:
paginator = Paginator(users, int(list_sz))
users = paginator.page(page)
return TemplateResponse(request,'dashboard/supplier/pagination/p2.html',{'users':users, 'pn':paginator.num_pages,'sz':list_sz, 'gid':0})
else:
paginator = Paginator(users, 10)
if p2_sz:
paginator = Paginator(users, int(p2_sz))
users = paginator.page(page)
return TemplateResponse(request,'dashboard/supplier/pagination/paginate.html',{'users':users})
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except InvalidPage:
groups = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
return TemplateResponse(request,'dashboard/supplier/pagination/paginate.html',{'users':users})
@staff_member_required
def user_search(request):
if request.is_ajax():
page = request.GET.get('page', 1)
list_sz = request.GET.get('size', 10)
p2_sz = request.GET.get('psize')
q = request.GET.get('q')
if list_sz is None:
sz = 10
else:
sz = list_sz
if q is not None:
users = Supplier.objects.filter(
Q(name__icontains=q) |
Q(email__icontains=q) | Q(mobile__icontains=q)).order_by('id')
paginator = Paginator(users, 10)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except InvalidPage:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
if p2_sz:
users = paginator.page(page)
return TemplateResponse(request, 'dashboard/supplier/pagination/paginate.html', {'users': users})
return TemplateResponse(request, 'dashboard/supplier/pagination/search.html',
{'users': users, 'pn': paginator.num_pages, 'sz': sz, 'q': q})
@staff_member_required
@permission_decorator('userprofile.add_user')
def user_add(request):
try:
permissions = Permission.objects.all()
groups = Group.objects.all()
user_trail(request.user.name, 'accessed add supplier page','view')
info_logger.info('User: '+str(request.user.name)+' accessed supplier create page')
return TemplateResponse(request, 'dashboard/supplier/add_user.html',{'permissions':permissions, 'groups':groups})
except TypeError as e:
error_logger.error(e)
return HttpResponse('error accessing add users page')
@staff_member_required
def supplier_add_modal(request):
try:
return TemplateResponse(request, 'dashboard/supplier/_modal_add_supplier.html', {})
except Exception as e:
error_logger.error(e)
return HttpResponse('error accessing add suppliers page')
@staff_member_required
def supplier_add(request):
try:
return TemplateResponse(request, 'dashboard/supplier/add_supplier.html',{})
except Exception as e:
error_logger.error(e)
return HttpResponse('error accessing add suppliers page')
@staff_member_required
def fetch_suppliers(request):
suppliers = Supplier.objects.all()
ctx = {'suppliers':suppliers}
return TemplateResponse(request, 'dashboard/supplier/refreshed_supplier.html',ctx)
@staff_member_required
@csrf_exempt
def user_process(request):
user = Supplier.objects.all()
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
code = request.POST.get('code')
fax = request.POST.get('fax')
city = request.POST.get('city')
website = request.POST.get('website','')
street1 = request.POST.get('street1')
street2 = request.POST.get('street2')
mobile = request.POST.get('mobile')
image= request.FILES.get('image')
groups = request.POST.getlist('groups[]')
new_user = Supplier.objects.create(
name = name,
email = email,
code = code,
fax = fax,
city = city,
website = website,
street1 = street1,
street2 = street2,
mobile = mobile,
image = image
)
try:
new_user.save()
except:
error_logger.info('Error when saving ')
last_id = Supplier.objects.latest('id')
if groups:
permissions = Permission.objects.filter(group__name__in=groups)
last_id.user_permissions.add(*permissions)
gps = Group.objects.filter(name__in=groups)
last_id.groups.add(*gps)
last_id.save()
user_trail(request.user.name, 'created user: '+str(name),'add')
info_logger.info('User: '+str(request.user.name)+' created user:'+str(name))
return HttpResponse(last_id.id)
def user_detail(request, pk):
user = get_object_or_404(Supplier, pk=pk)
return TemplateResponse(request, 'dashboard/supplier/detail.html', {'user':user})
def user_delete(request, pk):
user = get_object_or_404(Supplier, pk=pk)
if request.method == 'POST':
user.delete()
user_trail(request.user.name, 'deleted supplier: '+ str(user.name))
return HttpResponse('success')
def user_edit(request, pk):
user = get_object_or_404(Supplier, pk=pk)
#addresses = user.get_address()
ctx = {'user': user}
user_trail(request.user.name, 'accessed edit page for supplier '+ str(user.name),'update')
info_logger.info('User: '+str(request.user.name)+' accessed edit page for supplier: '+str(user.name))
return TemplateResponse(request, 'dashboard/supplier/edit_user.html', ctx)
def user_update(request, pk):
user = get_object_or_404(Supplier, pk=pk)
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
code = request.POST.get('code')
fax = request.POST.get('fax')
city = request.POST.get('city')
website = request.POST.get('website','')
street1 = request.POST.get('street1')
street2 = request.POST.get('street2')
mobile = request.POST.get('mobile')
image= request.FILES.get('image')
if image :
user.name = name
user.email = email
user.code = code
user.fax = fax
user.city = city
user.website = website
user.street2 = street2
user.street1 = street1
user.mobile = mobile
user.image = image
user.save()
user_trail(request.user.name, 'updated supplier: '+ str(user.name))
info_logger.info('User: '+str(request.user.name)+' updated supplier: '+str(user.name))
return HttpResponse("success with image")
else:
user.name = name
user.email = email
user.code = code
user.fax = fax
user.city = city
user.website = website
user.street2 = street2
user.street1 = street1
user.mobile = mobile
user.save()
user_trail(request.user.name, 'updated supplier: '+ str(user.name))
info_logger.info('User: '+str(request.user.name)+' updated supplier: '+str(user.name))
return HttpResponse("success without image")
@csrf_exempt
def user_assign_permission(request):
if request.method == 'POST':
user_id = request.POST.get('user_id')
user = get_object_or_404(User, pk=user_id)
user_has_permissions = Permission.objects.filter(user=user)
login_status = request.POST.get('check_login')
permission_list = request.POST.getlist('checklist[]')
if login_status == 'inactive':
user.is_staff = False
user.is_active = False
user.user_permissions.remove(*user_has_permissions)
user.save()
user_trail(request.user.name, 'deactivated and removed all permissions for user: '+ str(user.name))
info_logger.info('User: '+str(request.user.name)+' deactivated and removed all permissions for user: '+str(user.name))
return HttpResponse('deactivated')
else:
if user_has_permissions in permission_list:
not_in_user_permissions = list(set(permission_list) - set(user_has_permissions))
user.is_staff = True
user.is_active = True
user.user_permissions.add(*not_in_user_permissions)
user.save()
user_trail(request.user.name, 'assigned permissions for user: '+ str(user.name))
info_logger.info('User: '+str(request.user)+' assigned permissions for user: '+str(user.name))
return HttpResponse('permissions added')
else:
not_in_user_permissions = list(set(permission_list) - set(user_has_permissions))
user.is_staff = True
user.is_active = True
user.user_permissions.remove(*user_has_permissions)
user.user_permissions.add(*not_in_user_permissions)
user.save()
user_trail(request.user.name, 'assigned permissions for user: '+ str(user.name))
info_logger.info('User: '+str(request.user.name)+' assigned permissions for user: '+str(user.name))
return HttpResponse('permissions updated')
@staff_member_required
def address_add(request,pk):
if request.is_ajax():
if request.method == 'GET':
if pk:
pk = pk
ctx = {'supplier_pk':pk}
return TemplateResponse(request, 'dashboard/supplier/_address_add.html', ctx)
if request.method == 'POST':
city = request.POST.get('city')
email = request.POST.get('email')
postal_code = request.POST.get('postal_code')
phone = request.POST.get('phone')
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
contact_name = request.POST.get('contact_name')
job_position = request.POST.get('job_position')
supplier = get_object_or_404(Supplier, pk=pk)
address = AddressBook.objects.create(
city=city,
email=email,
postal_code =postal_code,
phone = phone,
first_name=first_name,
last_name=last_name,
contact_name=contact_name,
job_position=job_position
)
address.save()
supplier.addresses.add(address)
ctx = {'address': address}
return TemplateResponse(request,
'dashboard/supplier/_newContact.html',
ctx)
@staff_member_required
def refresh_contact(request, pk=None):
if request.method == 'GET':
if pk:
user = get_object_or_404(Supplier, pk=pk)
ctx = {'user': user}
return TemplateResponse(request,
'dashboard/supplier/_newContact.html',
ctx)
return HttpResponse('Post request not accepted')
@staff_member_required
def contact_delete(request, pk):
address = get_object_or_404(AddressBook, pk=pk)
if request.method == 'POST':
address.delete()
messages.success(
request,
pgettext_lazy(
'Dashboard message', 'Deleted contact %s') % address)
if pk:
if request.is_ajax():
script = "'#tr"+str(pk)+"'"
return HttpResponse(script)
ctx = {'address': address}
return TemplateResponse(request,
'dashboard/supplier/modal_delete.html',
ctx)
def user_trails(request):
users = UserTrail.objects.all().order_by('id')
user_trail(request.user.name, 'accessed user trail page')
info_logger.info('User: '+str(request.user.name)+' accessed the user trail page')
return TemplateResponse(request, 'dashboard/users/trail.html', {'users':users})
| 36
| 153
| 0.714854
|
834e3d8d10b01c56df8b40c64003547202e06fb7
| 3,469
|
py
|
Python
|
stable-marriages/stable_marriage_test.py
|
dawidvdh/programmers-introduction-to-mathematics
|
2345a118f055bb7f98140ee58d5332c6691e1fc1
|
[
"MIT"
] | 2,915
|
2018-10-29T12:42:36.000Z
|
2022-03-30T19:12:12.000Z
|
stable-marriages/stable_marriage_test.py
|
dawidvdh/programmers-introduction-to-mathematics
|
2345a118f055bb7f98140ee58d5332c6691e1fc1
|
[
"MIT"
] | 34
|
2018-12-04T23:58:40.000Z
|
2021-10-04T16:22:41.000Z
|
stable-marriages/stable_marriage_test.py
|
dawidvdh/programmers-introduction-to-mathematics
|
2345a118f055bb7f98140ee58d5332c6691e1fc1
|
[
"MIT"
] | 272
|
2018-11-04T06:53:40.000Z
|
2022-03-28T17:31:45.000Z
|
from assertpy import assert_that
from stable_marriage import Suited
from stable_marriage import Suitor
from stable_marriage import stable_marriage
from stable_marriage import verify_stable
def test_eq():
suitor = Suitor(0, [0, 1])
suitor2 = Suitor(0, [1, 0])
suited = Suited(0, [0, 1])
suited2 = Suited(0, [1, 0])
assert_that(suitor).is_equal_to(suitor2)
assert_that(suited).is_equal_to(suited2)
def test_repr():
suitor = Suitor(0, [0, 1])
suited = Suited(0, [0, 1])
assert_that(repr(suitor)).is_equal_to("Suitor(0)")
assert_that(repr(suited)).is_equal_to("Suited(0)")
def test_verify_stable_stable():
suitors = [Suitor(0, [0, 1]), Suitor(1, [1, 0])]
suiteds = [Suited(0, [0, 1]), Suited(1, [1, 0])]
marriage = {suitors[0]: suiteds[0], suitors[1]: suiteds[1]}
assert_that(verify_stable(suitors, suiteds, marriage)).is_true()
def test_verify_stable_unstable():
suitors = [Suitor(0, [1, 0]), Suitor(1, [1, 0])]
suiteds = [Suited(0, [0, 1]), Suited(1, [0, 1])]
marriage = {suitors[0]: suiteds[0], suitors[1]: suiteds[1]}
result = verify_stable(suitors, suiteds, marriage)
assert_that(result).is_instance_of(tuple)
assert_that(result[0]).is_false()
assert_that(result[1]).is_equal_to((suitors[0], suiteds[1]))
def test_stable_marriage_two():
suitors = [Suitor(0, [0, 1]), Suitor(1, [1, 0])]
suiteds = [Suited(0, [0, 1]), Suited(1, [1, 0])]
marriage = stable_marriage(suitors, suiteds)
assert_that(marriage).is_equal_to(
{suitors[0]: suiteds[0], suitors[1]: suiteds[1]})
assert_that(verify_stable(suitors, suiteds, marriage)).is_true()
def test_stable_marriage_six():
suitors = [
Suitor(0, [3, 5, 4, 2, 1, 0]),
Suitor(1, [2, 3, 1, 0, 4, 5]),
Suitor(2, [5, 2, 1, 0, 3, 4]),
Suitor(3, [0, 1, 2, 3, 4, 5]),
Suitor(4, [4, 5, 1, 2, 0, 3]),
Suitor(5, [0, 1, 2, 3, 4, 5]),
]
suiteds = [
Suited(0, [3, 5, 4, 2, 1, 0]),
Suited(1, [2, 3, 1, 0, 4, 5]),
Suited(2, [5, 2, 1, 0, 3, 4]),
Suited(3, [0, 1, 2, 3, 4, 5]),
Suited(4, [4, 5, 1, 2, 0, 3]),
Suited(5, [0, 1, 2, 3, 4, 5]),
]
marriage = stable_marriage(suitors, suiteds)
assert_that(marriage).is_equal_to({
suitors[0]: suiteds[3],
suitors[1]: suiteds[2],
suitors[2]: suiteds[5],
suitors[3]: suiteds[0],
suitors[4]: suiteds[4],
suitors[5]: suiteds[1],
})
assert_that(verify_stable(suitors, suiteds, marriage)).is_true()
def test_stable_marriage_all_tied():
suitors = [
Suitor(0, [5, 4, 3, 2, 1, 0]),
Suitor(1, [5, 4, 3, 2, 1, 0]),
Suitor(2, [5, 4, 3, 2, 1, 0]),
Suitor(3, [5, 4, 3, 2, 1, 0]),
Suitor(4, [5, 4, 3, 2, 1, 0]),
Suitor(5, [5, 4, 3, 2, 1, 0]),
]
suiteds = [
Suited(0, [0, 1, 2, 3, 4, 5]),
Suited(1, [0, 1, 2, 3, 4, 5]),
Suited(2, [0, 1, 2, 3, 4, 5]),
Suited(3, [0, 1, 2, 3, 4, 5]),
Suited(4, [0, 1, 2, 3, 4, 5]),
Suited(5, [0, 1, 2, 3, 4, 5]),
]
marriage = stable_marriage(suitors, suiteds)
assert_that(marriage).is_equal_to({
suitors[0]: suiteds[5],
suitors[1]: suiteds[4],
suitors[2]: suiteds[3],
suitors[3]: suiteds[2],
suitors[4]: suiteds[1],
suitors[5]: suiteds[0],
})
assert_that(verify_stable(suitors, suiteds, marriage)).is_true()
| 31.252252
| 68
| 0.556356
|
fb23dd46ca3ec87d1049c30d81d92085a64fdda6
| 5,263
|
py
|
Python
|
server/particles.py
|
vanjo9800/gravityBalls
|
921374a8d1a8c392d331e1d8a8164c35f1045f00
|
[
"MIT"
] | 1
|
2019-05-07T14:12:32.000Z
|
2019-05-07T14:12:32.000Z
|
server/particles.py
|
vanjo9800/gravityBalls
|
921374a8d1a8c392d331e1d8a8164c35f1045f00
|
[
"MIT"
] | null | null | null |
server/particles.py
|
vanjo9800/gravityBalls
|
921374a8d1a8c392d331e1d8a8164c35f1045f00
|
[
"MIT"
] | null | null | null |
import math
import random
def addVectors(al1,al2):
""" Returns the sum of two vectors """
angle2,length2 = al2
angle1,length1 = al1
x = math.sin(angle1) * length1 + math.sin(angle2) * length2
y = math.cos(angle1) * length1 + math.cos(angle2) * length2
angle = 0.5 * math.pi - math.atan2(y, x)
length = math.hypot(x, y)
return (angle, length)
def collide(p1, p2):
""" Tests whether two particles overlap
If they do, make them bounce
i.e. update their angle, speed and position """
dx = p1.x - p2.x
dy = p1.y - p2.y
dist = math.hypot(dx, dy)
if dist < p1.size + p2.size:
angle = math.atan2(dy, dx) + 0.5 * math.pi
total_mass = p1.mass + p2.mass
(p1.angle, p1.speed) = addVectors((p1.angle, p1.speed*(p1.mass-p2.mass)/total_mass), (angle, 2*p2.speed*p2.mass/total_mass))
(p2.angle, p2.speed) = addVectors((p2.angle, p2.speed*(p2.mass-p1.mass)/total_mass), (angle+math.pi, 2*p1.speed*p1.mass/total_mass))
elasticity = p1.elasticity * p2.elasticity
p1.speed *= elasticity
p2.speed *= elasticity
overlap = 0.5*(p1.size + p2.size - dist+1)
p1.x += math.sin(angle)*overlap
p1.y -= math.cos(angle)*overlap
p2.x -= math.sin(angle)*overlap
p2.y += math.cos(angle)*overlap
class Particle:
""" A circular object with a velocity, size and mass """
def __init__(self, xy, size, mass=1):
self.x,self.y = xy
self.size = size
self.colour = (0, 0, 255)
self.thickness = 0
self.speed = 0
self.angle = 0
self.mass = mass
self.drag = 2
self.elasticity = 0.9
def move(self):
""" Update position based on speed, angle
Update speed based on drag """
#(self.angle, self.speed) = addVectors((self.angle, self.speed), gravity)
self.x += math.sin(self.angle) * self.speed
self.y -= math.cos(self.angle) * self.speed
self.speed *= self.drag
def mouseMove(self, x, y):
""" Change angle and speed to move towards a given point """
dx = x - self.x
dy = y - self.y
self.angle = 0.5*math.pi + math.atan2(dy, dx)
self.speed = math.hypot(dx, dy) * 0.1
class Environment:
""" Defines the boundary of a simulation and its properties """
def __init__(self, width_height):
self.width,self.height = width_height
self.particles = []
self.colour = (255,255,255)
self.mass_of_air = 0.2
self.elasticity = 0.75
self.acceleration = None
def addParticles(self, n=1, **kargs):
""" Add n particles with properties given by keyword arguments """
for i in range(n):
size = kargs.get('size', random.randint(10, 20))
mass = kargs.get('mass', random.randint(100, 10000))
x = kargs.get('x', random.uniform(size, self.width - size))
y = kargs.get('y', random.uniform(size, self.height - size))
particle = Particle((x, y), size, mass)
particle.speed = kargs.get('speed', random.random())
particle.angle = kargs.get('angle', random.uniform(0, math.pi*2))
particle.colour = kargs.get('colour', (0, 0, 255))
particle.drag = (particle.mass/(particle.mass + self.mass_of_air)) ** particle.size
self.particles.append(particle)
def update(self):
""" Moves particles and tests for collisions with the walls and each other """
for i, particle in enumerate(self.particles):
particle.move()
if self.acceleration:
particle.accelerate(self.acceleration)
self.bounce(particle)
for particle2 in self.particles[i+1:]:
collide(particle, particle2)
def bounce(self, particle):
""" Tests whether a particle has hit the boundary of the environment """
if particle.x > self.width - particle.size:
particle.x = 2*(self.width - particle.size) - particle.x
particle.angle = - particle.angle
particle.speed *= self.elasticity
elif particle.x < particle.size:
particle.x = 2*particle.size - particle.x
particle.angle = - particle.angle
particle.speed *= self.elasticity
if particle.y > self.height - particle.size:
particle.y = 2*(self.height - particle.size) - particle.y
particle.angle = math.pi - particle.angle
particle.speed *= self.elasticity
elif particle.y < particle.size:
particle.y = 2*particle.size - particle.y
particle.angle = math.pi - particle.angle
particle.speed *= self.elasticity
def findParticle(self, x, y):
""" Returns any particle that occupies position x, y """
for particle in self.particles:
if math.hypot(particle.x - x, particle.y - y) <= particle.size:
return particle
return None
| 36.804196
| 141
| 0.560707
|
21af8e4b5380a3aa21e81ef859c35dac7cdc0324
| 1,697
|
py
|
Python
|
test/test_mutators.py
|
mehrdad-shokri/Bashfuscator
|
7487348da2d0112213f8540ae28bf12b652f924a
|
[
"MIT"
] | 859
|
2018-08-07T02:06:01.000Z
|
2022-03-24T10:00:13.000Z
|
test/test_mutators.py
|
mehrdad-shokri/Bashfuscator
|
7487348da2d0112213f8540ae28bf12b652f924a
|
[
"MIT"
] | 25
|
2018-09-13T19:30:17.000Z
|
2022-01-05T17:53:35.000Z
|
test/test_mutators.py
|
mehrdad-shokri/Bashfuscator
|
7487348da2d0112213f8540ae28bf12b652f924a
|
[
"MIT"
] | 123
|
2018-08-11T02:48:36.000Z
|
2022-03-30T13:46:57.000Z
|
from datetime import datetime
import os
import pytest
from subprocess import STDOUT, PIPE, Popen
from bashfuscator.core.engine.obfuscation_handler import ObfuscationHandler
inputCommand = "echo 'It works!'"
expectedOutput = "It works!\n"
obHandler = ObfuscationHandler()
commandObNames = [(c.longName, s.longName) for c in obHandler.cmdObfuscators for s in c.stubs]
stringObNames = [(s.longName, None) for s in obHandler.strObfuscators]
tokenObNames = [(t.longName, None) for t in obHandler.tokObfuscators]
encoderObNames = [(e.longName, None) for e in obHandler.encoders]
compressorObNames = [(c.longName, None) for c in obHandler.compressors]
mutators = commandObNames + stringObNames + tokenObNames + encoderObNames + compressorObNames
obHandler = ObfuscationHandler()
@pytest.mark.parametrize("mutatorName,stubName", mutators)
def test_mutators(mutatorName, stubName):
try:
for i in range(100):
payload = obHandler.genObfuscationLayer(inputCommand, userMutator=mutatorName, userStub=stubName)
proc = Popen(payload, executable="bash", stdout=PIPE, stderr=STDOUT, shell=True, universal_newlines=True)
payloadOutput, __ = proc.communicate()
assert(expectedOutput == payloadOutput)
except AssertionError:
if not os.path.exists("failing"):
os.mkdir("failing")
date = datetime.now()
timestamp = str(date.month) + "." + str(date.day) + "." + str(date.year) + "-" + str(date.hour) + "." + str(date.minute) + "." + str(date.second)
with open("failing/" + mutatorName.replace("/", ".") + "-" + timestamp + ".sh", "w") as errorFile:
errorFile.write(payload)
raise
| 38.568182
| 153
| 0.695345
|
4df043d61d6da23e6220ee89734d8b0b3e186611
| 3,508
|
py
|
Python
|
Old model/Old v2/scenario_module.py
|
zenmood/IndoorFarmWiz
|
0f5075007cbd1d15c83ed3aef820ec3d72048a90
|
[
"MIT"
] | 11
|
2020-06-28T04:30:26.000Z
|
2022-03-26T08:40:47.000Z
|
Old model/Old v2/scenario_module.py
|
zenmood/IndoorFarmWiz
|
0f5075007cbd1d15c83ed3aef820ec3d72048a90
|
[
"MIT"
] | 4
|
2020-07-27T19:45:27.000Z
|
2020-07-28T13:58:41.000Z
|
Old model/Old v2/scenario_module.py
|
zenmood/IndoorFarmWiz
|
0f5075007cbd1d15c83ed3aef820ec3d72048a90
|
[
"MIT"
] | null | null | null |
# INPUT SCENARIO CLASS #
class Scenario(object):
def __init__(self):
self.currency = None # The type of currency
self.country = None # The country of the farm (no caps)
self.capex = None # The starting amount of money or loan
self.repayment = None # The loan repayment amount
self.interest = None # The loan interest rate
self.lights = None # The name of the lights
self.crop = None # The type of crop grown
self.area = None # The cultivation area of the farm
self.surface = None # The surface area of the farm interior
self.volume = None # The volume of the farm
self.building = None # The type of building for the farm facility
self.system = None # The type of vertical farming cultivation system
self.co2 = None # Does the farm have CO2 enrichment?
self.energy = None # What is the energy pricing for your local region?
self.energy_standing = None
self.renewable = None # What percentage of your energy supply is produced in-house from a renewable supply?
self.water = None # What is the water pricing for your local area?
self.water_standing = None
self.toutdoors = None # Average outdoor temperature
self.crop_price = None # Crop price per kilo
self.farm_staff = None # The number of staff working on the farm
self.salaries = None # The annual salaries of permanent employees (Management and founders)
self.standard_wage = None # The £/h wages for farm hands.
self.insurance = None # The cost of insurance premium
self.coverage = None # The level of coverage from insurance ( high, med or low)
self.days = None # The number of days you would like to run your simulation
def __str__(self):
"""String representation"""
return """This is the representation of a scenario with values:
lights : {}
crop : {}
""".format(self.lights, self.crop)
def getScenario(self, input_file):
import json
with open(input_file) as f:
inputs = json.load(f)
self.currency = inputs['currency']
self.country = inputs['country']
self.capex = inputs["start_loan"]
self.repayment = inputs["loan_repayment"]
self.interest = inputs['loan_interest']
self.lights = inputs['lights']
self.crop = inputs['crop']
self.area = inputs['grow_area']
self.surface = inputs['surface_area']
self.volume = inputs['farm_volume']
self.building = inputs['building_type']
self.rent = inputs['rental_costs']
self.system = inputs['grow_system']
self.co2 = inputs['co2_enrichment']
self.energy = inputs['energy_price']
self.energy_standing = inputs['energy_standing_charge']
self.water = inputs['water_price']
self.water_standing = inputs['water_standing_charge']
self.renewable = inputs['ratio_of_renewable_energy_created_to_sourced']
self.toutdoors = inputs['average_outdoor_temperature']
self.crop_price = inputs['crop_price_per_kilo']
self.farm_staff = inputs['number_of_farm_staff']
self.salaries = inputs['annual_salaries_of_employees']
self.standard_wage = inputs['standard_wage']
self.insurance = inputs['insurance_premium']
self.coverage = inputs['insurance_coverage']
self.days = inputs['days_for_simulation']
| 48.054795
| 116
| 0.651083
|
a65d335085a5b4fc1613ed3db7cf60ad7f55ecab
| 4,508
|
py
|
Python
|
test/unit/services/eth/test_eth_extension_block_cleanup_service.py
|
doubleukay/bxgateway
|
ac01fc9475c039cf4255576dd4ecd6bff6c48f69
|
[
"MIT"
] | 21
|
2019-11-06T17:37:41.000Z
|
2022-03-28T07:18:33.000Z
|
test/unit/services/eth/test_eth_extension_block_cleanup_service.py
|
doubleukay/bxgateway
|
ac01fc9475c039cf4255576dd4ecd6bff6c48f69
|
[
"MIT"
] | 4
|
2019-11-06T22:08:00.000Z
|
2021-12-08T06:20:51.000Z
|
test/unit/services/eth/test_eth_extension_block_cleanup_service.py
|
doubleukay/bxgateway
|
ac01fc9475c039cf4255576dd4ecd6bff6c48f69
|
[
"MIT"
] | 10
|
2020-08-05T15:58:16.000Z
|
2022-02-07T23:51:10.000Z
|
import os
from mock import MagicMock
from bxcommon.services.extension_transaction_service import ExtensionTransactionService
from bxcommon.services.transaction_service import TransactionService
from bxcommon.test_utils import helpers
from bxcommon.utils import convert
from bxcommon.utils.object_hash import Sha256Hash, SHA256_HASH_LEN
from bxgateway.messages.eth.protocol.new_block_eth_protocol_message import NewBlockEthProtocolMessage
from bxgateway.services.eth.eth_extension_block_cleanup_service import EthExtensionBlockCleanupService
from bxgateway.testing.abstract_block_cleanup_service_test import AbstractBlockCleanupServiceTest
from bxgateway.services.eth.abstract_eth_block_cleanup_service import AbstractEthBlockCleanupService
from bxgateway.services.eth.eth_block_queuing_service import EthBlockQueuingService
class EthExtensionBlockCleanupServiceTest(AbstractBlockCleanupServiceTest):
def setUp(self) -> None:
super().setUp()
node_conn = MagicMock()
self.node.block_queuing_service = EthBlockQueuingService(self.node, node_conn)
self.node.connection_pool.add(1, "127.0.0.0", 8002, node_conn)
def _get_sample_block(self, file_path):
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(file_path))))
with open(os.path.join(root_dir, "samples/eth_sample_block.txt")) as sample_file:
btc_block = sample_file.read().strip("\n")
buf = bytearray(convert.hex_to_bytes(btc_block))
parsed_block = NewBlockEthProtocolMessage(msg_bytes=buf)
return parsed_block
def _test_mark_blocks_and_request_cleanup(self):
marked_block = Sha256Hash(binary=helpers.generate_bytearray(SHA256_HASH_LEN))
prev_block = Sha256Hash(binary=helpers.generate_bytearray(SHA256_HASH_LEN))
tracked_blocks = []
self.cleanup_service.on_new_block_received(marked_block, prev_block)
self.transaction_service.track_seen_short_ids(marked_block, [])
for _ in range(self.block_confirmations_count - 1):
tracked_block = Sha256Hash(binary=helpers.generate_bytearray(SHA256_HASH_LEN))
self.transaction_service.track_seen_short_ids(tracked_block, [])
tracked_blocks.append(tracked_block)
unmarked_block = Sha256Hash(binary=helpers.generate_bytearray(SHA256_HASH_LEN))
self.assertIsNone(self.cleanup_service.last_confirmed_block)
self.cleanup_service.mark_blocks_and_request_cleanup([marked_block, *tracked_blocks])
self.assertEqual(marked_block, self.cleanup_service.last_confirmed_block)
self.assertTrue(self.cleanup_service.is_marked_for_cleanup(marked_block))
self.assertFalse(self.cleanup_service.is_marked_for_cleanup(unmarked_block))
self.assertEqual(marked_block, self.cleanup_service.last_confirmed_block)
def _test_block_cleanup(self):
block_msg = self._get_sample_block(self._get_file_path())
transactions = list(block_msg.txns())
block_hash = block_msg.block_hash()
transaction_hashes = []
for idx, tx in enumerate(transactions):
tx_hash = tx.hash()
tx_content = str(tx).encode()
self.transaction_service.set_transaction_contents(tx_hash, tx_content)
self.transaction_service.assign_short_id(tx_hash, idx + 1)
transaction_hashes.append(tx_hash)
self.cleanup_service._block_hash_marked_for_cleanup.add(block_hash)
self.cleanup_service.clean_block_transactions(block_msg, self.transaction_service)
self.assertEqual(0, self.transaction_service._total_tx_contents_size)
for tx_hash in transaction_hashes:
self.assertFalse(self.transaction_service.has_transaction_contents(tx_hash))
self.node.post_block_cleanup_tasks.assert_called_once_with(
block_hash,
[],
transaction_hashes
)
def test_mark_blocks_and_request_cleanup(self):
self._test_mark_blocks_and_request_cleanup()
def test_block_cleanup(self):
self._test_block_cleanup()
def test_block_confirmation_cleanup(self):
self._test_block_confirmation_cleanup()
def _get_transaction_service(self) -> TransactionService:
return ExtensionTransactionService(self.node, 1)
def _get_cleanup_service(self) -> AbstractEthBlockCleanupService:
return EthExtensionBlockCleanupService(self.node, 1)
def _get_file_path(self) -> str:
return __file__
| 47.957447
| 102
| 0.76331
|
f41c25d0cd16554447fbfd1dc0e39e6dfc1d3f80
| 43,861
|
py
|
Python
|
lektor/builder.py
|
evilham/lektor
|
a2f32e620f8978504c2b898dc2e50a6bf71ec30e
|
[
"BSD-3-Clause"
] | null | null | null |
lektor/builder.py
|
evilham/lektor
|
a2f32e620f8978504c2b898dc2e50a6bf71ec30e
|
[
"BSD-3-Clause"
] | null | null | null |
lektor/builder.py
|
evilham/lektor
|
a2f32e620f8978504c2b898dc2e50a6bf71ec30e
|
[
"BSD-3-Clause"
] | null | null | null |
import hashlib
import os
import shutil
import sqlite3
import stat
import sys
import tempfile
from collections import deque
from collections import namedtuple
from contextlib import contextmanager
from itertools import chain
import click
from lektor.build_programs import builtin_build_programs
from lektor.buildfailures import FailureController
from lektor.constants import PRIMARY_ALT
from lektor.context import Context
from lektor.reporter import reporter
from lektor.sourcesearch import find_files
from lektor.utils import fs_enc
from lektor.utils import process_extra_flags
from lektor.utils import prune_file_and_folder
def create_tables(con):
can_disable_rowid = ("3", "8") <= tuple(sqlite3.sqlite_version.split("."))
if can_disable_rowid:
without_rowid = "without rowid"
else:
without_rowid = ""
try:
con.execute(
"""
create table if not exists artifacts (
artifact text,
source text,
source_mtime integer,
source_size integer,
source_checksum text,
is_dir integer,
is_primary_source integer,
primary key (artifact, source)
) %s;
"""
% without_rowid
)
con.execute(
"""
create index if not exists artifacts_source on artifacts (
source
);
"""
)
con.execute(
"""
create table if not exists artifact_config_hashes (
artifact text,
config_hash text,
primary key (artifact)
) %s;
"""
% without_rowid
)
con.execute(
"""
create table if not exists dirty_sources (
source text,
primary key (source)
) %s;
"""
% without_rowid
)
con.execute(
"""
create table if not exists source_info (
path text,
alt text,
lang text,
type text,
source text,
title text,
primary key (path, alt, lang)
) %s;
"""
% without_rowid
)
finally:
con.close()
class BuildState:
def __init__(self, builder, path_cache):
self.builder = builder
self.named_temporaries = set()
self.updated_artifacts = []
self.failed_artifacts = []
self.path_cache = path_cache
@property
def pad(self):
"""The pad for this buildstate."""
return self.builder.pad
@property
def env(self):
"""The environment backing this buildstate."""
return self.builder.env
@property
def config(self):
"""The config for this buildstate."""
return self.builder.pad.db.config
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
self.close()
def close(self):
for fn in self.named_temporaries:
try:
os.remove(fn)
except OSError:
pass
def notify_failure(self, artifact, exc_info):
"""Notify about a failure. This marks a failed artifact and stores
a failure.
"""
self.failed_artifacts.append(artifact)
self.builder.failure_controller.store_failure(artifact.artifact_name, exc_info)
reporter.report_failure(artifact, exc_info)
def make_named_temporary(self, identifier=None):
"""Creates a named temporary file and returns the filename for it.
This can be usedful in some scenarious when building with external
tools.
"""
tmpdir = os.path.join(self.builder.meta_path, "tmp")
try:
os.makedirs(tmpdir)
except OSError:
pass
fn = os.path.join(
dir,
"nt-%s-%s.tmp" % (identifier or "generic", os.urandom(20).encode("hex")),
)
self.named_temporaries.add(fn)
return fn
def get_file_info(self, filename):
if filename:
return self.path_cache.get_file_info(filename)
return None
def to_source_filename(self, filename):
return self.path_cache.to_source_filename(filename)
def get_virtual_source_info(self, virtual_source_path):
virtual_source = self.pad.get(virtual_source_path)
if not virtual_source:
return VirtualSourceInfo(virtual_source_path, None, None)
mtime = virtual_source.get_mtime(self.path_cache)
checksum = virtual_source.get_checksum(self.path_cache)
return VirtualSourceInfo(virtual_source_path, mtime, checksum)
def connect_to_database(self):
"""Returns a database connection for the build state db."""
return self.builder.connect_to_database()
def get_destination_filename(self, artifact_name):
"""Returns the destination filename for an artifact name."""
return os.path.join(
self.builder.destination_path,
artifact_name.strip("/").replace("/", os.path.sep),
)
def artifact_name_from_destination_filename(self, filename):
"""Returns the artifact name for a destination filename."""
dst = self.builder.destination_path
filename = os.path.join(dst, filename)
if filename.startswith(dst):
filename = filename[len(dst) :].lstrip(os.path.sep)
if os.path.altsep:
filename = filename.lstrip(os.path.altsep)
return filename.replace(os.path.sep, "/")
def new_artifact(
self, artifact_name, sources=None, source_obj=None, extra=None, config_hash=None
):
"""Creates a new artifact and returns it."""
dst_filename = self.get_destination_filename(artifact_name)
key = self.artifact_name_from_destination_filename(dst_filename)
return Artifact(
self,
key,
dst_filename,
sources,
source_obj=source_obj,
extra=extra,
config_hash=config_hash,
)
def artifact_exists(self, artifact_name):
"""Given an artifact name this checks if it was already produced."""
dst_filename = self.get_destination_filename(artifact_name)
return os.path.exists(dst_filename)
def get_artifact_dependency_infos(self, artifact_name, sources):
con = self.connect_to_database()
try:
cur = con.cursor()
rv = list(self._iter_artifact_dependency_infos(cur, artifact_name, sources))
finally:
con.close()
return rv
def _iter_artifact_dependency_infos(self, cur, artifact_name, sources):
"""This iterates over all dependencies as file info objects."""
cur.execute(
"""
select source, source_mtime, source_size,
source_checksum, is_dir
from artifacts
where artifact = ?
""",
[artifact_name],
)
rv = cur.fetchall()
found = set()
for path, mtime, size, checksum, is_dir in rv:
if "@" in path:
yield path, VirtualSourceInfo(path, mtime, checksum)
else:
file_info = FileInfo(
self.env, path, mtime, size, checksum, bool(is_dir)
)
filename = self.to_source_filename(file_info.filename)
found.add(filename)
yield filename, file_info
# In any case we also iterate over our direct sources, even if the
# build state does not know about them yet. This can be caused by
# an initial build or a change in original configuration.
for source in sources:
filename = self.to_source_filename(source)
if filename not in found:
yield source, None
def write_source_info(self, info):
"""Writes the source info into the database. The source info is
an instance of :class:`lektor.build_programs.SourceInfo`.
"""
reporter.report_write_source_info(info)
source = self.to_source_filename(info.filename)
con = self.connect_to_database()
try:
cur = con.cursor()
for lang, title in info.title_i18n.items():
cur.execute(
"""
insert or replace into source_info
(path, alt, lang, type, source, title)
values (?, ?, ?, ?, ?, ?)
""",
[info.path, info.alt, lang, info.type, source, title],
)
con.commit()
finally:
con.close()
def prune_source_infos(self):
"""Remove all source infos of files that no longer exist."""
MAX_VARS = 999 # Default SQLITE_MAX_VARIABLE_NUMBER.
con = self.connect_to_database()
to_clean = []
try:
cur = con.cursor()
cur.execute(
"""
select distinct source from source_info
"""
)
for (source,) in cur.fetchall():
fs_path = os.path.join(self.env.root_path, source)
if not os.path.exists(fs_path):
to_clean.append(source)
if to_clean:
for i in range(0, len(to_clean), MAX_VARS):
chunk = to_clean[i : i + MAX_VARS]
cur.execute(
"""
delete from source_info
where source in (%s)
"""
% ", ".join(["?"] * len(chunk)),
chunk,
)
con.commit()
finally:
con.close()
for source in to_clean:
reporter.report_prune_source_info(source)
def remove_artifact(self, artifact_name):
"""Removes an artifact from the build state."""
con = self.connect_to_database()
try:
cur = con.cursor()
cur.execute(
"""
delete from artifacts where artifact = ?
""",
[artifact_name],
)
con.commit()
finally:
con.close()
def _any_sources_are_dirty(self, cur, sources):
"""Given a list of sources this checks if any of them are marked
as dirty.
"""
sources = [self.to_source_filename(x) for x in sources]
if not sources:
return False
cur.execute(
"""
select source from dirty_sources where source in (%s) limit 1
"""
% ", ".join(["?"] * len(sources)),
sources,
)
return cur.fetchone() is not None
@staticmethod
def _get_artifact_config_hash(cur, artifact_name):
"""Returns the artifact's config hash."""
cur.execute(
"""
select config_hash from artifact_config_hashes
where artifact = ?
""",
[artifact_name],
)
rv = cur.fetchone()
return rv[0] if rv else None
def check_artifact_is_current(self, artifact_name, sources, config_hash):
con = self.connect_to_database()
cur = con.cursor()
try:
# The artifact config changed
if config_hash != self._get_artifact_config_hash(cur, artifact_name):
return False
# If one of our source files is explicitly marked as dirty in the
# build state, we are not current.
if self._any_sources_are_dirty(cur, sources):
return False
# If we do have an already existing artifact, we need to check if
# any of the source files we depend on changed.
for _, info in self._iter_artifact_dependency_infos(
cur, artifact_name, sources
):
# if we get a missing source info it means that we never
# saw this before. This means we need to build it.
if info is None:
return False
if isinstance(info, VirtualSourceInfo):
new_vinfo = self.get_virtual_source_info(info.path)
if not info.unchanged(new_vinfo):
return False
# If the file info is different, then it clearly changed.
elif not info.unchanged(self.get_file_info(info.filename)):
return False
return True
finally:
con.close()
def iter_unreferenced_artifacts(self, all=False):
"""Finds all unreferenced artifacts in the build folder and yields
them.
"""
dst = os.path.join(self.builder.destination_path)
con = self.connect_to_database()
cur = con.cursor()
try:
for dirpath, dirnames, filenames in os.walk(dst):
dirnames[:] = [
x for x in dirnames if not self.env.is_ignored_artifact(x)
]
for filename in filenames:
if self.env.is_ignored_artifact(filename):
continue
full_path = os.path.join(dst, dirpath, filename)
artifact_name = self.artifact_name_from_destination_filename(
full_path
)
if all:
yield artifact_name
continue
cur.execute(
"""
select source from artifacts
where artifact = ?
and is_primary_source""",
[artifact_name],
)
sources = set(x[0] for x in cur.fetchall())
# It's a bad artifact if there are no primary sources
# or the primary sources do not exist.
if not sources or not any(
self.get_file_info(x).exists for x in sources
):
yield artifact_name
finally:
con.close()
def iter_artifacts(self):
"""Iterates over all artifact and their file infos.."""
con = self.connect_to_database()
try:
cur = con.cursor()
cur.execute(
"""
select distinct artifact from artifacts order by artifact
"""
)
rows = cur.fetchall()
con.close()
for (artifact_name,) in rows:
path = self.get_destination_filename(artifact_name)
info = FileInfo(self.builder.env, path)
if info.exists:
yield artifact_name, info
finally:
con.close()
def vacuum(self):
"""Vacuums the build db."""
con = self.connect_to_database()
try:
con.execute("vacuum")
finally:
con.close()
def _describe_fs_path_for_checksum(path):
"""Given a file system path this returns a basic description of what
this is. This is used for checksum hashing on directories.
"""
# This is not entirely correct as it does not detect changes for
# contents from alternatives. However for the moment it's good
# enough.
if os.path.isfile(path):
return b"\x01"
if os.path.isfile(os.path.join(path, "contents.lr")):
return b"\x02"
if os.path.isdir(path):
return b"\x03"
return b"\x00"
class FileInfo:
"""A file info object holds metainformation of a file so that changes
can be detected easily.
"""
def __init__(
self, env, filename, mtime=None, size=None, checksum=None, is_dir=None
):
self.env = env
self.filename = filename
if mtime is not None and size is not None and is_dir is not None:
self._stat = (mtime, size, is_dir)
else:
self._stat = None
self._checksum = checksum
def _get_stat(self):
rv = self._stat
if rv is not None:
return rv
try:
st = os.stat(self.filename)
mtime = int(st.st_mtime)
if stat.S_ISDIR(st.st_mode):
size = len(os.listdir(self.filename))
is_dir = True
else:
size = int(st.st_size)
is_dir = False
rv = mtime, size, is_dir
except OSError:
rv = 0, -1, False
self._stat = rv
return rv
@property
def mtime(self):
"""The timestamp of the last modification."""
return self._get_stat()[0]
@property
def size(self):
"""The size of the file in bytes. If the file is actually a
dictionary then the size is actually the number of files in it.
"""
return self._get_stat()[1]
@property
def is_dir(self):
"""Is this a directory?"""
return self._get_stat()[2]
@property
def exists(self):
return self.size >= 0
@property
def checksum(self):
"""The checksum of the file or directory."""
rv = self._checksum
if rv is not None:
return rv
try:
h = hashlib.sha1()
if os.path.isdir(self.filename):
h.update(b"DIR\x00")
for filename in sorted(os.listdir(self.filename)):
if self.env.is_uninteresting_source_name(filename):
continue
if isinstance(filename, str):
filename = filename.encode("utf-8")
h.update(filename)
h.update(
_describe_fs_path_for_checksum(
os.path.join(self.filename, filename.decode("utf-8"))
)
)
h.update(b"\x00")
else:
with open(self.filename, "rb") as f:
while 1:
chunk = f.read(16 * 1024)
if not chunk:
break
h.update(chunk)
checksum = h.hexdigest()
except (OSError, IOError):
checksum = "0" * 40
self._checksum = checksum
return checksum
@property
def filename_and_checksum(self):
"""Like 'filename:checksum'."""
return "%s:%s" % (self.filename, self.checksum)
def unchanged(self, other):
"""Given another file info checks if the are similar enough to
not consider it changed.
"""
if not isinstance(other, FileInfo):
raise TypeError("'other' must be a FileInfo, not %r" % other)
# If mtime and size match, we skip the checksum comparison which
# might require a file read which we do not want in those cases.
# (Except if it's a directory, then we won't do that)
if not self.is_dir and self.mtime == other.mtime and self.size == other.size:
return True
return self.checksum == other.checksum
class VirtualSourceInfo:
def __init__(self, path, mtime=None, checksum=None):
self.path = path
self.mtime = mtime
self.checksum = checksum
def unchanged(self, other):
if not isinstance(other, VirtualSourceInfo):
raise TypeError("'other' must be a VirtualSourceInfo, not %r" % other)
if self.path != other.path:
raise ValueError(
"trying to compare mismatched virtual paths: "
"%r.unchanged(%r)" % (self, other)
)
return (self.mtime, self.checksum) == (other.mtime, other.checksum)
def __repr__(self):
return "VirtualSourceInfo(%r, %r, %r)" % (self.path, self.mtime, self.checksum)
artifacts_row = namedtuple(
"artifacts_row",
[
"artifact",
"source",
"source_mtime",
"source_size",
"source_checksum",
"is_dir",
"is_primary_source",
],
)
class Artifact:
"""This class represents a build artifact."""
def __init__(
self,
build_state,
artifact_name,
dst_filename,
sources,
source_obj=None,
extra=None,
config_hash=None,
):
self.build_state = build_state
self.artifact_name = artifact_name
self.dst_filename = dst_filename
self.sources = sources
self.in_update_block = False
self.updated = False
self.source_obj = source_obj
self.extra = extra
self.config_hash = config_hash
self._new_artifact_file = None
self._pending_update_ops = []
def __repr__(self):
return "<%s %r>" % (
self.__class__.__name__,
self.dst_filename,
)
@property
def is_current(self):
"""Checks if the artifact is current."""
# If the artifact does not exist, we're not current.
if not os.path.isfile(self.dst_filename):
return False
return self.build_state.check_artifact_is_current(
self.artifact_name, self.sources, self.config_hash
)
def get_dependency_infos(self):
return self.build_state.get_artifact_dependency_infos(
self.artifact_name, self.sources
)
def ensure_dir(self):
"""Creates the directory if it does not exist yet."""
dst_dir = os.path.dirname(self.dst_filename)
try:
os.makedirs(dst_dir)
except OSError:
pass
def open(self, mode="rb", ensure_dir=None):
"""Opens the artifact for reading or writing. This is transaction
safe by writing into a temporary file and by moving it over the
actual source in commit.
"""
if ensure_dir is None:
ensure_dir = "r" not in mode
if ensure_dir:
self.ensure_dir()
if "r" in mode:
fn = self._new_artifact_file or self.dst_filename
return open(fn, mode)
if self._new_artifact_file is None:
fd, tmp_filename = tempfile.mkstemp(
dir=os.path.dirname(self.dst_filename), prefix=".__trans"
)
os.chmod(tmp_filename, 0o644)
self._new_artifact_file = tmp_filename
return os.fdopen(fd, mode)
return open(self._new_artifact_file, mode)
def replace_with_file(self, filename, ensure_dir=True, copy=False):
"""This is similar to open but it will move over a given named
file. The file will be deleted by a rollback or renamed by a
commit.
"""
if ensure_dir:
self.ensure_dir()
if copy:
with self.open("wb") as df:
with open(filename, "rb") as sf:
shutil.copyfileobj(sf, df)
else:
self._new_artifact_file = filename
def render_template_into(self, template_name, this, **extra):
"""Renders a template into the artifact. The default behavior is to
catch the error and render it into the template with a failure marker.
"""
rv = self.build_state.env.render_template(
template_name, self.build_state.pad, this=this, **extra
)
with self.open("wb") as f:
f.write(rv.encode("utf-8") + b"\n")
def _memorize_dependencies(
self, dependencies=None, virtual_dependencies=None, for_failure=False
):
"""This updates the dependencies recorded for the artifact based
on the direct sources plus the provided dependencies. This also
stores the config hash.
This normally defers the operation until commit but the `for_failure`
more will immediately commit into a new connection.
"""
def operation(con):
primary_sources = set(
self.build_state.to_source_filename(x) for x in self.sources
)
seen = set()
rows = []
for source in chain(self.sources, dependencies or ()):
source = self.build_state.to_source_filename(source)
if source in seen:
continue
info = self.build_state.get_file_info(source)
rows.append(
artifacts_row(
artifact=self.artifact_name,
source=source,
source_mtime=info.mtime,
source_size=info.size,
source_checksum=info.checksum,
is_dir=info.is_dir,
is_primary_source=source in primary_sources,
)
)
seen.add(source)
for v_source in virtual_dependencies or ():
checksum = v_source.get_checksum(self.build_state.path_cache)
mtime = v_source.get_mtime(self.build_state.path_cache)
rows.append(
artifacts_row(
artifact=self.artifact_name,
source=v_source.path,
source_mtime=mtime,
source_size=None,
source_checksum=checksum,
is_dir=False,
is_primary_source=False,
)
)
reporter.report_dependencies(rows)
cur = con.cursor()
if not for_failure:
cur.execute(
"delete from artifacts where artifact = ?", [self.artifact_name]
)
if rows:
cur.executemany(
"""
insert or replace into artifacts (
artifact, source, source_mtime, source_size,
source_checksum, is_dir, is_primary_source)
values (?, ?, ?, ?, ?, ?, ?)
""",
rows,
)
if self.config_hash is None:
cur.execute(
"""
delete from artifact_config_hashes
where artifact = ?
""",
[self.artifact_name],
)
else:
cur.execute(
"""
insert or replace into artifact_config_hashes
(artifact, config_hash) values (?, ?)
""",
[self.artifact_name, self.config_hash],
)
cur.close()
if for_failure:
con = self.build_state.connect_to_database()
try:
operation(con)
except: # noqa
con.rollback()
con.close()
raise
con.commit()
con.close()
else:
self._auto_deferred_update_operation(operation)
def clear_dirty_flag(self):
"""Clears the dirty flag for all sources."""
def operation(con):
sources = [self.build_state.to_source_filename(x) for x in self.sources]
cur = con.cursor()
cur.execute(
"""
delete from dirty_sources where source in (%s)
"""
% ", ".join(["?"] * len(sources)),
list(sources),
)
cur.close()
reporter.report_dirty_flag(False)
self._auto_deferred_update_operation(operation)
def set_dirty_flag(self):
"""Given a list of artifacts this will mark all of their sources
as dirty so that they will be rebuilt next time.
"""
def operation(con):
sources = set()
for source in self.sources:
sources.add(self.build_state.to_source_filename(source))
if not sources:
return
cur = con.cursor()
cur.executemany(
"""
insert or replace into dirty_sources (source) values (?)
""",
[(x,) for x in sources],
)
cur.close()
reporter.report_dirty_flag(True)
self._auto_deferred_update_operation(operation)
def _auto_deferred_update_operation(self, f):
"""Helper that defers an update operation when inside an update
block to a later point. Otherwise it's auto committed.
"""
if self.in_update_block:
self._pending_update_ops.append(f)
return
con = self.build_state.connect_to_database()
try:
f(con)
except: # noqa
con.rollback()
raise
con.commit()
@contextmanager
def update(self):
"""Opens the artifact for modifications. At the start the dirty
flag is cleared out and if the commit goes through without errors it
stays cleared. The setting of the dirty flag has to be done by the
caller however based on the `exc_info` on the context.
"""
ctx = self.begin_update()
try:
yield ctx
except: # pylint: disable=bare-except # noqa
exc_info = sys.exc_info()
self.finish_update(ctx, exc_info)
else:
self.finish_update(ctx)
def begin_update(self):
"""Begins an update block."""
if self.in_update_block:
raise RuntimeError("Artifact is already open for updates.")
self.updated = False
ctx = Context(self)
ctx.push()
self.in_update_block = True
self.clear_dirty_flag()
return ctx
def _commit(self):
con = None
try:
for op in self._pending_update_ops:
if con is None:
con = self.build_state.connect_to_database()
op(con)
if self._new_artifact_file is not None:
os.replace(self._new_artifact_file, self.dst_filename)
self._new_artifact_file = None
if con is not None:
con.commit()
con.close()
con = None
self.build_state.updated_artifacts.append(self)
self.build_state.builder.failure_controller.clear_failure(
self.artifact_name
)
finally:
if con is not None:
con.rollback()
con.close()
def _rollback(self):
if self._new_artifact_file is not None:
try:
os.remove(self._new_artifact_file)
except OSError:
pass
self._new_artifact_file = None
self._pending_update_ops = []
def finish_update(self, ctx, exc_info=None):
"""Finalizes an update block."""
if not self.in_update_block:
raise RuntimeError("Artifact is not open for updates.")
ctx.pop()
self.in_update_block = False
self.updated = True
# If there was no error, we memoize the dependencies like normal
# and then commit our transaction.
if exc_info is None:
self._memorize_dependencies(
ctx.referenced_dependencies,
ctx.referenced_virtual_dependencies.values(),
)
self._commit()
return
# If an error happened we roll back all changes and record the
# stacktrace in two locations: we record it on the context so
# that a called can respond to our failure, and we also persist
# it so that the dev server can render it out later.
self._rollback()
# This is a special form of dependency memorization where we do
# not prune old dependencies and we just append new ones and we
# use a new database connection that immediately commits.
self._memorize_dependencies(
ctx.referenced_dependencies,
ctx.referenced_virtual_dependencies.values(),
for_failure=True,
)
ctx.exc_info = exc_info
self.build_state.notify_failure(self, exc_info)
class PathCache:
def __init__(self, env):
self.file_info_cache = {}
self.source_filename_cache = {}
self.env = env
def to_source_filename(self, filename):
"""Given a path somewhere below the environment this will return the
short source filename that is used internally. Unlike the given
path, this identifier is also platform independent.
"""
key = filename
rv = self.source_filename_cache.get(key)
if rv is not None:
return rv
folder = os.path.abspath(self.env.root_path)
if isinstance(folder, str) and not isinstance(filename, str):
filename = filename.decode(fs_enc)
filename = os.path.normpath(os.path.join(folder, filename))
if filename.startswith(folder):
filename = filename[len(folder) :].lstrip(os.path.sep)
if os.path.altsep:
filename = filename.lstrip(os.path.altsep)
else:
raise ValueError(
"The given value (%r) is not below the "
"source folder (%r)" % (filename, self.env.root_path)
)
rv = filename.replace(os.path.sep, "/")
self.source_filename_cache[key] = rv
return rv
def get_file_info(self, filename):
"""Returns the file info for a given file. This will be cached
on the generator for the lifetime of it. This means that further
accesses to this file info will not cause more IO but it might not
be safe to use the generator after modifications to the original
files have been performed on the outside.
Generally this function can be used to acquire the file info for
any file on the file system but it should onl be used for source
files or carefully for other things.
The filename given can be a source filename.
"""
fn = os.path.join(self.env.root_path, filename)
rv = self.file_info_cache.get(fn)
if rv is None:
self.file_info_cache[fn] = rv = FileInfo(self.env, fn)
return rv
class Builder:
def __init__(self, pad, destination_path, buildstate_path=None, extra_flags=None):
self.extra_flags = process_extra_flags(extra_flags)
self.pad = pad
self.destination_path = os.path.abspath(
os.path.join(pad.db.env.root_path, destination_path)
)
if buildstate_path:
self.meta_path = buildstate_path
else:
self.meta_path = os.path.join(self.destination_path, ".lektor")
self.failure_controller = FailureController(pad, self.destination_path)
try:
os.makedirs(self.meta_path)
if os.listdir(self.destination_path) != [".lektor"]:
if not click.confirm(
click.style(
"The build dir %s hasn't been used before, and other "
"files or folders already exist there. If you prune "
"(which normally follows the build step), "
"they will be deleted. Proceed with building?"
% self.destination_path,
fg="yellow",
)
):
os.rmdir(self.meta_path)
raise click.Abort()
except OSError:
pass
con = self.connect_to_database()
try:
create_tables(con)
finally:
con.close()
@property
def env(self):
"""The environment backing this generator."""
return self.pad.db.env
@property
def buildstate_database_filename(self):
"""The filename for the build state database."""
return os.path.join(self.meta_path, "buildstate")
def connect_to_database(self):
con = sqlite3.connect(
self.buildstate_database_filename,
isolation_level=None,
timeout=10,
check_same_thread=False,
)
cur = con.cursor()
cur.execute("pragma journal_mode=WAL")
cur.execute("pragma synchronous=NORMAL")
con.commit()
cur.close()
return con
def touch_site_config(self):
"""Touches the site config which typically will trigger a rebuild."""
try:
os.utime(os.path.join(self.env.root_path, "site.ini"), None)
except OSError:
pass
def find_files(self, query, alt=PRIMARY_ALT, lang=None, limit=50, types=None):
"""Returns a list of files that match the query. This requires that
the source info is up to date and is primarily used by the admin to
show files that exist.
"""
return find_files(self, query, alt, lang, limit, types)
def new_build_state(self, path_cache=None):
"""Creates a new build state."""
if path_cache is None:
path_cache = PathCache(self.env)
return BuildState(self, path_cache)
def get_build_program(self, source, build_state):
"""Finds the right build function for the given source file."""
for cls, builder in chain(
reversed(self.env.build_programs), reversed(builtin_build_programs)
):
if isinstance(source, cls):
return builder(source, build_state)
# TODO: re-enable pylint when https://github.com/PyCQA/pylint/issues/1782 is fixed.
raise RuntimeError(
"I do not know how to build %r" % source
) # pylint: disable=inconsistent-return-statements
def build_artifact(self, artifact, build_func):
"""Various parts of the system once they have an artifact and a
function to build it, will invoke this function. This ultimately
is what builds.
The return value is the ctx that was used to build this thing
if it was built, or `None` otherwise.
"""
is_current = artifact.is_current
with reporter.build_artifact(artifact, build_func, is_current):
if not is_current:
with artifact.update() as ctx:
# Upon builing anything we record a dependency to the
# project file. This is not ideal but for the moment
# it will ensure that if the file changes we will
# rebuild.
project_file = self.env.project.project_file
if project_file:
ctx.record_dependency(project_file)
build_func(artifact)
return ctx
return None
@staticmethod
def update_source_info(prog, build_state):
"""Updates a single source info based on a program. This is done
automatically as part of a build.
"""
info = prog.describe_source_record()
if info is not None:
build_state.write_source_info(info)
def prune(self, all=False):
"""This cleans up data left in the build folder that does not
correspond to known artifacts.
"""
path_cache = PathCache(self.env)
with reporter.build(all and "clean" or "prune", self):
self.env.plugin_controller.emit("before-prune", builder=self, all=all)
with self.new_build_state(path_cache=path_cache) as build_state:
for aft in build_state.iter_unreferenced_artifacts(all=all):
reporter.report_pruned_artifact(aft)
filename = build_state.get_destination_filename(aft)
prune_file_and_folder(filename, self.destination_path)
build_state.remove_artifact(aft)
build_state.prune_source_infos()
if all:
build_state.vacuum()
self.env.plugin_controller.emit("after-prune", builder=self, all=all)
def build(self, source, path_cache=None):
"""Given a source object, builds it."""
with self.new_build_state(path_cache=path_cache) as build_state:
with reporter.process_source(source):
prog = self.get_build_program(source, build_state)
self.env.plugin_controller.emit(
"before-build",
builder=self,
build_state=build_state,
source=source,
prog=prog,
)
prog.build()
if build_state.updated_artifacts:
self.update_source_info(prog, build_state)
self.env.plugin_controller.emit(
"after-build",
builder=self,
build_state=build_state,
source=source,
prog=prog,
)
return prog, build_state
def get_initial_build_queue(self):
"""Returns the initial build queue as deque."""
return deque(self.pad.get_all_roots())
def extend_build_queue(self, queue, prog):
queue.extend(prog.iter_child_sources())
for func in self.env.custom_generators:
queue.extend(func(prog.source) or ())
def build_all(self):
"""Builds the entire tree. Returns the number of failures."""
failures = 0
path_cache = PathCache(self.env)
# We keep a dummy connection here that does not do anything which
# helps us with the WAL handling. See #144
con = self.connect_to_database()
try:
with reporter.build("build", self):
self.env.plugin_controller.emit("before-build-all", builder=self)
to_build = self.get_initial_build_queue()
while to_build:
source = to_build.popleft()
prog, build_state = self.build(source, path_cache=path_cache)
self.extend_build_queue(to_build, prog)
failures += len(build_state.failed_artifacts)
self.env.plugin_controller.emit("after-build-all", builder=self)
if failures:
reporter.report_build_all_failure(failures)
return failures
finally:
con.close()
def update_all_source_infos(self):
"""Fast way to update all source infos without having to build
everything.
"""
# We keep a dummy connection here that does not do anything which
# helps us with the WAL handling. See #144
con = self.connect_to_database()
try:
with reporter.build("source info update", self):
with self.new_build_state() as build_state:
to_build = self.get_initial_build_queue()
while to_build:
source = to_build.popleft()
with reporter.process_source(source):
prog = self.get_build_program(source, build_state)
self.update_source_info(prog, build_state)
self.extend_build_queue(to_build, prog)
build_state.prune_source_infos()
finally:
con.close()
| 34.64534
| 91
| 0.552427
|
78736908ac90934f91fdd1b9cbd63b1f98ba3e8b
| 1,628
|
py
|
Python
|
module1-web-application-development-with-flask/Unit 3 Sprint 3 Module 1/myapp.py
|
SarmenSinanian/DS-Unit-3-Sprint-3-Productization-and-Cloud
|
f67562632eef1377921eee53e3d0d62bbafc5d5e
|
[
"MIT"
] | null | null | null |
module1-web-application-development-with-flask/Unit 3 Sprint 3 Module 1/myapp.py
|
SarmenSinanian/DS-Unit-3-Sprint-3-Productization-and-Cloud
|
f67562632eef1377921eee53e3d0d62bbafc5d5e
|
[
"MIT"
] | null | null | null |
module1-web-application-development-with-flask/Unit 3 Sprint 3 Module 1/myapp.py
|
SarmenSinanian/DS-Unit-3-Sprint-3-Productization-and-Cloud
|
f67562632eef1377921eee53e3d0d62bbafc5d5e
|
[
"MIT"
] | null | null | null |
# # import my flask package
# from flask import Flask, render_template
#
# # create Flask web server
# app = Flask(__name__)
#
# # route determines location
# @app.route("/")
#
# # define a little function to tell
# # app what to do at that route (app.rout("/"))
# # http://127.0.0.1:5000
# def home():
# return render_template('home.html')
#
# # Create another route
# @app.route("/about")
#
# # Define another function for this new route
# # http://127.0.0.1:5000/about
# def pred():
# return render_template('about.html')
#
# # Clean things up
# if __name__ == "__main__":
# app.run(debug = True)
#
# #conda install Flask==1.0.3 is not buggy
#
# # open CMD/anaconda prompt, cd to directory of
# # myapp.py, run "python myapp.py", go to
# # ip.address provided after "running on https:"
#
# #to run this go to terminal and type python myapp.py
# #alt approach to running it, also in terminal:
# # FLASK_APP= myapp.py flask run
#import my flask package
from flask import Flask, render_template
#create Flask web server
app = Flask(__name__)
#route determines location
@app.route("/")
#define a little function to
#tell it what to do at that route
def home():
return render_template('home.html')
#Create another route
@app.route("/about")
#define another function for this new route
def pred():
return render_template('about.html')
#clean things up
if __name__ == "__main__":
app.run(debug=True)
#to run this go to terminal and type python myapp.py
#alt approach to running it, also in terminal:
# FLASK_APP= myapp.py flask run
| 25.046154
| 55
| 0.665848
|
abfeb155e60cd9806ebca20210a264a430c4c30b
| 3,105
|
py
|
Python
|
playground/optimization/ottKama155it/custom_indicators/ott.py
|
ysdede/jesse_strategies
|
ade9f4ba42cec11207c766d267b9d8feb8bce648
|
[
"CC0-1.0"
] | 38
|
2021-09-18T15:33:28.000Z
|
2022-02-21T17:29:08.000Z
|
playground/optimization/ottKama155it/custom_indicators/ott.py
|
ysdede/jesse_strategies
|
ade9f4ba42cec11207c766d267b9d8feb8bce648
|
[
"CC0-1.0"
] | 4
|
2022-01-02T14:46:12.000Z
|
2022-02-16T18:39:41.000Z
|
playground/optimization/ottKama155it/custom_indicators/ott.py
|
ysdede/jesse_strategies
|
ade9f4ba42cec11207c766d267b9d8feb8bce648
|
[
"CC0-1.0"
] | 11
|
2021-10-19T06:21:43.000Z
|
2022-02-21T17:29:10.000Z
|
from collections import namedtuple
import numpy as np
import numba
import talib
from jesse.helpers import get_candle_source, slice_candles
import custom_indicators as cta
OTT = namedtuple('OTT', ['ott', 'mavg', 'long_stop', 'short_stop'])
def ott(candles: np.ndarray, length: int = 2, percent: float = 1.4, ma_type="var", source_type="close",
sequential=False) -> OTT:
"""
:param candles: np.ndarray
:param length: int - default: 2
:param percent: int - default: 1.4
:param ma_type: str - default: var
:param source_type: str - default: close
:param sequential: bool - default: False
:return: Union[float, np.ndarray]
"""
if length < 1 or percent <= 0:
raise ValueError('Bad parameters.')
# Accept normal array too.
if len(candles.shape) == 1:
source = candles
else:
candles = slice_candles(candles, sequential)
source = get_candle_source(candles, source_type=source_type)
if ma_type == 'kama':
MAvg = talib.KAMA(source, length)
elif ma_type == 'wma':
MAvg = talib.WMA(source, length)
else:
MAvg = cta.var(source, length, source_type, sequential=True)
ott_series, longStop, shortStop = ott_fast(MAvg, percent, length)
if sequential:
return OTT(ott_series, MAvg, longStop, shortStop)
else:
return OTT(ott_series[-1], MAvg[-1], longStop[-1], shortStop[-1])
@numba.njit
def ott_fast(MAvg, percent, length):
fark = np.multiply(np.multiply(MAvg, percent), 0.01)
# >>>>>>>
longStop = np.subtract(MAvg, fark)
longStopPrev = np.copy(longStop)
for i in range(length, longStop.size):
if MAvg[i] > longStop[i - 1]:
longStop[i] = max(longStop[i], longStop[i - 1])
longStopPrev[i] = longStop[i - 1]
for i in range(length, longStop.size):
if MAvg[i] > longStopPrev[i]:
longStop[i] = max(longStop[i], longStopPrev[i])
longStopPrev[i] = longStop[i - 1]
# <<<<<>>>>>>>
shortStop = np.add(MAvg, fark)
shortStopPrev = np.copy(shortStop)
for i in range(length, shortStop.size):
if MAvg[i] < shortStop[i - 1]:
shortStop[i] = min(shortStop[i], shortStop[i - 1])
shortStopPrev[i] = shortStop[i - 1]
for i in range(length, shortStop.size):
if MAvg[i] < shortStopPrev[i]:
shortStop[i] = min(shortStop[i], shortStopPrev[i])
shortStopPrev[i] = shortStop[i - 1]
# <<<<<>>>>>>>
dir = np.full_like(longStop, 1)
temp_dir = dir[length - 1]
for i in range(length, dir.size):
if temp_dir < 0 and MAvg[i] > shortStopPrev[i]:
temp_dir = dir[i] = 1
elif temp_dir < 0 and MAvg[i] < shortStopPrev[i]:
temp_dir = dir[i] = -1
elif temp_dir > 0 and MAvg[i] < longStopPrev[i]:
temp_dir = dir[i] = -1
# <<<<<>>>>>>>
MT = np.where(dir > 0, longStop, shortStop)
OTT = np.where(MAvg > MT, MT * (200 + percent) / 200, MT * (200 - percent) / 200)
return np.concatenate((np.full(2, 0), OTT[:-2])), longStop, shortStop
| 33.031915
| 103
| 0.599678
|
5cf04ffa93f43d7508e83b8f363f59b518da2e8b
| 1,193
|
py
|
Python
|
drawbot/animateMutatorSans.py
|
justvanrossum/mutatorSans
|
d8f0fb27ec3815486887328dd843689d2a10db86
|
[
"MIT"
] | null | null | null |
drawbot/animateMutatorSans.py
|
justvanrossum/mutatorSans
|
d8f0fb27ec3815486887328dd843689d2a10db86
|
[
"MIT"
] | null | null | null |
drawbot/animateMutatorSans.py
|
justvanrossum/mutatorSans
|
d8f0fb27ec3815486887328dd843689d2a10db86
|
[
"MIT"
] | null | null | null |
import math
d = listFontVariations("MutatorMathTest")
print(list(d.keys()))
for fontName in installedFonts():
variations = listFontVariations(fontName)
if variations:
print(fontName)
for axis_name, dimensions in variations.items():
print (axis_name, dimensions)
print ()
weightMin = listFontVariations('MutatorMathTest')['wght']['minValue']
weightMax = listFontVariations('MutatorMathTest')['wght']['maxValue']
widthMin = listFontVariations('MutatorMathTest')['wdth']['minValue']
widthMax = listFontVariations('MutatorMathTest')['wdth']['maxValue']
steps = 50
txt = '→FRISCH'
def ip(a, b, f):
return a + f*(b-a)
for i in range(steps):
angle = 2 * pi * (i / steps)
a1 = .5+cos(angle)*.5
a2 = .5+sin(angle)*.5
newPage(1200, 250)
font("MutatorMathTest")
fontSize(200)
weightValue = ip(weightMin, weightMax, a1)
widthValue = ip(widthMin, widthMax, a2)
fontVariations(wght=weightValue, wdth=widthValue)
text(txt, (20, 50))
font("Menlo-Regular")
fontSize(10)
text('MutatorSans weight: %3.3f, width: %3.3f' % (weightValue, widthValue), (10, 10))
saveImage('mutatorSans.gif')
| 25.934783
| 89
| 0.656329
|
760a7bd040511bef9fd32f55a315eb790b647c0a
| 61,723
|
py
|
Python
|
python/ccxt/async_support/huobipro.py
|
mark-luke/Pay-Encrypt
|
1579917a7ad8f28038625ee27beed98a42c9f28f
|
[
"MIT"
] | null | null | null |
python/ccxt/async_support/huobipro.py
|
mark-luke/Pay-Encrypt
|
1579917a7ad8f28038625ee27beed98a42c9f28f
|
[
"MIT"
] | null | null | null |
python/ccxt/async_support/huobipro.py
|
mark-luke/Pay-Encrypt
|
1579917a7ad8f28038625ee27beed98a42c9f28f
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import hashlib
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import NetworkError
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import OnMaintenance
from ccxt.base.errors import RequestTimeout
from ccxt.base.decimal_to_precision import TRUNCATE
class huobipro(Exchange):
def describe(self):
return self.deep_extend(super(huobipro, self).describe(), {
'id': 'huobipro',
'name': 'Huobi Pro',
'countries': ['CN'],
'rateLimit': 2000,
'userAgent': self.userAgents['chrome39'],
'version': 'v1',
'accounts': None,
'accountsById': None,
'hostname': 'api.huobi.pro', # api.testnet.huobi.pro
'pro': True,
'has': {
'cancelOrder': True,
'CORS': False,
'createOrder': True,
'fetchBalance': True,
'fetchClosedOrders': True,
'fetchCurrencies': True,
'fetchDepositAddress': True,
'fetchDeposits': True,
'fetchMarkets': True,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrders': True,
'fetchTicker': True,
'fetchTickers': True,
'fetchTrades': True,
'fetchTradingLimits': True,
'fetchWithdrawals': True,
'withdraw': True,
},
'timeframes': {
'1m': '1min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '60min',
'4h': '4hour',
'1d': '1day',
'1w': '1week',
'1M': '1mon',
'1y': '1year',
},
'urls': {
'test': {
'market': 'https://api.testnet.huobi.pro',
'public': 'https://api.testnet.huobi.pro',
'private': 'https://api.testnet.huobi.pro',
},
'logo': 'https://user-images.githubusercontent.com/1294454/76137448-22748a80-604e-11ea-8069-6e389271911d.jpg',
'api': {
'market': 'https://{hostname}',
'public': 'https://{hostname}',
'private': 'https://{hostname}',
'v2Public': 'https://{hostname}',
'v2Private': 'https://{hostname}',
},
'www': 'https://www.huobi.com',
'referral': 'https://www.huobi.com/en-us/topic/invited/?invite_code=rwrd3',
'doc': 'https://huobiapi.github.io/docs/spot/v1/cn/',
'fees': 'https://www.huobi.com/about/fee/',
},
'api': {
'v2Public': {
'get': [
'reference/currencies',
],
},
'v2Private': {
'get': [
'account/ledger',
'account/withdraw/quota',
'account/withdraw/address', # 提币地址查询(限母用户可用)
'account/deposit/address',
'reference/transact-fee-rate',
'account/asset-valuation', # 获取账户资产估值
'point/account', # 点卡余额查询
'sub-user/user-list', # 获取子用户列表
'sub-user/user-state', # 获取特定子用户的用户状态
'sub-user/account-list', # 获取特定子用户的账户列表
'sub-user/deposit-address', # 子用户充币地址查询
'sub-user/query-deposit', # 子用户充币记录查询
'user/api-key', # 母子用户API key信息查询
],
'post': [
'point/transfer', # 点卡划转
'sub-user/management', # 冻结/解冻子用户
'sub-user/creation', # 子用户创建
'sub-user/tradable-market', # 设置子用户交易权限
'sub-user/transferability', # 设置子用户资产转出权限
'sub-user/api-key-generation', # 子用户API key创建
'sub-user/api-key-modification', # 修改子用户API key
'sub-user/api-key-deletion', # 删除子用户API key
],
},
'market': {
'get': [
'history/kline', # 获取K线数据
'detail/merged', # 获取聚合行情(Ticker)
'depth', # 获取 Market Depth 数据
'trade', # 获取 Trade Detail 数据
'history/trade', # 批量获取最近的交易记录
'detail', # 获取 Market Detail 24小时成交量数据
'tickers',
],
},
'public': {
'get': [
'common/symbols', # 查询系统支持的所有交易对
'common/currencys', # 查询系统支持的所有币种
'common/timestamp', # 查询系统当前时间
'common/exchange', # order limits
'settings/currencys', # ?language=en-US
],
},
'private': {
'get': [
'account/accounts', # 查询当前用户的所有账户(即account-id)
'account/accounts/{id}/balance', # 查询指定账户的余额
'account/accounts/{sub-uid}',
'account/history',
'cross-margin/loan-info',
'margin/loan-info', # 查询借币币息率及额度
'fee/fee-rate/get',
'order/openOrders',
'order/orders',
'order/orders/{id}', # 查询某个订单详情
'order/orders/{id}/matchresults', # 查询某个订单的成交明细
'order/orders/getClientOrder',
'order/history', # 查询当前委托、历史委托
'order/matchresults', # 查询当前成交、历史成交
'dw/withdraw-virtual/addresses', # 查询虚拟币提现地址(Deprecated)
'query/deposit-withdraw',
'margin/loan-info',
'margin/loan-orders', # 借贷订单
'margin/accounts/balance', # 借贷账户详情
'cross-margin/loan-orders', # 查询借币订单
'cross-margin/accounts/balance', # 借币账户详情
'points/actions',
'points/orders',
'subuser/aggregate-balance',
'stable-coin/exchange_rate',
'stable-coin/quote',
],
'post': [
'account/transfer', # 资产划转(该节点为母用户和子用户进行资产划转的通用接口。)
'futures/transfer',
'order/batch-orders',
'order/orders/place', # 创建并执行一个新订单(一步下单, 推荐使用)
'order/orders/submitCancelClientOrder',
'order/orders/batchCancelOpenOrders',
'order/orders', # 创建一个新的订单请求 (仅创建订单,不执行下单)
'order/orders/{id}/place', # 执行一个订单 (仅执行已创建的订单)
'order/orders/{id}/submitcancel', # 申请撤销一个订单请求
'order/orders/batchcancel', # 批量撤销订单
'dw/balance/transfer', # 资产划转
'dw/withdraw/api/create', # 申请提现虚拟币
'dw/withdraw-virtual/create', # 申请提现虚拟币
'dw/withdraw-virtual/{id}/place', # 确认申请虚拟币提现(Deprecated)
'dw/withdraw-virtual/{id}/cancel', # 申请取消提现虚拟币
'dw/transfer-in/margin', # 现货账户划入至借贷账户
'dw/transfer-out/margin', # 借贷账户划出至现货账户
'margin/orders', # 申请借贷
'margin/orders/{id}/repay', # 归还借贷
'cross-margin/transfer-in', # 资产划转
'cross-margin/transfer-out', # 资产划转
'cross-margin/orders', # 申请借币
'cross-margin/orders/{id}/repay', # 归还借币
'stable-coin/exchange',
'subuser/transfer',
],
},
},
'fees': {
'trading': {
'tierBased': False,
'percentage': True,
'maker': 0.002,
'taker': 0.002,
},
},
'exceptions': {
'exact': {
# err-code
'bad-request': BadRequest,
'api-not-support-temp-addr': PermissionDenied, # {"status":"error","err-code":"api-not-support-temp-addr","err-msg":"API withdrawal does not support temporary addresses","data":null}
'timeout': RequestTimeout, # {"ts":1571653730865,"status":"error","err-code":"timeout","err-msg":"Request Timeout"}
'gateway-internal-error': ExchangeNotAvailable, # {"status":"error","err-code":"gateway-internal-error","err-msg":"Failed to load data. Try again later.","data":null}
'account-frozen-balance-insufficient-error': InsufficientFunds, # {"status":"error","err-code":"account-frozen-balance-insufficient-error","err-msg":"trade account balance is not enough, left: `0.0027`","data":null}
'invalid-amount': InvalidOrder, # eg "Paramemter `amount` is invalid."
'order-limitorder-amount-min-error': InvalidOrder, # limit order amount error, min: `0.001`
'order-limitorder-amount-max-error': InvalidOrder, # market order amount error, max: `1000000`
'order-marketorder-amount-min-error': InvalidOrder, # market order amount error, min: `0.01`
'order-limitorder-price-min-error': InvalidOrder, # limit order price error
'order-limitorder-price-max-error': InvalidOrder, # limit order price error
'order-orderstate-error': OrderNotFound, # canceling an already canceled order
'order-queryorder-invalid': OrderNotFound, # querying a non-existent order
'order-update-error': ExchangeNotAvailable, # undocumented error
'api-signature-check-failed': AuthenticationError,
'api-signature-not-valid': AuthenticationError, # {"status":"error","err-code":"api-signature-not-valid","err-msg":"Signature not valid: Incorrect Access key [Access key错误]","data":null}
'base-record-invalid': OrderNotFound, # https://github.com/ccxt/ccxt/issues/5750
# err-msg
'invalid symbol': BadSymbol, # {"ts":1568813334794,"status":"error","err-code":"invalid-parameter","err-msg":"invalid symbol"}
'invalid-parameter': BadRequest, # {"ts":1576210479343,"status":"error","err-code":"invalid-parameter","err-msg":"symbol trade not open now"}
'base-symbol-trade-disabled': BadSymbol, # {"status":"error","err-code":"base-symbol-trade-disabled","err-msg":"Trading is disabled for self symbol","data":null}
'system-maintenance': OnMaintenance, # {"status": "error", "err-code": "system-maintenance", "err-msg": "System is in maintenance!", "data": null}
},
},
'options': {
# https://github.com/ccxt/ccxt/issues/5376
'fetchOrdersByStatesMethod': 'private_get_order_orders', # 'private_get_order_history' # https://github.com/ccxt/ccxt/pull/5392
'fetchOpenOrdersMethod': 'fetch_open_orders_v1', # 'fetch_open_orders_v2' # https://github.com/ccxt/ccxt/issues/5388
'createMarketBuyOrderRequiresPrice': True,
'fetchMarketsMethod': 'publicGetCommonSymbols',
'fetchBalanceMethod': 'privateGetAccountAccountsIdBalance',
'createOrderMethod': 'privatePostOrderOrdersPlace',
'language': 'en-US',
},
'commonCurrencies': {
# https://github.com/ccxt/ccxt/issues/6081
# https://github.com/ccxt/ccxt/issues/3365
# https://github.com/ccxt/ccxt/issues/2873
'GET': 'Themis', # conflict with GET(Guaranteed Entrance Token, GET Protocol)
'HOT': 'Hydro Protocol', # conflict with HOT(Holo) https://github.com/ccxt/ccxt/issues/4929
# https://github.com/ccxt/ccxt/issues/7399
# https://coinmarketcap.com/currencies/pnetwork/
# https://coinmarketcap.com/currencies/penta/markets/
# https://en.cryptonomist.ch/blog/eidoo/the-edo-to-pnt-upgrade-what-you-need-to-know-updated/
'PNT': 'Penta',
},
})
async def fetch_trading_limits(self, symbols=None, params={}):
# self method should not be called directly, use loadTradingLimits() instead
# by default it will try load withdrawal fees of all currencies(with separate requests)
# however if you define symbols = ['ETH/BTC', 'LTC/BTC'] in args it will only load those
await self.load_markets()
if symbols is None:
symbols = self.symbols
result = {}
for i in range(0, len(symbols)):
symbol = symbols[i]
result[symbol] = await self.fetch_trading_limits_by_id(self.market_id(symbol), params)
return result
async def fetch_trading_limits_by_id(self, id, params={}):
request = {
'symbol': id,
}
response = await self.publicGetCommonExchange(self.extend(request, params))
#
# {status: "ok",
# data: { symbol: "aidocbtc",
# 'buy-limit-must-less-than': 1.1,
# 'sell-limit-must-greater-than': 0.9,
# 'limit-order-must-greater-than': 1,
# 'limit-order-must-less-than': 5000000,
# 'market-buy-order-must-greater-than': 0.0001,
# 'market-buy-order-must-less-than': 100,
# 'market-sell-order-must-greater-than': 1,
# 'market-sell-order-must-less-than': 500000,
# 'circuit-break-when-greater-than': 10000,
# 'circuit-break-when-less-than': 10,
# 'market-sell-order-rate-must-less-than': 0.1,
# 'market-buy-order-rate-must-less-than': 0.1 }}
#
return self.parse_trading_limits(self.safe_value(response, 'data', {}))
def parse_trading_limits(self, limits, symbol=None, params={}):
#
# { symbol: "aidocbtc",
# 'buy-limit-must-less-than': 1.1,
# 'sell-limit-must-greater-than': 0.9,
# 'limit-order-must-greater-than': 1,
# 'limit-order-must-less-than': 5000000,
# 'market-buy-order-must-greater-than': 0.0001,
# 'market-buy-order-must-less-than': 100,
# 'market-sell-order-must-greater-than': 1,
# 'market-sell-order-must-less-than': 500000,
# 'circuit-break-when-greater-than': 10000,
# 'circuit-break-when-less-than': 10,
# 'market-sell-order-rate-must-less-than': 0.1,
# 'market-buy-order-rate-must-less-than': 0.1 }
#
return {
'info': limits,
'limits': {
'amount': {
'min': self.safe_float(limits, 'limit-order-must-greater-than'),
'max': self.safe_float(limits, 'limit-order-must-less-than'),
},
},
}
def cost_to_precision(self, symbol, cost):
return self.decimal_to_precision(cost, TRUNCATE, self.markets[symbol]['precision']['cost'], self.precisionMode)
async def fetch_markets(self, params={}):
method = self.options['fetchMarketsMethod']
response = await getattr(self, method)(params)
markets = self.safe_value(response, 'data')
numMarkets = len(markets)
if numMarkets < 1:
raise NetworkError(self.id + ' publicGetCommonSymbols returned empty response: ' + self.json(markets))
result = []
for i in range(0, len(markets)):
market = markets[i]
baseId = self.safe_string(market, 'base-currency')
quoteId = self.safe_string(market, 'quote-currency')
id = baseId + quoteId
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
symbol = base + '/' + quote
precision = {
'amount': self.safe_integer(market, 'amount-precision'),
'price': self.safe_integer(market, 'price-precision'),
'cost': self.safe_integer(market, 'value-precision'),
}
maker = 0 if (base == 'OMG') else 0.2 / 100
taker = 0 if (base == 'OMG') else 0.2 / 100
minAmount = self.safe_float(market, 'min-order-amt', math.pow(10, -precision['amount']))
maxAmount = self.safe_float(market, 'max-order-amt')
minCost = self.safe_float(market, 'min-order-value', 0)
state = self.safe_string(market, 'state')
active = (state == 'online')
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': active,
'precision': precision,
'taker': taker,
'maker': maker,
'limits': {
'amount': {
'min': minAmount,
'max': maxAmount,
},
'price': {
'min': math.pow(10, -precision['price']),
'max': None,
},
'cost': {
'min': minCost,
'max': None,
},
},
'info': market,
})
return result
def parse_ticker(self, ticker, market=None):
#
# fetchTicker
#
# {
# "amount": 26228.672978342216,
# "open": 9078.95,
# "close": 9146.86,
# "high": 9155.41,
# "id": 209988544334,
# "count": 265846,
# "low": 8988.0,
# "version": 209988544334,
# "ask": [9146.87, 0.156134],
# "vol": 2.3822168242201668E8,
# "bid": [9146.86, 0.080758],
# }
#
# fetchTickers
# {
# symbol: "bhdht",
# open: 2.3938,
# high: 2.4151,
# low: 2.3323,
# close: 2.3909,
# amount: 628.992,
# vol: 1493.71841095,
# count: 2088,
# bid: 2.3643,
# bidSize: 0.7136,
# ask: 2.4061,
# askSize: 0.4156
# }
#
symbol = None
if market is not None:
symbol = market['symbol']
timestamp = self.safe_integer(ticker, 'ts')
bid = None
bidVolume = None
ask = None
askVolume = None
if 'bid' in ticker:
if isinstance(ticker['bid'], list):
bid = self.safe_float(ticker['bid'], 0)
bidVolume = self.safe_float(ticker['bid'], 1)
else:
bid = self.safe_float(ticker, 'bid')
bidVolume = self.safe_value(ticker, 'bidSize')
if 'ask' in ticker:
if isinstance(ticker['ask'], list):
ask = self.safe_float(ticker['ask'], 0)
askVolume = self.safe_float(ticker['ask'], 1)
else:
ask = self.safe_float(ticker, 'ask')
askVolume = self.safe_value(ticker, 'askSize')
open = self.safe_float(ticker, 'open')
close = self.safe_float(ticker, 'close')
change = None
percentage = None
average = None
if (open is not None) and (close is not None):
change = close - open
average = self.sum(open, close) / 2
if (close is not None) and (close > 0):
percentage = (change / open) * 100
baseVolume = self.safe_float(ticker, 'amount')
quoteVolume = self.safe_float(ticker, 'vol')
vwap = self.vwap(baseVolume, quoteVolume)
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_float(ticker, 'high'),
'low': self.safe_float(ticker, 'low'),
'bid': bid,
'bidVolume': bidVolume,
'ask': ask,
'askVolume': askVolume,
'vwap': vwap,
'open': open,
'close': close,
'last': close,
'previousClose': None,
'change': change,
'percentage': percentage,
'average': average,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}
async def fetch_order_book(self, symbol, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
'type': 'step0',
}
response = await self.marketGetDepth(self.extend(request, params))
#
# {
# "status": "ok",
# "ch": "market.btcusdt.depth.step0",
# "ts": 1583474832790,
# "tick": {
# "bids": [
# [9100.290000000000000000, 0.200000000000000000],
# [9099.820000000000000000, 0.200000000000000000],
# [9099.610000000000000000, 0.205000000000000000],
# ],
# "asks": [
# [9100.640000000000000000, 0.005904000000000000],
# [9101.010000000000000000, 0.287311000000000000],
# [9101.030000000000000000, 0.012121000000000000],
# ],
# "ts":1583474832008,
# "version":104999698780
# }
# }
#
if 'tick' in response:
if not response['tick']:
raise ExchangeError(self.id + ' fetchOrderBook() returned empty response: ' + self.json(response))
tick = self.safe_value(response, 'tick')
timestamp = self.safe_integer(tick, 'ts', self.safe_integer(response, 'ts'))
result = self.parse_order_book(tick, timestamp)
result['nonce'] = self.safe_integer(tick, 'version')
return result
raise ExchangeError(self.id + ' fetchOrderBook() returned unrecognized response: ' + self.json(response))
async def fetch_ticker(self, symbol, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
response = await self.marketGetDetailMerged(self.extend(request, params))
#
# {
# "status": "ok",
# "ch": "market.btcusdt.detail.merged",
# "ts": 1583494336669,
# "tick": {
# "amount": 26228.672978342216,
# "open": 9078.95,
# "close": 9146.86,
# "high": 9155.41,
# "id": 209988544334,
# "count": 265846,
# "low": 8988.0,
# "version": 209988544334,
# "ask": [9146.87, 0.156134],
# "vol": 2.3822168242201668E8,
# "bid": [9146.86, 0.080758],
# }
# }
#
ticker = self.parse_ticker(response['tick'], market)
timestamp = self.safe_value(response, 'ts')
ticker['timestamp'] = timestamp
ticker['datetime'] = self.iso8601(timestamp)
return ticker
async def fetch_tickers(self, symbols=None, params={}):
await self.load_markets()
response = await self.marketGetTickers(params)
tickers = self.safe_value(response, 'data')
timestamp = self.safe_integer(response, 'ts')
result = {}
for i in range(0, len(tickers)):
marketId = self.safe_string(tickers[i], 'symbol')
market = self.safe_value(self.markets_by_id, marketId)
symbol = marketId
if market is not None:
symbol = market['symbol']
ticker = self.parse_ticker(tickers[i], market)
ticker['timestamp'] = timestamp
ticker['datetime'] = self.iso8601(timestamp)
result[symbol] = ticker
return self.filter_by_array(result, 'symbol', symbols)
def parse_trade(self, trade, market=None):
#
# fetchTrades(public)
#
# {
# "amount": 0.010411000000000000,
# "trade-id": 102090736910,
# "ts": 1583497692182,
# "id": 10500517034273194594947,
# "price": 9096.050000000000000000,
# "direction": "sell"
# }
#
# fetchMyTrades(private)
#
# {
# 'symbol': 'swftcbtc',
# 'fee-currency': 'swftc',
# 'filled-fees': '0',
# 'source': 'spot-api',
# 'id': 83789509854000,
# 'type': 'buy-limit',
# 'order-id': 83711103204909,
# 'filled-points': '0.005826843283532154',
# 'fee-deduct-currency': 'ht',
# 'filled-amount': '45941.53',
# 'price': '0.0000001401',
# 'created-at': 1597933260729,
# 'match-id': 100087455560,
# 'role': 'maker',
# 'trade-id': 100050305348
# },
#
symbol = None
if market is None:
marketId = self.safe_string(trade, 'symbol')
if marketId in self.markets_by_id:
market = self.markets_by_id[marketId]
if market is not None:
symbol = market['symbol']
timestamp = self.safe_integer_2(trade, 'ts', 'created-at')
order = self.safe_string(trade, 'order-id')
side = self.safe_string(trade, 'direction')
type = self.safe_string(trade, 'type')
if type is not None:
typeParts = type.split('-')
side = typeParts[0]
type = typeParts[1]
takerOrMaker = self.safe_string(trade, 'role')
price = self.safe_float(trade, 'price')
amount = self.safe_float_2(trade, 'filled-amount', 'amount')
cost = None
if price is not None:
if amount is not None:
cost = amount * price
fee = None
feeCost = self.safe_float(trade, 'filled-fees')
feeCurrency = None
if market is not None:
feeCurrency = self.safe_currency_code(self.safe_string(trade, 'fee-currency'))
filledPoints = self.safe_float(trade, 'filled-points')
if filledPoints is not None:
if (feeCost is None) or (feeCost == 0.0):
feeCost = filledPoints
feeCurrency = self.safe_currency_code(self.safe_string(trade, 'fee-deduct-currency'))
if feeCost is not None:
fee = {
'cost': feeCost,
'currency': feeCurrency,
}
tradeId = self.safe_string_2(trade, 'trade-id', 'tradeId')
id = self.safe_string(trade, 'id', tradeId)
return {
'id': id,
'info': trade,
'order': order,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'type': type,
'side': side,
'takerOrMaker': takerOrMaker,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
}
async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
market = None
request = {}
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
if limit is not None:
request['size'] = limit # 1-100 orders, default is 100
if since is not None:
request['start-date'] = self.ymd(since) # maximum query window size is 2 days, query window shift should be within past 120 days
response = await self.privateGetOrderMatchresults(self.extend(request, params))
trades = self.parse_trades(response['data'], market, since, limit)
return trades
async def fetch_trades(self, symbol, since=None, limit=1000, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if limit is not None:
request['size'] = limit
response = await self.marketGetHistoryTrade(self.extend(request, params))
#
# {
# "status": "ok",
# "ch": "market.btcusdt.trade.detail",
# "ts": 1583497692365,
# "data": [
# {
# "id": 105005170342,
# "ts": 1583497692182,
# "data": [
# {
# "amount": 0.010411000000000000,
# "trade-id": 102090736910,
# "ts": 1583497692182,
# "id": 10500517034273194594947,
# "price": 9096.050000000000000000,
# "direction": "sell"
# }
# ]
# },
# # ...
# ]
# }
#
data = self.safe_value(response, 'data')
result = []
for i in range(0, len(data)):
trades = self.safe_value(data[i], 'data', [])
for j in range(0, len(trades)):
trade = self.parse_trade(trades[j], market)
result.append(trade)
result = self.sort_by(result, 'timestamp')
return self.filter_by_symbol_since_limit(result, symbol, since, limit)
def parse_ohlcv(self, ohlcv, market=None):
#
# {
# "amount":1.2082,
# "open":0.025096,
# "close":0.025095,
# "high":0.025096,
# "id":1591515300,
# "count":6,
# "low":0.025095,
# "vol":0.0303205097
# }
#
return [
self.safe_timestamp(ohlcv, 'id'),
self.safe_float(ohlcv, 'open'),
self.safe_float(ohlcv, 'high'),
self.safe_float(ohlcv, 'low'),
self.safe_float(ohlcv, 'close'),
self.safe_float(ohlcv, 'amount'),
]
async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=1000, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
'period': self.timeframes[timeframe],
}
if limit is not None:
request['size'] = limit
response = await self.marketGetHistoryKline(self.extend(request, params))
#
# {
# "status":"ok",
# "ch":"market.ethbtc.kline.1min",
# "ts":1591515374371,
# "data":[
# {"amount":0.0,"open":0.025095,"close":0.025095,"high":0.025095,"id":1591515360,"count":0,"low":0.025095,"vol":0.0},
# {"amount":1.2082,"open":0.025096,"close":0.025095,"high":0.025096,"id":1591515300,"count":6,"low":0.025095,"vol":0.0303205097},
# {"amount":0.0648,"open":0.025096,"close":0.025096,"high":0.025096,"id":1591515240,"count":2,"low":0.025096,"vol":0.0016262208},
# ]
# }
#
data = self.safe_value(response, 'data', [])
return self.parse_ohlcvs(data, market, timeframe, since, limit)
async def fetch_accounts(self, params={}):
await self.load_markets()
response = await self.privateGetAccountAccounts(params)
return response['data']
async def fetch_currencies(self, params={}):
request = {
'language': self.options['language'],
}
response = await self.publicGetSettingsCurrencys(self.extend(request, params))
currencies = self.safe_value(response, 'data')
result = {}
for i in range(0, len(currencies)):
currency = currencies[i]
#
# { name: "ctxc",
# 'display-name': "CTXC",
# 'withdraw-precision': 8,
# 'currency-type': "eth",
# 'currency-partition': "pro",
# 'support-sites': null,
# 'otc-enable': 0,
# 'deposit-min-amount': "2",
# 'withdraw-min-amount': "4",
# 'show-precision': "8",
# weight: "2988",
# visible: True,
# 'deposit-desc': "Please don’t deposit any other digital assets except CTXC t…",
# 'withdraw-desc': "Minimum withdrawal amount: 4 CTXC. not >_<not For security reason…",
# 'deposit-enabled': True,
# 'withdraw-enabled': True,
# 'currency-addr-with-tag': False,
# 'fast-confirms': 15,
# 'safe-confirms': 30 }
#
id = self.safe_value(currency, 'name')
precision = self.safe_integer(currency, 'withdraw-precision')
code = self.safe_currency_code(id)
active = currency['visible'] and currency['deposit-enabled'] and currency['withdraw-enabled']
name = self.safe_string(currency, 'display-name')
result[code] = {
'id': id,
'code': code,
'type': 'crypto',
# 'payin': currency['deposit-enabled'],
# 'payout': currency['withdraw-enabled'],
# 'transfer': None,
'name': name,
'active': active,
'fee': None, # todo need to fetch from fee endpoint
'precision': precision,
'limits': {
'amount': {
'min': math.pow(10, -precision),
'max': math.pow(10, precision),
},
'price': {
'min': math.pow(10, -precision),
'max': math.pow(10, precision),
},
'cost': {
'min': None,
'max': None,
},
'deposit': {
'min': self.safe_float(currency, 'deposit-min-amount'),
'max': math.pow(10, precision),
},
'withdraw': {
'min': self.safe_float(currency, 'withdraw-min-amount'),
'max': math.pow(10, precision),
},
},
'info': currency,
}
return result
async def fetch_balance(self, params={}):
await self.load_markets()
await self.load_accounts()
method = self.options['fetchBalanceMethod']
request = {
'id': self.accounts[0]['id'],
}
response = await getattr(self, method)(self.extend(request, params))
balances = self.safe_value(response['data'], 'list', [])
result = {'info': response}
for i in range(0, len(balances)):
balance = balances[i]
currencyId = self.safe_string(balance, 'currency')
code = self.safe_currency_code(currencyId)
account = None
if code in result:
account = result[code]
else:
account = self.account()
if balance['type'] == 'trade':
account['free'] = self.safe_float(balance, 'balance')
if balance['type'] == 'frozen':
account['used'] = self.safe_float(balance, 'balance')
result[code] = account
return self.parse_balance(result)
async def fetch_orders_by_states(self, states, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
request = {
'states': states,
}
market = None
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
method = self.safe_string(self.options, 'fetchOrdersByStatesMethod', 'private_get_order_orders')
response = await getattr(self, method)(self.extend(request, params))
#
# {status: "ok",
# data: [{ id: 13997833014,
# symbol: "ethbtc",
# 'account-id': 3398321,
# amount: "0.045000000000000000",
# price: "0.034014000000000000",
# 'created-at': 1545836976871,
# type: "sell-limit",
# 'field-amount': "0.045000000000000000",
# 'field-cash-amount': "0.001530630000000000",
# 'field-fees': "0.000003061260000000",
# 'finished-at': 1545837948214,
# source: "spot-api",
# state: "filled",
# 'canceled-at': 0 } ]}
#
return self.parse_orders(response['data'], market, since, limit)
async def fetch_order(self, id, symbol=None, params={}):
await self.load_markets()
request = {
'id': id,
}
response = await self.privateGetOrderOrdersId(self.extend(request, params))
order = self.safe_value(response, 'data')
return self.parse_order(order)
async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
return await self.fetch_orders_by_states('pre-submitted,submitted,partial-filled,filled,partial-canceled,canceled', symbol, since, limit, params)
async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
method = self.safe_string(self.options, 'fetchOpenOrdersMethod', 'fetch_open_orders_v1')
return await getattr(self, method)(symbol, since, limit, params)
async def fetch_open_orders_v1(self, symbol=None, since=None, limit=None, params={}):
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchOpenOrdersV1 requires a symbol argument')
return await self.fetch_orders_by_states('pre-submitted,submitted,partial-filled', symbol, since, limit, params)
async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
return await self.fetch_orders_by_states('filled,partial-canceled,canceled', symbol, since, limit, params)
async def fetch_open_orders_v2(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchOpenOrders requires a symbol argument')
market = self.market(symbol)
accountId = self.safe_string(params, 'account-id')
if accountId is None:
# pick the first account
await self.load_accounts()
for i in range(0, len(self.accounts)):
account = self.accounts[i]
if account['type'] == 'spot':
accountId = self.safe_string(account, 'id')
if accountId is not None:
break
request = {
'symbol': market['id'],
'account-id': accountId,
}
if limit is not None:
request['size'] = limit
omitted = self.omit(params, 'account-id')
response = await self.privateGetOrderOpenOrders(self.extend(request, omitted))
#
# {
# "status":"ok",
# "data":[
# {
# "symbol":"ethusdt",
# "source":"api",
# "amount":"0.010000000000000000",
# "account-id":1528640,
# "created-at":1561597491963,
# "price":"400.000000000000000000",
# "filled-amount":"0.0",
# "filled-cash-amount":"0.0",
# "filled-fees":"0.0",
# "id":38477101630,
# "state":"submitted",
# "type":"sell-limit"
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
return self.parse_orders(data, market, since, limit)
def parse_order_status(self, status):
statuses = {
'partial-filled': 'open',
'partial-canceled': 'canceled',
'filled': 'closed',
'canceled': 'canceled',
'submitted': 'open',
}
return self.safe_string(statuses, status, status)
def parse_order(self, order, market=None):
#
# { id: 13997833014,
# symbol: "ethbtc",
# 'account-id': 3398321,
# amount: "0.045000000000000000",
# price: "0.034014000000000000",
# 'created-at': 1545836976871,
# type: "sell-limit",
# 'field-amount': "0.045000000000000000", # they have fixed it for filled-amount
# 'field-cash-amount': "0.001530630000000000", # they have fixed it for filled-cash-amount
# 'field-fees': "0.000003061260000000", # they have fixed it for filled-fees
# 'finished-at': 1545837948214,
# source: "spot-api",
# state: "filled",
# 'canceled-at': 0 }
#
# { id: 20395337822,
# symbol: "ethbtc",
# 'account-id': 5685075,
# amount: "0.001000000000000000",
# price: "0.0",
# 'created-at': 1545831584023,
# type: "buy-market",
# 'field-amount': "0.029100000000000000", # they have fixed it for filled-amount
# 'field-cash-amount': "0.000999788700000000", # they have fixed it for filled-cash-amount
# 'field-fees': "0.000058200000000000", # they have fixed it for filled-fees
# 'finished-at': 1545831584181,
# source: "spot-api",
# state: "filled",
# 'canceled-at': 0 }
#
id = self.safe_string(order, 'id')
side = None
type = None
status = None
if 'type' in order:
orderType = order['type'].split('-')
side = orderType[0]
type = orderType[1]
status = self.parse_order_status(self.safe_string(order, 'state'))
symbol = None
if market is None:
if 'symbol' in order:
if order['symbol'] in self.markets_by_id:
marketId = order['symbol']
market = self.markets_by_id[marketId]
if market is not None:
symbol = market['symbol']
timestamp = self.safe_integer(order, 'created-at')
amount = self.safe_float(order, 'amount')
filled = self.safe_float_2(order, 'filled-amount', 'field-amount') # typo in their API, filled amount
if (type == 'market') and (side == 'buy'):
amount = filled if (status == 'closed') else None
price = self.safe_float(order, 'price')
if price == 0.0:
price = None
cost = self.safe_float_2(order, 'filled-cash-amount', 'field-cash-amount') # same typo
remaining = None
average = None
if filled is not None:
if amount is not None:
remaining = amount - filled
# if cost is defined and filled is not zero
if (cost is not None) and (filled > 0):
average = cost / filled
feeCost = self.safe_float_2(order, 'filled-fees', 'field-fees') # typo in their API, filled fees
fee = None
if feeCost is not None:
feeCurrency = None
if market is not None:
feeCurrency = market['quote'] if (side == 'sell') else market['base']
fee = {
'cost': feeCost,
'currency': feeCurrency,
}
return {
'info': order,
'id': id,
'clientOrderId': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'average': average,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': fee,
'trades': None,
}
async def create_order(self, symbol, type, side, amount, price=None, params={}):
await self.load_markets()
await self.load_accounts()
market = self.market(symbol)
request = {
'account-id': self.accounts[0]['id'],
'symbol': market['id'],
'type': side + '-' + type,
}
if (type == 'market') and (side == 'buy'):
if self.options['createMarketBuyOrderRequiresPrice']:
if price is None:
raise InvalidOrder(self.id + " market buy order requires price argument to calculate cost(total amount of quote currency to spend for buying, amount * price). To switch off self warning exception and specify cost in the amount argument, set .options['createMarketBuyOrderRequiresPrice'] = False. Make sure you know what you're doing.")
else:
# despite that cost = amount * price is in quote currency and should have quote precision
# the exchange API requires the cost supplied in 'amount' to be of base precision
# more about it here:
# https://github.com/ccxt/ccxt/pull/4395
# https://github.com/ccxt/ccxt/issues/7611
# we use amountToPrecision here because the exchange requires cost in base precision
request['amount'] = self.costtToPrecision(symbol, float(amount) * float(price))
else:
request['amount'] = self.cost_to_precision(symbol, amount)
else:
request['amount'] = self.amount_to_precision(symbol, amount)
if type == 'limit' or type == 'ioc' or type == 'limit-maker':
request['price'] = self.price_to_precision(symbol, price)
method = self.options['createOrderMethod']
response = await getattr(self, method)(self.extend(request, params))
timestamp = self.milliseconds()
id = self.safe_string(response, 'data')
return {
'info': response,
'id': id,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'status': None,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'amount': amount,
'filled': None,
'remaining': None,
'cost': None,
'trades': None,
'fee': None,
'clientOrderId': None,
'average': None,
}
async def cancel_order(self, id, symbol=None, params={}):
response = await self.privatePostOrderOrdersIdSubmitcancel({'id': id})
#
# response = {
# 'status': 'ok',
# 'data': '10138899000',
# }
#
return self.extend(self.parse_order(response), {
'id': id,
'status': 'canceled',
})
def currency_to_precision(self, currency, fee):
return self.decimal_to_precision(fee, 0, self.currencies[currency]['precision'])
def calculate_fee(self, symbol, type, side, amount, price, takerOrMaker='taker', params={}):
market = self.markets[symbol]
rate = market[takerOrMaker]
cost = amount * rate
key = 'quote'
if side == 'sell':
cost *= price
else:
key = 'base'
return {
'type': takerOrMaker,
'currency': market[key],
'rate': rate,
'cost': float(self.currency_to_precision(market[key], cost)),
}
def parse_deposit_address(self, depositAddress, currency=None):
#
# {
# currency: "eth",
# address: "0xf7292eb9ba7bc50358e27f0e025a4d225a64127b",
# addressTag: "",
# chain: "eth"
# }
#
address = self.safe_string(depositAddress, 'address')
tag = self.safe_string(depositAddress, 'addressTag')
currencyId = self.safe_string(depositAddress, 'currency')
code = self.safe_currency_code(currencyId)
self.check_address(address)
return {
'currency': code,
'address': address,
'tag': tag,
'info': depositAddress,
}
async def fetch_deposit_address(self, code, params={}):
await self.load_markets()
currency = self.currency(code)
request = {
'currency': currency['id'],
}
response = await self.v2PrivateGetAccountDepositAddress(self.extend(request, params))
#
# {
# code: 200,
# data: [
# {
# currency: "eth",
# address: "0xf7292eb9ba7bc50358e27f0e025a4d225a64127b",
# addressTag: "",
# chain: "eth"
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
return self.parse_deposit_address(self.safe_value(data, 0, {}), currency)
async def fetch_deposits(self, code=None, since=None, limit=None, params={}):
if limit is None or limit > 100:
limit = 100
await self.load_markets()
currency = None
if code is not None:
currency = self.currency(code)
request = {
'type': 'deposit',
'from': 0, # From 'id' ... if you want to get results after a particular transaction id, pass the id in params.from
}
if currency is not None:
request['currency'] = currency['id']
if limit is not None:
request['size'] = limit # max 100
response = await self.privateGetQueryDepositWithdraw(self.extend(request, params))
# return response
return self.parse_transactions(response['data'], currency, since, limit)
async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
if limit is None or limit > 100:
limit = 100
await self.load_markets()
currency = None
if code is not None:
currency = self.currency(code)
request = {
'type': 'withdraw',
'from': 0, # From 'id' ... if you want to get results after a particular transaction id, pass the id in params.from
}
if currency is not None:
request['currency'] = currency['id']
if limit is not None:
request['size'] = limit # max 100
response = await self.privateGetQueryDepositWithdraw(self.extend(request, params))
# return response
return self.parse_transactions(response['data'], currency, since, limit)
def parse_transaction(self, transaction, currency=None):
#
# fetchDeposits
#
# {
# 'id': 8211029,
# 'type': 'deposit',
# 'currency': 'eth',
# 'chain': 'eth',
# 'tx-hash': 'bd315....',
# 'amount': 0.81162421,
# 'address': '4b8b....',
# 'address-tag': '',
# 'fee': 0,
# 'state': 'safe',
# 'created-at': 1542180380965,
# 'updated-at': 1542180788077
# }
#
# fetchWithdrawals
#
# {
# 'id': 6908275,
# 'type': 'withdraw',
# 'currency': 'btc',
# 'chain': 'btc',
# 'tx-hash': 'c1a1a....',
# 'amount': 0.80257005,
# 'address': '1QR....',
# 'address-tag': '',
# 'fee': 0.0005,
# 'state': 'confirmed',
# 'created-at': 1552107295685,
# 'updated-at': 1552108032859
# }
#
timestamp = self.safe_integer(transaction, 'created-at')
updated = self.safe_integer(transaction, 'updated-at')
code = self.safe_currency_code(self.safe_string(transaction, 'currency'))
type = self.safe_string(transaction, 'type')
if type == 'withdraw':
type = 'withdrawal'
status = self.parse_transaction_status(self.safe_string(transaction, 'state'))
tag = self.safe_string(transaction, 'address-tag')
feeCost = self.safe_float(transaction, 'fee')
if feeCost is not None:
feeCost = abs(feeCost)
return {
'info': transaction,
'id': self.safe_string(transaction, 'id'),
'txid': self.safe_string(transaction, 'tx-hash'),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'address': self.safe_string(transaction, 'address'),
'tag': tag,
'type': type,
'amount': self.safe_float(transaction, 'amount'),
'currency': code,
'status': status,
'updated': updated,
'fee': {
'currency': code,
'cost': feeCost,
'rate': None,
},
}
def parse_transaction_status(self, status):
statuses = {
# deposit statuses
'unknown': 'failed',
'confirming': 'pending',
'confirmed': 'ok',
'safe': 'ok',
'orphan': 'failed',
# withdrawal statuses
'submitted': 'pending',
'canceled': 'canceled',
'reexamine': 'pending',
'reject': 'failed',
'pass': 'pending',
'wallet-reject': 'failed',
# 'confirmed': 'ok', # present in deposit statuses
'confirm-error': 'failed',
'repealed': 'failed',
'wallet-transfer': 'pending',
'pre-transfer': 'pending',
}
return self.safe_string(statuses, status, status)
async def withdraw(self, code, amount, address, tag=None, params={}):
await self.load_markets()
self.check_address(address)
currency = self.currency(code)
request = {
'address': address, # only supports existing addresses in your withdraw address list
'amount': amount,
'currency': currency['id'].lower(),
}
if tag is not None:
request['addr-tag'] = tag # only for XRP?
response = await self.privatePostDwWithdrawApiCreate(self.extend(request, params))
id = self.safe_string(response, 'data')
return {
'info': response,
'id': id,
}
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/'
if api == 'market':
url += api
elif (api == 'public') or (api == 'private'):
url += self.version
elif (api == 'v2Public') or (api == 'v2Private'):
url += 'v2'
url += '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'private' or api == 'v2Private':
self.check_required_credentials()
timestamp = self.ymdhms(self.milliseconds(), 'T')
request = {
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '2',
'AccessKeyId': self.apiKey,
'Timestamp': timestamp,
}
if method != 'POST':
request = self.extend(request, query)
request = self.keysort(request)
auth = self.urlencode(request)
# unfortunately, PHP demands double quotes for the escaped newline symbol
# eslint-disable-next-line quotes
payload = "\n".join([method, self.hostname, url, auth])
signature = self.hmac(self.encode(payload), self.encode(self.secret), hashlib.sha256, 'base64')
auth += '&' + self.urlencode({'Signature': signature})
url += '?' + auth
if method == 'POST':
body = self.json(query)
headers = {
'Content-Type': 'application/json',
}
else:
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
else:
if params:
url += '?' + self.urlencode(params)
url = self.implode_params(self.urls['api'][api], {
'hostname': self.hostname,
}) + url
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def handle_errors(self, httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody):
if response is None:
return # fallback to default error handler
if 'status' in response:
#
# {"status":"error","err-code":"order-limitorder-amount-min-error","err-msg":"limit order amount error, min: `0.001`","data":null}
#
status = self.safe_string(response, 'status')
if status == 'error':
code = self.safe_string(response, 'err-code')
feedback = self.id + ' ' + body
self.throw_exactly_matched_exception(self.exceptions['exact'], code, feedback)
message = self.safe_string(response, 'err-msg')
self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
raise ExchangeError(feedback)
| 43.899716
| 355
| 0.484698
|
4bcedbd7b4ffbca748c760e8e1dcbcb940f49430
| 2,221
|
py
|
Python
|
eisenmann-backend/service/migrations/0001_initial.py
|
RubenRodrigo/Eisenmann-Inventory
|
5abb59a11d43987db3d1742b6f0978c6aa6ee81d
|
[
"MIT"
] | null | null | null |
eisenmann-backend/service/migrations/0001_initial.py
|
RubenRodrigo/Eisenmann-Inventory
|
5abb59a11d43987db3d1742b6f0978c6aa6ee81d
|
[
"MIT"
] | null | null | null |
eisenmann-backend/service/migrations/0001_initial.py
|
RubenRodrigo/Eisenmann-Inventory
|
5abb59a11d43987db3d1742b6f0978c6aa6ee81d
|
[
"MIT"
] | null | null | null |
# Generated by Django 3.2.5 on 2022-01-31 11:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('product', '0001_initial'),
('employee', '0001_initial'),
('client', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Service',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('code', models.CharField(blank=True, max_length=8, null=True)),
('estimated_price', models.CharField(blank=True, max_length=128, null=True)),
('init_date', models.DateField(blank=True, null=True)),
('end_date', models.DateField(blank=True, null=True)),
('observations', models.TextField(blank=True, null=True)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('state', models.BooleanField(default=False)),
('client', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='client_services', to='client.client')),
],
),
migrations.CreateModel(
name='ServiceProductDetail',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.TextField(blank=True, null=True)),
('quantity', models.IntegerField(blank=True, default=0, null=True)),
('total_cost', models.FloatField(blank=True, default=0.0, null=True)),
('employee', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='employee.employee')),
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='product.productstock')),
('service', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='service_products', to='service.service')),
],
),
]
| 49.355556
| 170
| 0.615038
|
2a8566e4cd6e4c7b7f59bc6fbabffb5f1337881e
| 1,461
|
py
|
Python
|
linked_list.py
|
cunctat0r/pystudy
|
5fe55518faa6ba957001ce9c6f268babb4b98784
|
[
"MIT"
] | null | null | null |
linked_list.py
|
cunctat0r/pystudy
|
5fe55518faa6ba957001ce9c6f268babb4b98784
|
[
"MIT"
] | null | null | null |
linked_list.py
|
cunctat0r/pystudy
|
5fe55518faa6ba957001ce9c6f268babb4b98784
|
[
"MIT"
] | null | null | null |
class Node(object):
def __init__(self, data, nxt=None):
self.data = data
self.next_node = nxt
def get_next(self):
return self.next_node
def set_next(self, nxt):
self.next_node = nxt
def get_data(self):
return self.data
def set_data(delf, data):
self.data = data
class LinkedList(object):
def __init__(self, root=None):
self.root = root
self.size = 0
def get_size(self):
return self.size
def add(self, data):
new_node = Node(data, self.root)
self.root = new_node
self.size += 1
def remove(self, data):
this_node = self.root
prev_node = None
while this_node:
if this_node.get_data() == data:
if prev_node:
prev_node.set_next(this_node.get_next())
else:
self.root = this_node
self.size -= 1
return True
else:
prev_node = this_node
this_node = this_node.get_next()
return False
def find(self, data):
this_node = self.root
while this_node:
if this_node.get_data() == data:
return data
else:
this_node = this_node.get_next()
return None
myList = LinkedList()
myList.add(5)
myList.add(8)
myList.add(12)
myList.remove(8)
print(myList.find(5))
| 23.564516
| 60
| 0.531828
|
8ba12b6a1db5d0324347ee37f701ccc86197dc3c
| 569
|
py
|
Python
|
api/features/migrations/0033_feature_owners.py
|
mevinbabuc/flagsmith
|
751bd6cb4a34bd2f80af5a9c547559da9c2fa010
|
[
"BSD-3-Clause"
] | 1,259
|
2021-06-10T11:24:09.000Z
|
2022-03-31T10:30:44.000Z
|
api/features/migrations/0033_feature_owners.py
|
mevinbabuc/flagsmith
|
751bd6cb4a34bd2f80af5a9c547559da9c2fa010
|
[
"BSD-3-Clause"
] | 392
|
2021-06-10T11:12:29.000Z
|
2022-03-31T10:13:53.000Z
|
api/features/migrations/0033_feature_owners.py
|
mevinbabuc/flagsmith
|
751bd6cb4a34bd2f80af5a9c547559da9c2fa010
|
[
"BSD-3-Clause"
] | 58
|
2021-06-11T03:18:07.000Z
|
2022-03-31T14:39:10.000Z
|
# Generated by Django 2.2.24 on 2021-09-19 11:36
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("features", "0032_update_feature_type"),
]
operations = [
migrations.AddField(
model_name="feature",
name="owners",
field=models.ManyToManyField(
related_name="owned_features", to=settings.AUTH_USER_MODEL
),
),
]
| 24.73913
| 74
| 0.630931
|
10dd16be2abb4036d19f9676058453da831f6e1a
| 13,254
|
py
|
Python
|
segtypes/common/data.py
|
paulsapps/splat
|
e312b86f36982dfddc4b00f082d7066f0b259938
|
[
"MIT"
] | null | null | null |
segtypes/common/data.py
|
paulsapps/splat
|
e312b86f36982dfddc4b00f082d7066f0b259938
|
[
"MIT"
] | null | null | null |
segtypes/common/data.py
|
paulsapps/splat
|
e312b86f36982dfddc4b00f082d7066f0b259938
|
[
"MIT"
] | null | null | null |
from segtypes.common.code import CommonSegCode
from segtypes.common.codesubsegment import CommonSegCodeSubsegment
from segtypes.common.group import CommonSegGroup
from pathlib import Path
from typing import List, Optional
from util.symbols import Symbol
from util import floats, options
class CommonSegData(CommonSegCodeSubsegment, CommonSegGroup):
def out_path(self) -> Optional[Path]:
if self.type.startswith("."):
if self.sibling:
# C file
return self.sibling.out_path()
else:
# Implied C file
return options.get_src_path() / self.dir / f"{self.name}.c"
else:
# ASM
return options.get_asm_path() / "data" / self.dir / f"{self.name}.{self.type}.s"
def scan(self, rom_bytes: bytes):
CommonSegGroup.scan(self, rom_bytes)
if super().should_scan():
self.file_text = self.disassemble_data(rom_bytes)
else:
self.file_text = None
def split(self, rom_bytes: bytes):
CommonSegGroup.split(self, rom_bytes)
if not self.type.startswith(".") and self.file_text:
path = self.out_path()
if path:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", newline="\n") as f:
f.write(self.file_text)
def should_split(self) -> bool:
return True
def should_scan(self) -> bool:
return True
def cache(self):
return [CommonSegCodeSubsegment.cache(self), CommonSegGroup.cache(self)]
def get_linker_section(self) -> str:
return ".data"
def get_linker_entries(self):
return CommonSegCodeSubsegment.get_linker_entries(self)
# Check symbols marked as jump tables to be valid
def check_jtbls(self, rom_bytes, syms: List[Symbol]):
endianness = options.get_endianess()
for i, sym in enumerate(syms):
if sym.type == "jtbl":
start = self.get_most_parent().ram_to_rom(syms[i].vram_start)
assert isinstance(start, int)
end = self.get_most_parent().ram_to_rom(syms[i + 1].vram_start)
sym_bytes = rom_bytes[start:end]
b = 0
last_bits = 0
while b < len(sym_bytes):
bits = int.from_bytes(sym_bytes[b : b + 4], endianness)
if last_bits != 0 and bits != 0 and abs(last_bits - bits) > 0x100000:
new_sym_rom_start = start + b
new_sym_ram_start = self.get_most_parent().rom_to_ram(new_sym_rom_start)
sym.size = new_sym_rom_start - sym.rom
# It turns out this isn't a valid jump table, so create a new symbol where it breaks
syms.insert(i + 1, self.get_most_parent().create_symbol(new_sym_ram_start, define=True, local_only=True))
return False
if bits != 0:
last_bits = bits
b += 4
return True
def get_symbols(self, rom_bytes) -> List[Symbol]:
symset = set()
endian = options.get_endianess()
# Find inter-data symbols
for i in range(self.rom_start, self.rom_end, 4):
bits = int.from_bytes(rom_bytes[i : i + 4], endian)
if self.contains_vram(bits):
symset.add(self.get_most_parent().create_symbol(bits, define=True, local_only=True))
for symbol_addr in self.seg_symbols:
for symbol in self.seg_symbols[symbol_addr]:
if not symbol.dead and self.contains_vram(symbol.vram_start):
symset.add(symbol)
ret: List[Symbol] = list(symset)
ret.sort(key=lambda s:s.vram_start)
# Ensure we start at the beginning
if len(ret) == 0 or ret[0].vram_start != self.vram_start:
ret.insert(0, self.get_most_parent().create_symbol(self.vram_start, define=True, local_only=True))
# Make a dummy symbol here that marks the end of the previous symbol's disasm range
ret.append(Symbol(self.vram_end))
while True:
valid = self.check_jtbls(rom_bytes, ret)
if valid:
break
return ret
def are_null(chars):
for b in chars:
if b != '\x00':
return False
return True
@staticmethod
def is_valid_ascii(bytes):
null_char = '\x00'
valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890[]():%!#=-_ "
invalid_chars = ""
duplicate_limit = 10
last_char = 0
true_end = None
consecutive_duplicates = 0
valid_count = 0
if len(bytes) <= 4 or bytes[0] == 0:
return False
try:
chars = bytes.decode("EUC-JP")
except:
return False
if len(chars) <= 4:
return False
for i, c in enumerate(chars):
# Ensure null bytes are only at the end of ascii strings
# TODO: if we find null bytes in the middle, break this into multiple strings ?
if c == null_char:
if true_end is None:
if CommonSegData.are_null(chars[i:]):
true_end = i
else:
pass
#return False
# Ensure we're not seeing a ton of the same character in a row
if last_char == c:
consecutive_duplicates += 1
if consecutive_duplicates >= duplicate_limit and last_char != null_char:
return False
else:
consecutive_duplicates = 0
if c in valid_chars:
valid_count += 1
elif c in invalid_chars:
return False
last_char = c
# Ensure the number of valid characters is sufficient
if true_end is not None:
# If there are more than 16 null chars at the end, something is afoot
if len(chars) - true_end > 16:
return False
end = true_end
else:
end = len(chars)
valid_ratio = valid_count / end
if valid_ratio >= 0.75:
return True
return False
# TODO if we see a new function's jtbl, split it
def is_valid_jtbl(self, sym:Symbol, bytes) -> bool:
min_jtbl_len = 16
if len(bytes) % 4 != 0:
return False
# Jump tables must have at least 3 labels
if len(bytes) < min_jtbl_len:
return False
most_parent = self.get_most_parent()
assert isinstance(most_parent, CommonSegCode)
# Grab the first word and see if its value is an address within a function
word = int.from_bytes(bytes[0:4], options.get_endianess())
jtbl_func:Optional[Symbol] = self.get_most_parent().get_func_for_addr(word)
if not jtbl_func:
return False
for i in range(4, len(bytes), 4):
word = int.from_bytes(bytes[i:i+4], options.get_endianess())
# If the word doesn't contain an address in the current function, this isn't a valid jump table
if not jtbl_func.contains_vram(word):
# Allow jump tables that are of a minimum length and end in 0s
if i < min_jtbl_len or any(b != 0 for b in bytes[i:]):
return False
# Mark this symbol as a jump table and record the jump table for later
sym.type = "jtbl"
most_parent.jumptables[sym.vram_start] = (jtbl_func.vram_start, jtbl_func.vram_end)
return True
def disassemble_symbol(self, sym_bytes, sym_type):
endian = options.get_endianess()
if sym_type == "jtbl":
sym_str = ".word "
else:
sym_str = f".{sym_type} "
if sym_type == "double":
slen = 8
elif sym_type == "short":
slen = 2
elif sym_type == "byte":
slen = 1
else:
slen = 4
if sym_type == "ascii":
try:
ascii_str = sym_bytes.decode("EUC-JP")
# ascii_str = ascii_str.rstrip("\x00")
ascii_str = ascii_str.replace("\\", "\\\\") # escape back slashes
ascii_str = ascii_str.replace("\"", "\\\"") # escape quotes
ascii_str = ascii_str.replace("\x00", "\\0")
ascii_str = ascii_str.replace("\n", "\\n")
sym_str += f'"{ascii_str}"'
return sym_str
except:
return self.disassemble_symbol(sym_bytes, "word")
i = 0
while i < len(sym_bytes):
adv_amt = min(slen, len(sym_bytes) - i)
bits = int.from_bytes(sym_bytes[i : i + adv_amt], endian)
if sym_type == "jtbl":
if bits == 0:
byte_str = "0"
else:
rom_addr = self.get_most_parent().ram_to_rom(bits)
if rom_addr:
byte_str = f"L{bits:X}_{rom_addr:X}"
else:
byte_str = f"0x{bits:X}"
elif slen == 4 and bits >= 0x80000000:
sym = self.get_most_parent().get_symbol(bits, reference=True)
if sym:
byte_str = sym.name
else:
byte_str = '0x{0:0{1}X}'.format(bits, 2 * slen)
else:
byte_str = '0x{0:0{1}X}'.format(bits, 2 * slen)
if sym_type in ["float", "double"]:
if sym_type == "float":
float_str = floats.format_f32_imm(bits)
else:
float_str = floats.format_f64_imm(bits)
# Fall back to .word if we see weird float values
# TODO: cut the symbol in half maybe where we see the first nan or something
if "e-" in float_str or "nan" in float_str:
return self.disassemble_symbol(sym_bytes, "word")
else:
byte_str = float_str
sym_str += byte_str
i += adv_amt
if i < len(sym_bytes):
sym_str += ", "
return sym_str
def disassemble_data(self, rom_bytes):
rodata_encountered = "rodata" in self.type
ret = ".include \"macro.inc\"\n\n"
ret += f'.section {self.get_linker_section()}'
if self.size == 0:
return None
syms = self.get_symbols(rom_bytes)
for i in range(len(syms) - 1):
mnemonic = syms[i].access_mnemonic
sym = self.get_most_parent().create_symbol(syms[i].vram_start, define=True, local_only=True)
dis_start = self.get_most_parent().ram_to_rom(syms[i].vram_start)
dis_end = self.get_most_parent().ram_to_rom(syms[i + 1].vram_start)
sym_len = dis_end - dis_start
if self.type == "bss":
disasm_str = f".space 0x{sym_len:X}"
else:
sym_bytes = rom_bytes[dis_start : dis_end]
# Checking if the mnemonic is addiu may be too picky - we'll see
if self.is_valid_ascii(sym_bytes) and mnemonic == "addiu":
stype = "ascii"
elif sym.type == "jtbl":
stype = "jtbl"
elif self.is_valid_jtbl(sym, sym_bytes):
stype = "jtbl"
elif len(sym_bytes) % 8 == 0 and mnemonic in CommonSegCodeSubsegment.double_mnemonics:
stype = "double"
elif len(sym_bytes) % 4 == 0 and mnemonic in CommonSegCodeSubsegment.float_mnemonics:
stype = "float"
elif len(sym_bytes) % 4 == 0 and sym.vram_start % 4 == 0 and (mnemonic in CommonSegCodeSubsegment.word_mnemonics or not mnemonic):
stype = "word"
elif len(sym_bytes) % 2 == 0 and sym.vram_start % 2 == 0 and (mnemonic in CommonSegCodeSubsegment.short_mnemonics or not mnemonic):
stype = "short"
else:
stype = "byte"
# If we're starting from a weird place, make sure our container size is correct
if dis_start % 4 != 0 and stype != "byte" and sym_len > 1:
stype = "short"
if dis_start % 2 != 0:
stype = "byte"
# Hint to the user that we are now in the .rodata section and no longer in the .data section (assuming rodata follows data)
if not rodata_encountered and mnemonic == "jtbl" and self.get_most_parent().rodata_follows_data:
rodata_encountered = True
ret += "\n\n\n.section .rodata"
disasm_str = self.disassemble_symbol(sym_bytes, stype)
sym.disasm_str = disasm_str
name_str = f"\n\n{options.get_asm_data_macro()} {sym.name}\n"
ret += name_str + disasm_str
ret += "\n"
return ret
| 36.61326
| 147
| 0.543459
|
62d4f4f89a83f439fb9af5e57e54d2282e0eceef
| 1,835
|
py
|
Python
|
rlbench/tasks/disl_pick_up_blue_cup_ur.py
|
Schellenberg3/RLBench
|
eb282087d50a9758df319feef8e0762bf27d56ca
|
[
"BSD-3-Clause"
] | null | null | null |
rlbench/tasks/disl_pick_up_blue_cup_ur.py
|
Schellenberg3/RLBench
|
eb282087d50a9758df319feef8e0762bf27d56ca
|
[
"BSD-3-Clause"
] | null | null | null |
rlbench/tasks/disl_pick_up_blue_cup_ur.py
|
Schellenberg3/RLBench
|
eb282087d50a9758df319feef8e0762bf27d56ca
|
[
"BSD-3-Clause"
] | null | null | null |
from typing import List, Tuple
import numpy as np
from pyrep.objects.shape import Shape
from pyrep.objects.proximity_sensor import ProximitySensor
from rlbench.const import colors
from rlbench.backend.task import Task
from rlbench.backend.conditions import DetectedCondition, NothingGrasped, GraspedCondition
from rlbench.backend.spawn_boundary import SpawnBoundary
# Note that the class name MUST be a camel-case version of the file name
class DislPickUpBlueCupUr(Task):
def init_task(self) -> None:
self.cup = Shape('cup')
self.cup_visual = Shape('cup_visual')
self.boundary = SpawnBoundary([Shape('boundary')])
self.success_sensor = ProximitySensor('success')
self.register_graspable_objects([self.cup])
self.register_success_conditions([
DetectedCondition(self.cup, self.success_sensor, negated=True),
GraspedCondition(self.robot.gripper, self.cup),
])
def init_episode(self, index: int) -> List[str]:
self.variation_index = 0
target_color_name, target_rgb = colors[4] # gets ('blue', (0.0,0.0,1.0))
self.cup_visual.set_color(target_rgb)
self.boundary.clear()
self.boundary.sample(self.success_sensor, min_distance=0.1)
return ['pick up the %s cup' % target_color_name,
'grasp the %s cup and lift it' % target_color_name,
'lift the %s cup' % target_color_name]
def base_rotation_bounds(self) -> Tuple[List[float], List[float]]:
return [0.0, 0.0, -0.01], [0.0, 0.0, -0.01]
def is_static_workspace(self) -> bool:
return True
def reward(self): # -> Union[float, None]:
"""Allows the user to customise the task and add reward shaping."""
return None
def variation_count(self) -> int:
return 1
| 35.288462
| 90
| 0.673569
|
f929322fd15947e59964e596298437abbaf46242
| 15,609
|
py
|
Python
|
dataset/convert_tfrecords.py
|
wenzhenmiao/KITTI_to_tfrecords
|
febb7ab1948c827a0c9071ba0d1d1a859ce9a47c
|
[
"Apache-2.0"
] | 1
|
2020-03-09T19:23:02.000Z
|
2020-03-09T19:23:02.000Z
|
dataset/convert_tfrecords.py
|
wenzhenmiao/KITTI_to_tfrecords
|
febb7ab1948c827a0c9071ba0d1d1a859ce9a47c
|
[
"Apache-2.0"
] | null | null | null |
dataset/convert_tfrecords.py
|
wenzhenmiao/KITTI_to_tfrecords
|
febb7ab1948c827a0c9071ba0d1d1a859ce9a47c
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2018 Changan Wang
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os
import random
import sys
import threading
import xml.etree.ElementTree as xml_tree
import numpy as np
import six
import tensorflow as tf
import dataset_common
os.environ['CUDA_VISIBLE_DEVICES']='0'
'''How to organize your dataset folder:
VOCROOT/
|->VOC2007/
| |->Annotations/
| |->ImageSets/
| |->...
|->VOC2012/
| |->Annotations/
| |->ImageSets/
| |->...
|->VOC2007TEST/
| |->Annotations/
| |->...
'''
tf.app.flags.DEFINE_string('dataset_directory', '/home/mx/data/KITTIdevkit/KITTI',
'All datas directory')
tf.app.flags.DEFINE_string('train_splits', 'KITTITRAIN',
'Comma-separated list of the training data sub-directory')
tf.app.flags.DEFINE_string('validation_splits', 'KITTIVAL',
'Comma-separated list of the validation data sub-directory')
tf.app.flags.DEFINE_string('output_directory', '/home/mx/data/KITTIdevkit/KITTI/KITTItfrecords',
'Output data directory')
tf.app.flags.DEFINE_integer('train_shards', 16,
'Number of shards in training TFRecord files.')
tf.app.flags.DEFINE_integer('validation_shards', 16,
'Number of shards in validation TFRecord files.')
tf.app.flags.DEFINE_integer('num_threads', 8,
'Number of threads to preprocess the images.')
RANDOM_SEED = 180428
FLAGS = tf.app.flags.FLAGS
def _int64_feature(value):
"""Wrapper for inserting int64 features into Example proto."""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def _float_feature(value):
"""Wrapper for inserting float features into Example proto."""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def _bytes_list_feature(value):
"""Wrapper for inserting a list of bytes features into Example proto.
"""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
def _bytes_feature(value):
"""Wrapper for inserting bytes features into Example proto."""
if isinstance(value, six.string_types):
value = six.binary_type(value, encoding='utf-8')
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _convert_to_example(filename, image_name, image_buffer, bboxes, labels, labels_text,
difficult, truncated, height, width):
"""Build an Example proto for an example.
Args:
filename: string, path to an image file, e.g., '/path/to/example.JPG'
image_buffer: string, JPEG encoding of RGB image
bboxes: List of bounding boxes for each image
labels: List of labels for bounding box
labels_text: List of labels' name for bounding box
difficult: List of ints indicate the difficulty of that bounding box
truncated: List of ints indicate the truncation of that bounding box
height: integer, image height in pixels
width: integer, image width in pixels
Returns:
Example proto
"""
ymin = []
xmin = []
ymax = []
xmax = []
for b in bboxes:
assert len(b) == 4
# pylint: disable=expression-not-assigned
[l.append(point) for l, point in zip([ymin, xmin, ymax, xmax], b)]
# pylint: enable=expression-not-assigned
channels = 3
image_format = 'png'
example = tf.train.Example(features=tf.train.Features(feature={
'image/height': _int64_feature(height),
'image/width': _int64_feature(width),
'image/channels': _int64_feature(channels),
'image/shape': _int64_feature([height, width, channels]),
'image/object/bbox/xmin': _float_feature(xmin),
'image/object/bbox/xmax': _float_feature(xmax),
'image/object/bbox/ymin': _float_feature(ymin),
'image/object/bbox/ymax': _float_feature(ymax),
'image/object/bbox/label': _int64_feature(labels),
'image/object/bbox/label_text': _bytes_list_feature(labels_text),
'image/object/bbox/difficult': _int64_feature(difficult),
'image/object/bbox/truncated': _int64_feature(truncated),
'image/format': _bytes_feature(image_format),
'image/filename': _bytes_feature(image_name.encode('utf8')),
'image/encoded': _bytes_feature(image_buffer)}))
return example
class ImageCoder(object):
"""Helper class that provides TensorFlow image coding utilities."""
def __init__(self):
# Create a single Session to run all image coding calls.
self._sess = tf.Session()
# Initializes function that converts PNG to JPEG data.
self._png_data = tf.placeholder(dtype=tf.string)
image = tf.image.decode_png(self._png_data, channels=3)
self._png_to_jpeg = tf.image.encode_jpeg(image, format='rgb', quality=100)
# Initializes function that converts CMYK JPEG data to RGB JPEG data.
self._cmyk_data = tf.placeholder(dtype=tf.string)
image = tf.image.decode_jpeg(self._cmyk_data, channels=0)
self._cmyk_to_rgb = tf.image.encode_jpeg(image, format='rgb', quality=100)
# Initializes function that decodes RGB JPEG data.
self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3)
def png_to_jpeg(self, image_data):
return self._sess.run(self._png_to_jpeg,
feed_dict={self._png_data: image_data})
def cmyk_to_rgb(self, image_data):
return self._sess.run(self._cmyk_to_rgb,
feed_dict={self._cmyk_data: image_data})
def decode_jpeg(self, image_data):
image = self._sess.run(self._decode_jpeg,
feed_dict={self._decode_jpeg_data: image_data})
assert len(image.shape) == 3
assert image.shape[2] == 3
return image
def _process_image(filename, coder):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height: integer, image height in pixels.
width: integer, image width in pixels.
"""
# Read the image file.
with tf.gfile.FastGFile(filename, 'rb') as f:
image_data = f.read()
# Decode the RGB JPEG.
image_png = coder.png_to_jpeg(image_data)
image = coder.decode_jpeg(image_png)
# Check that image converted to RGB
assert len(image.shape) == 3
height = image.shape[0]
width = image.shape[1]
assert image.shape[2] == 3
return image_data, height, width
def _find_image_bounding_boxes(directory, cur_record):
"""Find the bounding boxes for a given image file.
Args:
directory: string; the path of all datas.
cur_record: list of strings; the first of which is the sub-directory of cur_record, the second is the image filename.
Returns:
bboxes: List of bounding boxes for each image.
labels: List of labels for bounding box.
labels_text: List of labels' name for bounding box.
difficult: List of ints indicate the difficulty of that bounding box.
truncated: List of ints indicate the truncation of that bounding box.
"""
print('****************',cur_record)
anna_file = os.path.join(directory, cur_record[0], 'Annotations', cur_record[1].replace('png', 'xml'))
tree = xml_tree.parse(anna_file)
root = tree.getroot()
# Image shape.
size = root.find('size')
shape = [int(size.find('height').text),
int(size.find('width').text),
int(size.find('depth').text)]
# Find annotations.
bboxes = []
labels = []
labels_text = []
difficult = []
truncated = []
for obj in root.findall('object'):
label = obj.find('name').text
labels.append(int(dataset_common.KITTI_LABELS[label][0]))
labels_text.append(label.encode('ascii'))
isdifficult = obj.find('difficult')
if isdifficult is not None:
difficult.append(int(isdifficult.text))
else:
difficult.append(0)
istruncated = obj.find('truncated')
if istruncated is not None:
truncated.append(int(istruncated.text))
else:
truncated.append(0)
bbox = obj.find('bndbox')
bboxes.append((float(bbox.find('ymin').text) / shape[0],
float(bbox.find('xmin').text) / shape[1],
float(bbox.find('ymax').text) / shape[0],
float(bbox.find('xmax').text) / shape[1]
))
return bboxes, labels, labels_text, difficult, truncated
def _process_image_files_batch(coder, thread_index, ranges, name, directory, all_records, num_shards):
"""Processes and saves list of images as TFRecord in 1 thread.
Args:
coder: instance of ImageCoder to provide TensorFlow image coding utils.
thread_index: integer, unique batch to run index is within [0, len(ranges)).
ranges: list of pairs of integers specifying ranges of each batches to
analyze in parallel.
name: string, unique identifier specifying the data set
directory: string; the path of all datas
all_records: list of string tuples; the first of each tuple is the sub-directory of the record, the second is the image filename.
num_shards: integer number of shards for this data set.
"""
# Each thread produces N shards where N = int(num_shards / num_threads).
# For instance, if num_shards = 128, and the num_threads = 2, then the first
# thread would produce shards [0, 64).
num_threads = len(ranges)
assert not num_shards % num_threads
num_shards_per_batch = int(num_shards / num_threads)
shard_ranges = np.linspace(ranges[thread_index][0],
ranges[thread_index][1],
num_shards_per_batch + 1).astype(int)
num_files_in_thread = ranges[thread_index][1] - ranges[thread_index][0]
counter = 0
for s in range(num_shards_per_batch):
# Generate a sharded version of the file name, e.g. 'train-00002-of-00010'
shard = thread_index * num_shards_per_batch + s
output_filename = '%s-%.5d-of-%.5d' % (name, shard, num_shards)
output_file = os.path.join(FLAGS.output_directory, output_filename)
writer = tf.python_io.TFRecordWriter(output_file)
shard_counter = 0
files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int)
for i in files_in_shard:
cur_record = all_records[i]
filename = os.path.join(directory, cur_record[0], 'JPEGImages', cur_record[1])
bboxes, labels, labels_text, difficult, truncated = _find_image_bounding_boxes(directory, cur_record)
image_buffer, height, width = _process_image(filename, coder)
example = _convert_to_example(filename, cur_record[1], image_buffer, bboxes, labels, labels_text,
difficult, truncated, height, width)
writer.write(example.SerializeToString())
shard_counter += 1
counter += 1
if not counter % 1000:
print('%s [thread %d]: Processed %d of %d images in thread batch.' %
(datetime.now(), thread_index, counter, num_files_in_thread))
sys.stdout.flush()
writer.close()
print('%s [thread %d]: Wrote %d images to %s' %
(datetime.now(), thread_index, shard_counter, output_file))
sys.stdout.flush()
shard_counter = 0
print('%s [thread %d]: Wrote %d images to %d shards.' %
(datetime.now(), thread_index, counter, num_files_in_thread))
sys.stdout.flush()
def _process_image_files(name, directory, all_records, num_shards):
"""Process and save list of images as TFRecord of Example protos.
Args:
name: string, unique identifier specifying the data set
directory: string; the path of all datas
all_records: list of string tuples; the first of each tuple is the sub-directory of the record, the second is the image filename.
num_shards: integer number of shards for this data set.
"""
# Break all images into batches with a [ranges[i][0], ranges[i][1]].
spacing = np.linspace(0, len(all_records), FLAGS.num_threads + 1).astype(np.int)
ranges = []
threads = []
for i in range(len(spacing) - 1):
ranges.append([spacing[i], spacing[i + 1]])
# Launch a thread for each batch.
print('Launching %d threads for spacings: %s' % (FLAGS.num_threads, ranges))
sys.stdout.flush()
# Create a mechanism for monitoring when all threads are finished.
coord = tf.train.Coordinator()
# Create a generic TensorFlow-based utility for converting all image codings.
coder = ImageCoder()
threads = []
for thread_index in range(len(ranges)):
args = (coder, thread_index, ranges, name, directory, all_records, num_shards)
t = threading.Thread(target=_process_image_files_batch, args=args)
t.start()
threads.append(t)
# Wait for all the threads to terminate.
coord.join(threads)
print('%s: Finished writing all %d images in data set.' %
(datetime.now(), len(all_records)))
sys.stdout.flush()
def _process_dataset(name, directory, all_splits, num_shards):
"""Process a complete data set and save it as a TFRecord.
Args:
name: string, unique identifier specifying the data set.
directory: string, root path to the data set.
all_splits: list of strings, sub-path to the data set.
num_shards: integer number of shards for this data set.
"""
all_records = []
for split in all_splits:
jpeg_file_path = os.path.join(directory, split, 'JPEGImages')
images = tf.gfile.ListDirectory(jpeg_file_path)
jpegs = [im_name for im_name in images if im_name.strip()[-3:]=='png']
all_records.extend(list(zip([split] * len(jpegs), jpegs)))
shuffled_index = list(range(len(all_records)))
random.seed(RANDOM_SEED)
random.shuffle(shuffled_index)
all_records = [all_records[i] for i in shuffled_index]
_process_image_files(name, directory, all_records, num_shards)
def parse_comma_list(args):
return [s.strip() for s in args.split(',')]
def main(unused_argv):
assert not FLAGS.train_shards % FLAGS.num_threads, (
'Please make the FLAGS.num_threads commensurate with FLAGS.train_shards')
assert not FLAGS.validation_shards % FLAGS.num_threads, (
'Please make the FLAGS.num_threads commensurate with '
'FLAGS.validation_shards')
print('Saving results to %s' % FLAGS.output_directory)
# Run it!
_process_dataset('val', FLAGS.dataset_directory, parse_comma_list(FLAGS.validation_splits), FLAGS.validation_shards)
_process_dataset('train', FLAGS.dataset_directory, parse_comma_list(FLAGS.train_splits), FLAGS.train_shards)
if __name__ == '__main__':
tf.app.run()
| 39.31738
| 133
| 0.681466
|
192cbf6ffd8a42ff4c9affe89bfd85fe3e425d81
| 13,338
|
py
|
Python
|
devel/_setup_util.py
|
shang-hl/ROS-NUS_FYP
|
92aff3f8ad0beebb27f8c29a942108aac0172f58
|
[
"MIT"
] | null | null | null |
devel/_setup_util.py
|
shang-hl/ROS-NUS_FYP
|
92aff3f8ad0beebb27f8c29a942108aac0172f58
|
[
"MIT"
] | null | null | null |
devel/_setup_util.py
|
shang-hl/ROS-NUS_FYP
|
92aff3f8ad0beebb27f8c29a942108aac0172f58
|
[
"MIT"
] | null | null | null |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""This file generates shell code for the setup.SHELL scripts to set environment variables."""
from __future__ import print_function
import argparse
import copy
import errno
import os
import platform
import sys
CATKIN_MARKER_FILE = '.catkin'
system = platform.system()
IS_DARWIN = (system == 'Darwin')
IS_WINDOWS = (system == 'Windows')
PATH_TO_ADD_SUFFIX = ['bin']
if IS_WINDOWS:
# while catkin recommends putting dll's into bin, 3rd party packages often put dll's into lib
# since Windows finds dll's via the PATH variable, prepend it with path to lib
PATH_TO_ADD_SUFFIX.extend([['lib', os.path.join('lib', 'aarch64-linux-gnu')]])
# subfolder of workspace prepended to CMAKE_PREFIX_PATH
ENV_VAR_SUBFOLDERS = {
'CMAKE_PREFIX_PATH': '',
'LD_LIBRARY_PATH' if not IS_DARWIN else 'DYLD_LIBRARY_PATH': ['lib', os.path.join('lib', 'aarch64-linux-gnu')],
'PATH': PATH_TO_ADD_SUFFIX,
'PKG_CONFIG_PATH': [os.path.join('lib', 'pkgconfig'), os.path.join('lib', 'aarch64-linux-gnu', 'pkgconfig')],
'PYTHONPATH': 'lib/python3/dist-packages',
}
def rollback_env_variables(environ, env_var_subfolders):
"""
Generate shell code to reset environment variables.
by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH.
This does not cover modifications performed by environment hooks.
"""
lines = []
unmodified_environ = copy.copy(environ)
for key in sorted(env_var_subfolders.keys()):
subfolders = env_var_subfolders[key]
if not isinstance(subfolders, list):
subfolders = [subfolders]
value = _rollback_env_variable(unmodified_environ, key, subfolders)
if value is not None:
environ[key] = value
lines.append(assignment(key, value))
if lines:
lines.insert(0, comment('reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH'))
return lines
def _rollback_env_variable(environ, name, subfolders):
"""
For each catkin workspace in CMAKE_PREFIX_PATH remove the first entry from env[NAME] matching workspace + subfolder.
:param subfolders: list of str '' or subfoldername that may start with '/'
:returns: the updated value of the environment variable.
"""
value = environ[name] if name in environ else ''
env_paths = [path for path in value.split(os.pathsep) if path]
value_modified = False
for subfolder in subfolders:
if subfolder:
if subfolder.startswith(os.path.sep) or (os.path.altsep and subfolder.startswith(os.path.altsep)):
subfolder = subfolder[1:]
if subfolder.endswith(os.path.sep) or (os.path.altsep and subfolder.endswith(os.path.altsep)):
subfolder = subfolder[:-1]
for ws_path in _get_workspaces(environ, include_fuerte=True, include_non_existing=True):
path_to_find = os.path.join(ws_path, subfolder) if subfolder else ws_path
path_to_remove = None
for env_path in env_paths:
env_path_clean = env_path[:-1] if env_path and env_path[-1] in [os.path.sep, os.path.altsep] else env_path
if env_path_clean == path_to_find:
path_to_remove = env_path
break
if path_to_remove:
env_paths.remove(path_to_remove)
value_modified = True
new_value = os.pathsep.join(env_paths)
return new_value if value_modified else None
def _get_workspaces(environ, include_fuerte=False, include_non_existing=False):
"""
Based on CMAKE_PREFIX_PATH return all catkin workspaces.
:param include_fuerte: The flag if paths starting with '/opt/ros/fuerte' should be considered workspaces, ``bool``
"""
# get all cmake prefix paths
env_name = 'CMAKE_PREFIX_PATH'
value = environ[env_name] if env_name in environ else ''
paths = [path for path in value.split(os.pathsep) if path]
# remove non-workspace paths
workspaces = [path for path in paths if os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE)) or (include_fuerte and path.startswith('/opt/ros/fuerte')) or (include_non_existing and not os.path.exists(path))]
return workspaces
def prepend_env_variables(environ, env_var_subfolders, workspaces):
"""Generate shell code to prepend environment variables for the all workspaces."""
lines = []
lines.append(comment('prepend folders of workspaces to environment variables'))
paths = [path for path in workspaces.split(os.pathsep) if path]
prefix = _prefix_env_variable(environ, 'CMAKE_PREFIX_PATH', paths, '')
lines.append(prepend(environ, 'CMAKE_PREFIX_PATH', prefix))
for key in sorted(key for key in env_var_subfolders.keys() if key != 'CMAKE_PREFIX_PATH'):
subfolder = env_var_subfolders[key]
prefix = _prefix_env_variable(environ, key, paths, subfolder)
lines.append(prepend(environ, key, prefix))
return lines
def _prefix_env_variable(environ, name, paths, subfolders):
"""
Return the prefix to prepend to the environment variable NAME.
Adding any path in NEW_PATHS_STR without creating duplicate or empty items.
"""
value = environ[name] if name in environ else ''
environ_paths = [path for path in value.split(os.pathsep) if path]
checked_paths = []
for path in paths:
if not isinstance(subfolders, list):
subfolders = [subfolders]
for subfolder in subfolders:
path_tmp = path
if subfolder:
path_tmp = os.path.join(path_tmp, subfolder)
# skip nonexistent paths
if not os.path.exists(path_tmp):
continue
# exclude any path already in env and any path we already added
if path_tmp not in environ_paths and path_tmp not in checked_paths:
checked_paths.append(path_tmp)
prefix_str = os.pathsep.join(checked_paths)
if prefix_str != '' and environ_paths:
prefix_str += os.pathsep
return prefix_str
def assignment(key, value):
if not IS_WINDOWS:
return 'export %s="%s"' % (key, value)
else:
return 'set %s=%s' % (key, value)
def comment(msg):
if not IS_WINDOWS:
return '# %s' % msg
else:
return 'REM %s' % msg
def prepend(environ, key, prefix):
if key not in environ or not environ[key]:
return assignment(key, prefix)
if not IS_WINDOWS:
return 'export %s="%s$%s"' % (key, prefix, key)
else:
return 'set %s=%s%%%s%%' % (key, prefix, key)
def find_env_hooks(environ, cmake_prefix_path):
"""Generate shell code with found environment hooks for the all workspaces."""
lines = []
lines.append(comment('found environment hooks in workspaces'))
generic_env_hooks = []
generic_env_hooks_workspace = []
specific_env_hooks = []
specific_env_hooks_workspace = []
generic_env_hooks_by_filename = {}
specific_env_hooks_by_filename = {}
generic_env_hook_ext = 'bat' if IS_WINDOWS else 'sh'
specific_env_hook_ext = environ['CATKIN_SHELL'] if not IS_WINDOWS and 'CATKIN_SHELL' in environ and environ['CATKIN_SHELL'] else None
# remove non-workspace paths
workspaces = [path for path in cmake_prefix_path.split(os.pathsep) if path and os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE))]
for workspace in reversed(workspaces):
env_hook_dir = os.path.join(workspace, 'etc', 'catkin', 'profile.d')
if os.path.isdir(env_hook_dir):
for filename in sorted(os.listdir(env_hook_dir)):
if filename.endswith('.%s' % generic_env_hook_ext):
# remove previous env hook with same name if present
if filename in generic_env_hooks_by_filename:
i = generic_env_hooks.index(generic_env_hooks_by_filename[filename])
generic_env_hooks.pop(i)
generic_env_hooks_workspace.pop(i)
# append env hook
generic_env_hooks.append(os.path.join(env_hook_dir, filename))
generic_env_hooks_workspace.append(workspace)
generic_env_hooks_by_filename[filename] = generic_env_hooks[-1]
elif specific_env_hook_ext is not None and filename.endswith('.%s' % specific_env_hook_ext):
# remove previous env hook with same name if present
if filename in specific_env_hooks_by_filename:
i = specific_env_hooks.index(specific_env_hooks_by_filename[filename])
specific_env_hooks.pop(i)
specific_env_hooks_workspace.pop(i)
# append env hook
specific_env_hooks.append(os.path.join(env_hook_dir, filename))
specific_env_hooks_workspace.append(workspace)
specific_env_hooks_by_filename[filename] = specific_env_hooks[-1]
env_hooks = generic_env_hooks + specific_env_hooks
env_hooks_workspace = generic_env_hooks_workspace + specific_env_hooks_workspace
count = len(env_hooks)
lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_COUNT', count))
for i in range(count):
lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d' % i, env_hooks[i]))
lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d_WORKSPACE' % i, env_hooks_workspace[i]))
return lines
def _parse_arguments(args=None):
parser = argparse.ArgumentParser(description='Generates code blocks for the setup.SHELL script.')
parser.add_argument('--extend', action='store_true', help='Skip unsetting previous environment variables to extend context')
parser.add_argument('--local', action='store_true', help='Only consider this prefix path and ignore other prefix path in the environment')
return parser.parse_known_args(args=args)[0]
if __name__ == '__main__':
try:
try:
args = _parse_arguments()
except Exception as e:
print(e, file=sys.stderr)
sys.exit(1)
if not args.local:
# environment at generation time
CMAKE_PREFIX_PATH = r'/home/user/FYP_431H/devel;/opt/ros/noetic'.split(';')
else:
# don't consider any other prefix path than this one
CMAKE_PREFIX_PATH = []
# prepend current workspace if not already part of CPP
base_path = os.path.dirname(__file__)
# CMAKE_PREFIX_PATH uses forward slash on all platforms, but __file__ is platform dependent
# base_path on Windows contains backward slashes, need to be converted to forward slashes before comparison
if os.path.sep != '/':
base_path = base_path.replace(os.path.sep, '/')
if base_path not in CMAKE_PREFIX_PATH:
CMAKE_PREFIX_PATH.insert(0, base_path)
CMAKE_PREFIX_PATH = os.pathsep.join(CMAKE_PREFIX_PATH)
environ = dict(os.environ)
lines = []
if not args.extend:
lines += rollback_env_variables(environ, ENV_VAR_SUBFOLDERS)
lines += prepend_env_variables(environ, ENV_VAR_SUBFOLDERS, CMAKE_PREFIX_PATH)
lines += find_env_hooks(environ, CMAKE_PREFIX_PATH)
print('\n'.join(lines))
# need to explicitly flush the output
sys.stdout.flush()
except IOError as e:
# and catch potential "broken pipe" if stdout is not writable
# which can happen when piping the output to a file but the disk is full
if e.errno == errno.EPIPE:
print(e, file=sys.stderr)
sys.exit(2)
raise
sys.exit(0)
| 43.731148
| 213
| 0.682336
|
d455c827f283b40066dc88d9a9e638feeae71a38
| 5,952
|
py
|
Python
|
utilities/copy_acd_bcd_files.py
|
slochower/host-guest-benchmarks
|
c398b499fe6dbae39523278946c0e25eb78d6d66
|
[
"MIT"
] | null | null | null |
utilities/copy_acd_bcd_files.py
|
slochower/host-guest-benchmarks
|
c398b499fe6dbae39523278946c0e25eb78d6d66
|
[
"MIT"
] | 8
|
2019-07-05T17:55:27.000Z
|
2022-03-21T18:59:50.000Z
|
utilities/copy_acd_bcd_files.py
|
slochower/host-guest-benchmarks
|
c398b499fe6dbae39523278946c0e25eb78d6d66
|
[
"MIT"
] | 1
|
2020-05-05T22:51:21.000Z
|
2020-05-05T22:51:21.000Z
|
import os
import subprocess as sp
from pathlib import Path
import parmed as pmd
systems = """./a-bam-p
./a-bam-s
./a-but-p
./a-but-s
./a-cbu-p
./a-chp-p
./a-cbu-s
./a-chp-s
./a-cpe-p
./a-coc-p
./a-coc-s
./a-cpe-s
./a-hep-p
./a-ham-s
./a-ham-p
./a-hep-s
./a-hp6-p
./a-hex-p
./a-hex-s
./a-hp6-s
./a-hx2-p
./a-hpa-s
./a-hpa-p
./a-hx2-s
./a-mba-p
./a-hx3-s
./a-hx3-p
./a-mba-s
./a-mhp-p
./a-mha-p
./a-mha-s
./a-mhp-s
./a-nmh-p
./a-nmb-p
./a-nmb-s
./a-nmh-s
./a-oct-p
./a-oam-p
./a-oam-s
./a-oct-s
./a-pnt-p
./a-pam-p
./a-pam-s
./a-pnt-s
./b-ben-s
./b-ben-p
./b-cbu-p
./b-cbu-s
./b-chp-s
./b-chp-p
./b-coc-s
./b-coc-p
./b-cpe-s
./b-cpe-p
./b-ham-s
./b-ham-p
./b-hep-s
./b-hep-p
./b-hex-p
./b-hex-s
./b-m4c-s
./b-m4c-p
./b-m4t-p
./b-m4t-s
./b-mch-s
./b-mha-s
./b-mha-p
./b-mch-p
./b-mo3-s
./b-mo4-p
./b-mo4-s
./b-mo3-p
./b-mp3-s
./b-mp4-s
./b-mp4-p
./b-mp3-p
./b-oam-s
./b-pb3-s
./b-pb3-p
./b-oam-p
./b-pb4-s
./b-pha-s
./b-pb4-p
./b-pha-p
./b-pnt-s
./b-pnt-p"""
systems = systems.split("\n")
systems = [i[2:] for i in systems]
systems = [i for i in systems if "xxxx" not in i]
def write_pdb(output_file, directory_path):
"""
Save PDB of the host-guest complex with CONECT records.
"""
input = \
f"""
parm smirnoff.prmtop
trajin smirnoff.inpcrd
strip :DUM,:Na+,:Cl-,:WAT
trajout {output_file} conect
run
quit
"""
with open(directory_path.joinpath("tmp.in"), "w") as f:
f.write(input)
command = \
f"""cpptraj -i tmp.in"""
p = sp.Popen(command, cwd=directory_path, shell=True)
p.communicate()
os.remove(directory_path.joinpath("tmp.in"))
def write_mol2(ligand_residue, output_file, directory_path):
"""
Save MOL2 of the guest molecule with SYBYL/Tripos atom types.
"""
# 1. Use `cpptraj` to extract just the ligand.
input = \
f"""
parm smirnoff.prmtop
trajin smirnoff.inpcrd
strip :MGO,:Na+,:Cl-,:WAT,:DUM
trajout {ligand_residue}.tmp.mol2
run
quit
"""
with open(directory_path.joinpath("tmp.in"), "w") as f:
f.write(input)
command = \
f"""cpptraj -i tmp.in"""
p = sp.Popen(command, cwd=directory_path, shell=True)
p.communicate()
os.remove(directory_path.joinpath("tmp.in"))
# 2. Use `antechamber` to make sure we get SYBYL atom types.
command = \
f""" antechamber -i {ligand_residue}.tmp.mol2 -fi mol2 -o {output_file} -fo mol2 -at sybyl -dr no
"""
p = sp.Popen(command, cwd=directory_path, shell=True)
p.communicate()
def grep_anchor_atoms(path, system):
"""
Create a dictionary of anchor atoms from existing files.
"""
pdb = path.joinpath(system, "bgbg-tip3p", f"{system}.pdb")
with open(pdb, "r") as file:
remark = file.readline()
remark = remark.rstrip()
remark = remark.split(" ")
prmtop = pmd.load_file(
str(path.joinpath(system, "smirnoff", "smirnoff.prmtop"))
)
dummy_residues = prmtop[":DUM"].residues
host_residue = prmtop[":MGO"].residues[0].number + 1
guest_residue = prmtop[f":{system.split('-')[1].upper()}"].residues[0].number + 1
anchor_atoms = {
"D1": f":{dummy_residues[0].number + 1}",
"D2": f":{dummy_residues[1].number + 1}",
"D3": f":{dummy_residues[2].number + 1}",
"H1": f":{host_residue}@{remark[2].split('@')[1]}",
"H2": f":{host_residue + 2}@{remark[3].split('@')[1]}",
"H3": f":{host_residue + 4}@{remark[4].split('@')[1]}",
"G1": f":{guest_residue}@{remark[5].split('@')[1]}",
"G2": f":{guest_residue}@{remark[6].split('@')[1]}",
}
return anchor_atoms
def write_guest_yaml_header(template_file, anchor_atoms, output_file):
"""
Write a `guest.yaml` based on a template, replacing the anchor atoms.
"""
string = [
f"name: {guest}" + "\n",
f"structure: {guest}.mol2" + "\n",
f"complex: {host}-{guest}.pdb" + "\n",
"net_charge: 0" + "\n",
"aliases:" + "\n",
f" - D1: {anchor_atoms['D1']}" + "\n",
f" - D2: {anchor_atoms['D2']}" + "\n",
f" - D3: {anchor_atoms['D3']}" + "\n",
f" - G1: {anchor_atoms['G1']}" + "\n",
f" - G2: {anchor_atoms['G2']}" + "\n",
]
with open(template_file, "r") as file:
guest_yaml = file.readlines()
for line_number in range(10):
guest_yaml[line_number] = string[line_number]
with open(output_file, "w") as file:
for line in guest_yaml:
file.write(line)
for system in systems:
print(system)
# Inputs
host, guest, orientation = system.split("-")
root_path = Path("/home/davids4/gpfs/smirnoff-host-guest-simulations-data/systems")
directory_path = root_path.joinpath(system).joinpath("smirnoff")
write_pdb(output_file=f"{system}.pdb",
directory_path=directory_path)
write_mol2(ligand_residue=guest,
output_file=f"{guest}.mol2",
directory_path=directory_path)
# Outputs for `taproom`
taproom_root = Path("/home/davids4/data/projects/host-guest-benchmarks/taproom/systems")
taproom_host = taproom_root.joinpath("acd") if "a" in host else taproom_root.joinpath("bcd")
taproom_directory = taproom_host.joinpath(guest)
if not os.path.exists(taproom_directory):
os.mkdir(taproom_directory)
if not os.path.exists(taproom_directory.joinpath("guest.mol2")):
sp.call(f"cp {directory_path.joinpath(guest + '.mol2')} {taproom_directory}/", shell=True)
# if not os.path.exists(taproom_directory.joinpath("guest.yaml")):
if 1:
anchor_atoms = grep_anchor_atoms(root_path, system)
write_guest_yaml_header(template_file=taproom_host.joinpath("hex").joinpath("guest.yaml"),
anchor_atoms=anchor_atoms,
output_file=taproom_directory.joinpath("guest.yaml"))
sp.call(f"cp {directory_path.joinpath(system + '.pdb')} {taproom_directory}/", shell=True)
| 24.293878
| 101
| 0.59711
|
5a3f3a3a3ebb96d3fca6cb7e897bebc49823db66
| 1,748
|
py
|
Python
|
KFM_train.py
|
Collapsar-G/Recommended-system
|
687cedd8d8fa7354363bf7d2ee482bb172abd6a2
|
[
"Apache-2.0"
] | null | null | null |
KFM_train.py
|
Collapsar-G/Recommended-system
|
687cedd8d8fa7354363bf7d2ee482bb172abd6a2
|
[
"Apache-2.0"
] | null | null | null |
KFM_train.py
|
Collapsar-G/Recommended-system
|
687cedd8d8fa7354363bf7d2ee482bb172abd6a2
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@Author : Collapsar-G
@License : (C) Copyright 2021-*
@Contact : gjf840513468@gmail.com
@File : $train.py
@Time : $2021.4.21 $8:50
@Desc : KFM模型训练入口
"""
import os
import time as time
import torch
from dataset import data_load
from miscc.config import cfg
from models.KFM import train
if cfg.GPU_ID != "":
torch.cuda.set_device(cfg.GPU_ID)
def KFM(control=cfg.KFM.control):
times = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
path = "./output/KFM/%s" % times
if not os.path.exists(path):
os.makedirs(path)
M, N, count = data_load()
pred = train(M, N, control, count, path)
# pred_data = pred.cpu().detach().numpy()
#
# np.savetxt("%s/%s_sparse_pred_data.txt" % (path, cfg.KFM.DATA_TYPE), pred_data)
# print("保存训练结果到:%s/%s_sparse_pred_data_all.txt" % (path, cfg.KFM.DATA_TYPE))
#
# print('-' * 10)
# print('-' * 10)
#
# pred_M, test_M, N_test, result = data_loat_test(pred_data)
#
# file_write_obj = open("%s/%s_sparse_pred_data_test.txt" % (path, cfg.KFM.DATA_TYPE), 'w')
# for var in result:
# file_write_obj.writelines(var[0] + "," + var[1] + "," + str(var[2]))
# # print(var)
# file_write_obj.write('\n')
# file_write_obj.close()
#
# # result_data = pd.DataFrame(data=result)
# # np.savetxt("%s/%s_sparse_pred_data_test.txt" % (path, cfg.KFM.DATA_TYPE), result)
# # result_data.to_csv("%s/%s_sparse_pred_data_test.txt" % (path, cfg.KFM.DATA_TYPE))
# print("保存测试结果到:%s/%s_sparse_pred_data_test.txt" % (path, cfg.KFM.DATA_TYPE))
# test(pred_M, test_M, N_test, path)
return
if __name__ == "__main__":
KFM()
| 24.971429
| 95
| 0.616133
|
28b13a6c7d9f536811a17b4e5f4a65a8296434b7
| 1,048
|
py
|
Python
|
lib/surface/compute/disks/__init__.py
|
bshaffer/google-cloud-sdk
|
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
|
[
"Apache-2.0"
] | null | null | null |
lib/surface/compute/disks/__init__.py
|
bshaffer/google-cloud-sdk
|
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
|
[
"Apache-2.0"
] | null | null | null |
lib/surface/compute/disks/__init__.py
|
bshaffer/google-cloud-sdk
|
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*- #
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Commands for reading and manipulating disks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Disks(base.Group):
"""Read and manipulate Google Compute Engine disks."""
Disks.category = base.COMPUTE_DISKS_CATEGORY
Disks.detailed_help = {
'brief': 'Read and manipulate Google Compute Engine disks',
}
| 31.757576
| 74
| 0.764313
|
0dc6d990a7747c25cc2dbb86fee8e1d0e67a9208
| 1,297
|
py
|
Python
|
test/blueprints/plant/conftest.py
|
keithly/flower-bed-designer
|
598cc14d60f822b91557df2328844da99b8040b7
|
[
"MIT"
] | null | null | null |
test/blueprints/plant/conftest.py
|
keithly/flower-bed-designer
|
598cc14d60f822b91557df2328844da99b8040b7
|
[
"MIT"
] | null | null | null |
test/blueprints/plant/conftest.py
|
keithly/flower-bed-designer
|
598cc14d60f822b91557df2328844da99b8040b7
|
[
"MIT"
] | null | null | null |
import pytest
@pytest.fixture
def test_plants_data():
return [
{
'plant_id': 1,
'common_name': 'common milkweed',
'genus': 'asclepias',
'species': 'syriaca',
'family': 'asclepiadaceae',
'rhizomatous': True,
'garden_friendly': False
},
{
'plant_id': 2,
'common_name': 'purple milkweed',
'genus': 'asclepias',
'species': 'purpurascens',
'family': 'asclepiadaceae',
'rhizomatous': True,
'garden_friendly': True
},
{
'plant_id': 3,
'common_name': 'heart-leaved aster',
'genus': 'symphyotrichum',
'species': 'cordifolium',
'family': 'asteraceae',
'rhizomatous': False,
'garden_friendly': True
}
]
@pytest.fixture
def test_cu_plant_data():
return {
'common_name': 'common milkweed',
'genus': 'asclepias',
'species': 'syriaca',
'family': 'asclepiadaceae',
'rhizomatous': True,
'garden_friendly': False
}
@pytest.fixture
def test_get_plant_data(test_cu_plant_data):
test_cu_plant_data['plant_id'] = 1
return test_cu_plant_data
| 24.471698
| 48
| 0.511951
|
3c535fab8ad79c9a4b76652917aba6dc3bdc7f29
| 4,201
|
py
|
Python
|
index.py
|
scottmetoyer/nzb-indexer
|
177cd3cb54f385d7af5df9668f9c6793147cd092
|
[
"MIT"
] | 8
|
2015-01-17T06:16:08.000Z
|
2019-12-04T10:49:45.000Z
|
index.py
|
scottmetoyer/nzb-indexer
|
177cd3cb54f385d7af5df9668f9c6793147cd092
|
[
"MIT"
] | null | null | null |
index.py
|
scottmetoyer/nzb-indexer
|
177cd3cb54f385d7af5df9668f9c6793147cd092
|
[
"MIT"
] | 2
|
2016-10-26T10:21:07.000Z
|
2019-12-04T10:49:46.000Z
|
# index.py
# Scott Metoyer, 2013
# Retrieves a list of new NZB's from the newsgroups specified in a config file
from nntplib import *
from pymongo import MongoClient
import string
import datetime
import time
try:
from config_local import config as config
except ImportError:
from config_default import config as config
mongo_connection = MongoClient('localhost', 27017)
db = mongo_connection.nzb_database
newsgroups = db.newsgroup_collection
articles = db.article_collection
def connect():
print('Connecting to ' + config["usenet_server"] + '...')
server = NNTP(config["usenet_server"], config["usenet_port"], config["usenet_username"], config["usenet_password"])
return server
def fetch_articles(group, start_index):
article_count = 0
server = connect()
print('Reading from group ' + group + '...')
resp, count, first, last, name = server.group(group)
print('Getting a list of nzb files in ' + group + '...')
if start_index < int(first):
start_index = int(first)
current_index = int(start_index)
last_index = int(last)
chunk_size = 10000
# Some sanity checking on the maximum number to process. If it's too many, we only grab the newest.
if last_index - current_index > config["max_run_size"]:
current_index = last_index - config["max_run_size"]
while (current_index < last_index):
if (current_index + chunk_size >= last_index):
chunk_size = last_index - current_index
try:
resp, items = server.xover(str(current_index), str(current_index + chunk_size))
except:
print("Error grabbing articles. Attempting to reconnect...")
server = connect()
server.group(group)
resp, items = server.xover(str(current_index), str(current_index + chunk_size))
print("Reconnected.")
for number, subject, poster, date, id, references, size, lines in items:
if '.nzb' in subject.lower():
# Check make sure this article doesn't exist in the database already
if articles.find_one({"message-id": id}) == None:
article = {"message-id": id,
"group": group,
"article-number": number,
"subject": subject,
"date": date}
try:
articles.insert(article)
print(group + "," + number + ": " + subject)
article_count += 1
except:
print("Error inserting article. Continuing...")
else:
print("Article " + id + " already exists in the database. Continuing...")
current_index += chunk_size
server.quit()
print("Articles added: " + str(article_count))
return current_index
def get_group(group_name):
group = newsgroups.find_one({"name": group_name})
if group == None:
group = {"name": group_name,
"last_scan": datetime.datetime.now(),
"last_article": 0}
newsgroups.insert(group)
return group
def update_group(group_name, last_article):
# Make sure the group exists
get_group(group_name)
newsgroups.update({"name": group_name},
{"$set": {
"last_scan": datetime.datetime.now(),
"last_article": last_article
}
})
# Grab groups to scan from configuration file
f = open("groups.txt", "r")
groups = (line.strip() for line in f.readlines() if len(line.strip()))
f.close()
print("Starting run...")
start = time.time()
for group_name in groups:
group_name = group_name
settings = get_group(group_name)
last_index = fetch_articles(group_name, settings["last_article"] + 1)
update_group(group_name, last_index)
end = time.time()
elapsed = end - start
print("Execution time: " + str(elapsed / 60) + " minutes")
| 35.008333
| 119
| 0.577482
|
fd20639d81f778e7905249f8f2bce96e731e762c
| 9,488
|
py
|
Python
|
code/viz.py
|
minji7608/asst4-s20
|
e901ff749799240eb30dba52ef6721cbcf414d87
|
[
"MIT"
] | null | null | null |
code/viz.py
|
minji7608/asst4-s20
|
e901ff749799240eb30dba52ef6721cbcf414d87
|
[
"MIT"
] | null | null | null |
code/viz.py
|
minji7608/asst4-s20
|
e901ff749799240eb30dba52ef6721cbcf414d87
|
[
"MIT"
] | null | null | null |
# Visualization tools for graphrat simulator
# For printing ASCII representation of maze
# And for showing as a heat map
import math
import sys
import curses
import time
import datetime
# Some installations don't support Tkinter and PIL libraries.
# Import them only if needed
specialImported = False
def importSpecial():
global specialImported, Tkinter, Image, ImageDraw
if not specialImported:
import Tkinter
from PIL import Image, ImageDraw
specialImported = True
class VizMode:
nothing, ascii, heatmap, both, error = range(5)
def parse(self, name):
if len(name) != 1:
return self.error
elif name == 'n':
return self.nothing
elif name == 'a':
return self.ascii
elif name == 'h':
return self.heatmap
elif name == 'b':
return self.both
else:
return self.error
def doHeatMap(self, v):
return v in [self.heatmap, self.both]
def doASCII(self, v):
return v in [self.ascii, self.both]
class Formatter:
width = 0
height = 0
digits = 1
separator = ""
file = None
x = 0
y = 0
stdscr = None
tlast = None
display = None
def __init__(self, width, height, maxval, fname = "", viz = VizMode.both):
self.width = width
self.height = height
self.digits = int(math.ceil(math.log10(maxval+1)))
# Pattern that separates lines
s = "-" * self.digits + "+"
self.separator = "+" + s * self.width
self.file = None
self.stdscr = None
self.display = None
vm = VizMode()
if fname == "":
self.file = sys.stdout
else:
try:
self.file = open(fname, "w")
except:
self.file = None
print "Could not open file '%s'" % fname
return
if vm.doASCII(viz):
self.stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
self.tlast = datetime.datetime.now()
if vm.doHeatMap(viz):
self.display = Display(width = self.width, height = self.height, maxval = maxval)
self.reset()
def reset(self):
self.x = 0
self.y = 0
def finish(self, fname = ""):
if self.file is not None and self.file not in [sys.stdout, sys.stderr]:
self.file.close()
self.file = None
if fname != "" and self.display is not None:
self.display.capture(fname)
self.finishDynamic(wait = False)
# Complete dynamic part of visualization
def finishDynamic(self, wait = False):
if self.stdscr is not None:
if wait:
self.printLine("[Hit any key to exit]")
self.stdscr.getch()
curses.nocbreak()
curses.echo()
curses.endwin()
self.stdscr = None
def printLine(self, s, addReturn = True):
ps = s
ss = s
if s[-1] == '\n':
ss = s[:-1]
addReturn = True
else:
ps = ps + '\n' if addReturn else ps
if self.stdscr is not None:
self.stdscr.addstr(self.y, self.x, ss)
elif (self.file is not None) and (self.display is None):
self.file.write(ps)
if addReturn:
self.x = 0
self.y += 1
def show(self, populations, period = 0.0):
self.printLine(self.separator)
for row in range(self.height):
rstart = row * self.width
rvals = populations[rstart:rstart+self.width]
line = "|"
for v in rvals:
sdig = "" if v == 0 else"%d" % v
slen = self.digits - len(sdig)
llen = (slen+1)/2
rlen = slen/2
line += " " * llen
line += sdig
line += " " * rlen
line += "|"
self.printLine(line)
self.printLine(self.separator)
if self.stdscr is not None:
self.stdscr.refresh()
if period > 0:
if self.tlast is not None:
tnow = datetime.datetime.now()
d = tnow - self.tlast
dsecs = 24 * 3600 * d.days + d.seconds + 1e-6 * d.microseconds
secs = period - dsecs
if secs > 0:
time.sleep(secs)
if self.display:
self.display.setColors(populations)
self.tlast = datetime.datetime.now()
# For generating heatmap
def cstring(c):
fields = [("%.2x" % int(255*x)) for x in c]
return "#" + "".join(fields)
class Colors:
black = (0.0, 0.0, 0.0)
blue = (0.0, 0.0, 1.0)
green = (0.0, 1.0, 0.0)
cyan = (0.0, 1.0, 1.0)
red = (1.0, 0.0, 0.0)
magenta = (1.0, 0.0, 1.0)
yellow = (1.0, 1.0, 0.0)
white = (1.0, 1.0, 1.0)
lightred = (1.0, 0.5, 0.5)
class HeatMap:
maxval = 1
logmax = 0
colorList = (Colors.magenta, Colors.blue, Colors.cyan, Colors.green, Colors.yellow, Colors.red)
weightList = (0.2, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)
# Below splitVal, interpolate over color range.
# Above, interpolate between final two colors
splitVal = 0.5
def __init__(self, maxval = 100, avgval = 10):
self.scaleList = []
for i in range(len(self.colorList)):
self.scaleList.append(map(lambda (c): c * self.weightList[i], self.colorList[i]))
self.maxval = maxval
self.logmax = math.log(self.maxval+1)
self.splitval = math.log(2.0 * avgval)/self.logmax
# Perform interpolation of number in range [0, 1.0) to get color
def interpolate(self, x):
x = min(x, 1.0)
x = max(x, 0.0)
upper = x >= self.splitVal
if upper:
lcolor = self.scaleList[-2]
rcolor = self.scaleList[-1]
point = (x - self.splitVal) / (1.0 - self.splitVal)
else:
x = x / self.splitVal
segs = len(self.scaleList) - 2
sx = x * segs
interval = int(sx)
point = sx - interval
lcolor = self.scaleList[interval]
rcolor = self.scaleList[interval+1]
color = [rcolor[idx] * point + lcolor[idx] * (1-point) for idx in range(3)]
return cstring(color)
def genColor(self, val):
if val == 0:
return cstring(Colors.black)
scale = math.log(val) / self.logmax
return self.interpolate(scale)
def genColors(self, vlist):
clist = [self.genColor(v) for v in vlist]
return clist
class Display:
width = 20
height = 15
squareSize = 8
display = None # TK Window
frame = None # Frame within window
canvas = None # Canvas within frame
squares = [] # Set of rectangles, k*k total
colorList = [] # Most recent set of colors
hmap = None
def __init__(self, width, height, maxdim = 800, maxval = 100):
importSpecial()
self.width = width
self.height = height
nodeCount = width * height
loadFactor = maxval / nodeCount
self.squareSize = maxdim / max(self.width, self.height)
self.display = Tkinter.Tk()
self.display.title('GraphRat Simulation of %d X %d maze (load factor = %d)' % (width, height, loadFactor))
self.frame = Tkinter.Frame(self.display)
self.frame.pack(fill=Tkinter.BOTH)
self.canvas = Tkinter.Canvas(self.frame, width = width * self.squareSize, height = height * self.squareSize)
self.canvas.pack(fill=Tkinter.BOTH)
self.squares = []
for r in range(0, self.height):
for c in range(0, self.width):
(x, y) = self.xyPos(r, c)
sq = self.canvas.create_rectangle(x, y, x+self.squareSize, y+self.squareSize, width = 0,
fill = cstring(Colors.black))
self.squares.append(sq)
self.hmap = HeatMap(maxval = maxval, avgval = maxval/nodeCount)
self.update()
def update(self):
self.canvas.update()
def xyPos(self, r, c):
x = self.squareSize * c
y = self.squareSize * r
return (x, y)
def rowCol(self, idx):
r = idx // self.width
c = idx % self.width
return (r, c)
def colorSquare(self, idx, color):
if idx >= 0 and idx < len(self.squares):
square = self.squares[idx]
self.canvas.itemconfig(square, fill = color)
# Set colors based on counts for each square
def setColors(self, vlist = []):
clist = self.hmap.genColors(vlist)
self.colorList = clist
for idx in range(len(vlist)):
self.colorSquare(idx, clist[idx])
self.update()
def capture(self, fname):
img = Image.new('RGB', (self.width * self.squareSize, self.height * self.squareSize), "black")
dimg = ImageDraw.Draw(img)
for idx in range(len(self.colorList)):
r, c = self.rowCol(idx)
x, y = self.xyPos(r, c)
dimg.rectangle((x, y, x + self.squareSize, y + self.squareSize), fill = self.colorList[idx])
try:
img.save(fname)
except Exception as e:
print "Could not save image to file %s. %s" % (fname, e)
def finish(self):
self.display.destroy()
| 31.732441
| 116
| 0.536046
|
cdc3691b923fbfc148679779e845c8adbd8fa6d2
| 6,167
|
py
|
Python
|
core/gdelt-diff.py
|
JustinTimperio/gdelt-diff
|
b20290837ffb12dff4e112cd87ec070df9932e9d
|
[
"MIT"
] | 3
|
2019-06-27T21:45:38.000Z
|
2021-02-11T15:26:43.000Z
|
core/gdelt-diff.py
|
JustinTimperio/gdelt-diff
|
b20290837ffb12dff4e112cd87ec070df9932e9d
|
[
"MIT"
] | 1
|
2021-02-11T15:26:39.000Z
|
2021-02-11T17:52:40.000Z
|
core/gdelt-diff.py
|
JustinTimperio/gdelt-diff
|
b20290837ffb12dff4e112cd87ec070df9932e9d
|
[
"MIT"
] | 1
|
2020-10-22T18:19:30.000Z
|
2020-10-22T18:19:30.000Z
|
#! /usr/bin/env python3
import os
import sys
import paf
import argparse
import requests
config = {
'base': '/opt/gdelt-diff',
'user_config': '/etc/gdelt-diff/config',
'english': 'http://data.gdeltproject.org/gdeltv2/masterfilelist.txt',
'translation': 'http://data.gdeltproject.org/gdeltv2/masterfilelist-translation.txt'
}
###################
# Core Functions
#################
def print_stream_status(lang, url):
status = requests.get(url, stream=True)
status = (lang.upper() + ' Stream Status: ' + str(status)[1:-1])
print('-'*len(status))
paf.prBold(status)
print('-'*len(status))
def fresh_install(lang, uc, config):
if uc[lang + '_path'] == '/path/here':
paf.prWarning('Your Config File Has Not Been Setup for the ' + lang.upper() + ' Stream!')
sys.exit('Edit the File ' + config['user_config'] + ' and Re-Run Your Command!')
if not os.path.exists(uc[lang + '_path']):
os.makedirs(uc[lang + '_path'])
paf.prWarning('Scanning File System...')
files = paf.basenames(paf.find_files(uc[lang + '_path']))
files = {"http://data.gdeltproject.org/gdeltv2/" + f for f in files}
paf.export_iterable(config['base'] + '/prev-' + lang + '.txt', files)
paf.export_iterable(config['base'] + '/404-' + lang + '.txt', [])
def fetch(url_list, storage_path):
fzf_new = set()
folders = set()
for f in paf.basenames(url_list):
if f:
folders.add(str('/' + f[:4] + '/' + f[4:6]))
for x in folders:
if not os.path.exists(storage_path + x):
os.makedirs(storage_path + x)
for url in paf.progress_bar(url_list, 'Downloading ' + str(len(url_list)) + ' Files'):
try:
f = requests.get(url)
except Exception:
fzf_new.add(url)
continue
fname = paf.basename(url)
folder = str('/' + fname[:4] + '/' + fname[4:6] + '/')
with open(storage_path + folder + fname, 'wb') as csv:
csv.write(f.content)
return fzf_new
def retry(lang, uc, config):
fzf_path = config['base'] + '/404-' + lang + '.txt'
fzf = fetch(paf.read_file(fzf_path), uc[lang + '_path'])
paf.export_iterable(fzf_path, fzf)
def gdelt_diff(lang, uc, config):
dlp_path = config['base'] + '/prev-' + lang + '.txt'
fzf_path = config['base'] + '/404-' + lang + '.txt'
# Download and Filter URLs
url = config[lang]
print_stream_status(lang, url)
paf.prBold('Downloading ' + lang.upper() + ' Stream Inventory File...')
dln = requests.get(url)
dlc = {''.join(x.split(' ')[2:]) for x in dln.text.split('\n')[:-1]}
# Filter URL Based On Start Date
if uc['start_date'] != 'all':
d = uc['start_date'].split('/')
days = {dt.replace('-', '') for dt in paf.date_to_today(int(d[0]), int(d[1]), int(d[2]))}
filtered = set()
for x in dlc:
if paf.basename(x)[:8] in days:
filtered.add(x)
dlc = filtered
# Run Install If Fresh Run
if not os.path.exists(dlp_path):
fresh_install(lang, uc, config)
# Compare Previous Run
dlp = paf.read_file(dlp_path)
diff = set(dlc).difference(dlp)
# Download Files Into Place
if len(diff) > 10000:
if paf.yn_frame(str(len(diff)) + ' Files Are Missing! Do You Still Want to Continue?') is True:
print('This May Take a While! Starting Download...')
else:
sys.exit()
if len(diff) > 0:
fzf = fetch(diff, uc[lang + '_path'])
paf.export_iterable(dlp_path, dlc)
for x in paf.read_file(fzf_path):
fzf.add(x)
paf.export_iterable(fzf_path, fzf)
else:
paf.prSuccess('All Files Are Up To Date!')
####################
# Parse Arguments
##################
parser = argparse.ArgumentParser(description="This tool is used to automatically maintain a repository of source files for the GDELT Project.")
parser.add_argument("-d", "--diff", action='store_true', help="Diff and Download BOTH GDELT Streams.")
parser.add_argument("-r", "--retry", action='store_true', help="Force a 404-Retry on All Missing or Dead Files in BOTH Streams.")
parser.add_argument("-de", "--diff_english", action='store_true', help="Diff and Download the Entire GDELT English Stream.")
parser.add_argument("-dt", "--diff_translation", action='store_true', help="Diff and Download the Entire GDELT Translation Stream.")
parser.add_argument("-re", "--retry_english", action='store_true', help="Force a 404-Retry on All Missing or Dead Files in English Stream.")
parser.add_argument("-rt", "--retry_translation", action='store_true', help="Force a 404-Retry on All Missing or Dead Files in Translation Stream.")
parser.add_argument("-rd", "--refresh_database", action='store_true', help="Update The Database of Synced Files For Both Streams.")
args = parser.parse_args()
######################
# Setup Environment
####################
if paf.am_i_root() is False:
sys.exit('Critical Error: This Command Must Be Run As Root!')
mandatory = ['english_path', 'translation_path', 'start_date']
optional = []
user_config = paf.read_config(config['user_config'], mandatory, optional)
#################
# Control Flow
###############
if args.diff:
gdelt_diff('english', user_config, config)
print('')
gdelt_diff('translation', user_config, config)
elif args.diff_english:
gdelt_diff('english', user_config, config)
elif args.diff_translation:
gdelt_diff('translation', user_config, config)
if args.retry:
gdelt_diff('english', user_config, config)
print('')
gdelt_diff('translation', user_config, config)
elif args.retry_english:
retry('english', user_config, config)
elif args.retry_translation:
retry('translation', user_config, config)
if args.refresh_database:
if os.path.exists(config['base'] + '/prev-english.txt'):
fresh_install('english', user_config, config)
print('Updated English Database!')
if os.path.exists(config['base'] + '/prev-translation.txt'):
fresh_install('translation', user_config, config)
print('Updated Translation Database!')
| 34.261111
| 148
| 0.624615
|
a01e8a6e1621e19158817fa366e18c450d24cebd
| 5,002
|
py
|
Python
|
student_feedback_project/student_feedback_app/tests/test_models.py
|
Ashwin-MJ/UniCom
|
89d02bd93ba7de6fd774a8a0be9c4b8c12f8ee99
|
[
"Unlicense"
] | null | null | null |
student_feedback_project/student_feedback_app/tests/test_models.py
|
Ashwin-MJ/UniCom
|
89d02bd93ba7de6fd774a8a0be9c4b8c12f8ee99
|
[
"Unlicense"
] | 5
|
2019-01-15T15:03:45.000Z
|
2019-03-20T11:58:55.000Z
|
student_feedback_project/student_feedback_app/tests/test_models.py
|
Ashwin-MJ/UniCom
|
89d02bd93ba7de6fd774a8a0be9c4b8c12f8ee99
|
[
"Unlicense"
] | null | null | null |
from student_feedback_app.models import *
from django.test import TestCase
from populate import *
# Ensure all test methods begin with test_..... otherwise they will not run
class StudentTestCase(TestCase):
def setUp(self):
add_course("Systems Programming 3", "SP3", "Introduction to Systems Programming using C and C++")
add_student("Bob", "3015244", "Bob@bob.bob", "Bob", 0, ["SP3"])
def test_student_in_course(self):
course = Course.objects.get(course_code = "SP3")
testUser = User.objects.get(username = "Bob")
testStudent = StudentProfile.objects.get(student=testUser)
self.assertTrue(testStudent in course.students.all())
def test_course_in_student(self):
course = Course.objects.get(course_code = "SP3")
testUser = User.objects.get(username = "Bob")
testStudent = StudentProfile.objects.get(student=testUser)
self.assertTrue(course in testStudent.courses.all())
class CourseTestCase(TestCase):
def setUp(self):
add_course("Systems Programming 3", "SP3", "Introduction to Systems Programming using C and C++")
def test_course_slug_correct(self):
# The slug for the above course should be sp3
systems = Course.objects.get(course_code="SP3")
self.assertEqual(systems.subject_slug, "sp3")
def test_course_description_correct(self):
systems = Course.objects.get(course_code="SP3")
self.assertEqual(systems.course_description, "Introduction to Systems Programming using C and C++")
class FeedbackTestCase(TestCase):
def setUp(self):
add_course("Systems Programming 3", "SP3", "Introduction to Systems Programming using C and C++")
add_lecturer("Wolf", "00001", "star", "wolf@star.com", ["SP3"])
add_student("Bob", "3015244", "Bob@bob.bob", "Bob", 0, ["SP3"])
add_category("writing", "#008080")
add_message("writing", ["wrote well"])
add_feedback(1, "writing", 4, "00001", "3015244", "SP3", "wrote well", "good explanation of pointers",False)
def test_fb_correct_optional_message(self):
fb = Feedback.objects.get(feedback_id=1)
self.assertEqual(fb.optional_message, "good explanation of pointers")
def test_fb_correct_lecturer(self):
fb = Feedback.objects.get(feedback_id=1)
self.assertEqual(fb.from_user.username, "Wolf")
def test_fb_correct_student(self):
fb = Feedback.objects.get(feedback_id=1)
self.assertEqual(fb.student.student.username, "Bob")
#Could add test for testing if feedback given time is the current time
class LecturerTestCase(TestCase):
def setUp(self):
add_course("Systems Programming 3", "SP3", "Introduction to Systems Programming using C and C++")
add_lecturer("Wolf", "00001", "star", "wolf@star.com", ["SP3"])
def test_lecturer_in_course(self):
course = Course.objects.get(course_code = "SP3")
testUser = User.objects.get(username = "Wolf")
testLecturer = LecturerProfile.objects.get(lecturer=testUser)
self.assertTrue(testLecturer in course.lecturers.all())
def test_course_in_lecturer(self):
course = Course.objects.get(course_code = "SP3")
testUser = User.objects.get(username = "Wolf")
testLecturer = LecturerProfile.objects.get(lecturer=testUser)
self.assertTrue(course in testLecturer.course_set.all())
def test_lecturer_email_correct(self):
testUser = User.objects.get(username = "Wolf")
testLecturer = LecturerProfile.objects.get(lecturer=testUser)
self.assertEqual(testLecturer.lecturer.email, "wolf@star.com")
class CategoryTestCase(TestCase):
def setUp(self):
add_course("Systems Programming 3", "SP3", "Introduction to Systems Programming using C and C++")
add_lecturer("Wolf", "00001", "star", "wolf@star.com", ["SP3"])
add_category("listening", "#008080")
def test_category_added_to_db(self):
self.assertTrue(Category.objects.filter(name="listening").exists())
class MessageTestCase(TestCase):
def setUp(self):
add_course("Systems Programming 3", "SP3", "Introduction to Systems Programming using C and C++")
add_lecturer("Wolf", "00001", "star", "wolf@star.com", ["SP3"])
add_category("listening", "#2F9395")
add_message("listening", ["listened well"])
def test_message_correct(self):
user = User.objects.get(id_number="00001")
cat = Category.objects.get(name="listening",user=user)
message = Message.objects.get(category=cat,user=user)
self.assertEqual(message.text, "listened well")
def test_cat_in_message(self):
user = User.objects.get(id_number="00001")
cat = Category.objects.get(name="listening",user=user)
message = Message.objects.get(category=cat,user=user)
self.assertEqual(message.category.name, cat.name)
def test_default_message(self):
#TODO
self.assertTrue(True)
| 41
| 116
| 0.681927
|
694afea209a03d3de15b92102f2dbfffe64b657a
| 14,922
|
py
|
Python
|
conda_concourse_ci/cli.py
|
pseudoyim/conda-concourse-ci
|
36ea5ff858397556412508574bccebd3b0c6fb9f
|
[
"BSD-3-Clause"
] | null | null | null |
conda_concourse_ci/cli.py
|
pseudoyim/conda-concourse-ci
|
36ea5ff858397556412508574bccebd3b0c6fb9f
|
[
"BSD-3-Clause"
] | null | null | null |
conda_concourse_ci/cli.py
|
pseudoyim/conda-concourse-ci
|
36ea5ff858397556412508574bccebd3b0c6fb9f
|
[
"BSD-3-Clause"
] | null | null | null |
import argparse
import logging
import os
from conda_build.conda_interface import cc_conda_build
from conda_concourse_ci import __version__, execute
def parse_args(parse_this=None):
parser = argparse.ArgumentParser()
parser.add_argument('--debug', action='store_true')
parser.add_argument('--version', action='version',
help='Show the conda-build version number and exit.',
version='conda-concourse-ci %s' % __version__)
sp = parser.add_subparsers(title='subcommands', dest='subparser_name')
submit_parser = sp.add_parser('submit', help="submit plan director to configured server")
submit_parser.add_argument('base_name',
help="name of your project, to distinguish it from other projects")
submit_parser.add_argument('--pipeline-name', help="name for the submitted pipeline",
default='{base_name} plan director')
submit_parser.add_argument('--pipeline-file', default='plan_director.yml',
help="path to pipeline .yml file containing plan")
submit_parser.add_argument('--config-root-dir',
help="path containing config.yml and matrix definitions")
submit_parser.add_argument('--src-dir', help="folder where git repo of source code lives",
default=os.getcwd())
submit_parser.add_argument('--private', action='store_false',
help='hide build logs (overall graph still shown in Concourse web view)',
dest='public')
bootstrap_parser = sp.add_parser('bootstrap',
help="create default configuration files to help you start")
bootstrap_parser.add_argument('base_name',
help="name of your project, to distinguish it from other projects")
one_off_parser = sp.add_parser('one-off',
help="submit local recipes and plan to configured server")
one_off_parser.add_argument('pipeline_label',
help="name of your project, to distinguish it from other projects")
one_off_parser.add_argument('folders', nargs="+",
help=("Specify folders, relative to --recipe-root-dir, to upload "
"and build"))
one_off_parser.add_argument('--automated-pipeline',
action='store_true',
default=False,
help="Flag to run this one_off command as an automated pipeline. Default is False",
)
one_off_parser.add_argument(
'--branches',
nargs='+',
default=None,
help=(
"Only used when --automated_pipeline is specified. "
"List of repository branches that recipes will be pulled from. "
"Either pass in one branch or n number of branches where "
"n is equal to the number of recipes you are building. "
"The default is to use the 'automated-build' branch. "
"Specific this option after the list of folders to avoid "
"confusing which arguments are folders and which are branches, "
"for example: "
"c3i one-off pipeline_label folder1 folder2 --branches branch1 branch2"
)
)
one_off_parser.add_argument(
"--pr-num",
action="store",
help="The PR number on which to make a comment when using the automated pipeline"
)
one_off_parser.add_argument(
"--repository",
action="store",
help="The git repo where the PR lives. This should look like: Org/Repo"
)
one_off_parser.add_argument(
"--pr-file",
action="store",
help="File added to the git repo by the PR"
)
one_off_parser.add_argument(
'--stage-for-upload', action='store_true',
help="create job that stages package for upload as part of the pipeline")
one_off_parser.add_argument(
'--push-branch', action='store_true',
help="create a job that push the branch(es) used for the build to master")
one_off_parser.add_argument(
'--destroy-pipeline', action='store_true',
help="destroys the pipeline once the review branch has been merged, "
"the artifacts have been staged, and the reciepe repo has been updated. "
"This requires --stage-for-upload and --push-branch options.")
one_off_parser.add_argument(
'--commit-msg', action='store',
help=("git commit message to record when packages are uploaded, "
"required when --stage-for-upload specified"))
one_off_parser.add_argument('--recipe-root-dir', default=os.getcwd(),
help="path containing recipe folders to upload")
one_off_parser.add_argument('--config-root-dir',
help="path containing config.yml and matrix definitions",
default=cc_conda_build.get('matrix_base_dir'))
one_off_parser.add_argument('--private', action='store_false',
help='hide build logs (overall graph still shown in Concourse web view)',
dest='public')
one_off_parser.add_argument('--channel', '-c', action='append',
help="Additional channel to use when building packages")
one_off_parser.add_argument('--platform-filter', '-p', action='append',
help="glob pattern(s) to filter build platforms. For example, "
"linux* will build all platform files whose filenames start with "
"linux", dest='platform_filters')
one_off_parser.add_argument('--worker-tag', '-t', action='append',
help="set worker tag(s) to limit where jobs will run. Applies "
"to all jobs. For finer control, use extra/worker_tags in "
"meta.yaml with selectors.",
dest='worker_tags')
one_off_parser.add_argument(
'-m', '--variant-config-files',
action="append",
help="""Additional variant config files to add. These yaml files can contain
keys such as `c_compiler` and `target_platform` to form a build matrix."""
)
one_off_parser.add_argument('--output-dir', help=("folder where output plan and recipes live."
"Defaults to temp folder. Set to something to save output."))
one_off_parser.add_argument(
'--append-file',
help="""Append data in meta.yaml with fields from this file. Jinja2 is not done
on appended fields""",
dest='append_sections_file',
)
one_off_parser.add_argument(
'--clobber-file',
help="""Clobber data in meta.yaml with fields from this file. Jinja2 is not done
on clobbered fields.""",
dest='clobber_sections_file',
)
one_off_parser.add_argument(
'--no-skip-existing', help="Do not skip existing builds",
dest="skip_existing", action="store_false"
)
one_off_parser.add_argument(
'--use-repo-access',
help="Pass the repo access credentials to the workers",
action="store_true",
)
one_off_parser.add_argument(
'--use-staging-channel',
help="Uploads built packages to staging channel",
action="store_true",
)
one_off_parser.add_argument(
'--dry-run',
action="store_true",
help=(
"Dry run, prepare concourse plan and files but do not submit. "
"Best used with the --output-dir option so the output can be inspected"
),
)
batch_parser = sp.add_parser('batch', help="submit a batch of one-off jobs.")
batch_parser.add_argument(
'batch_file',
help="""File describing batch job. Each lines defines a seperate
one-off job. List one or more folders on each line. Job specific
arguments can be specified after a ';' using param=value, multiple
arguments are seperated by a ','. For example:
recipe-feedstock; channel=conda-forge,clobber_sections_file=clobber.yaml
""")
# batch specific arguments
batch_parser.add_argument(
'--max-builds', default=6, type=int,
help=("maximum number of activate builds allowed before starting a new"
"job, default is 6"))
batch_parser.add_argument(
'--poll-time', default=120, type=int,
help=("time in seconds between checking concourse server for active "
"builds, default is 120 seconds."))
batch_parser.add_argument(
'--build-lookback', default=500, type=int,
help="number of builds to examine for active builds, default is 500")
batch_parser.add_argument(
'--label-prefix', default='autobot_',
help="prefix for pipeline labels, default is autobot_")
# one-off arguments
batch_parser.add_argument('--recipe-root-dir', default=os.getcwd(),
help="path containing recipe folders to upload")
batch_parser.add_argument('--config-root-dir',
help="path containing config.yml and matrix definitions",
default=cc_conda_build.get('matrix_base_dir'))
batch_parser.add_argument('--private', action='store_false',
help='hide build logs (overall graph still shown in Concourse web view)',
dest='public')
batch_parser.add_argument('--channel', '-c', action='append',
help="Additional channel to use when building packages")
batch_parser.add_argument('--platform-filter', '-p', action='append',
help="glob pattern(s) to filter build platforms. For example, "
"linux* will build all platform files whose filenames start with "
"linux", dest='platform_filters')
batch_parser.add_argument('--worker-tag', '-t', action='append',
help="set worker tag(s) to limit where jobs will run. Applies "
"to all jobs. For finer control, use extra/worker_tags in "
"meta.yaml with selectors.",
dest='worker_tags')
batch_parser.add_argument(
'-m', '--variant-config-files',
action="append",
help="""Additional variant config files to add. These yaml files can contain
keys such as `c_compiler` and `target_platform` to form a build matrix."""
)
batch_parser.add_argument('--output-dir', help=("folder where output plan and recipes live."
"Defaults to temp folder. Set to something to save output."))
batch_parser.add_argument(
'--append-file',
help="""Append data in meta.yaml with fields from this file. Jinja2 is not done
on appended fields""",
dest='append_sections_file',
)
batch_parser.add_argument(
'--clobber-file',
help="""Clobber data in meta.yaml with fields from this file. Jinja2 is not done
on clobbered fields.""",
dest='clobber_sections_file',
)
batch_parser.add_argument(
'--no-skip-existing', help="Do not skip existing builds",
dest="skip_existing", action="store_false"
)
batch_parser.add_argument(
'--use-repo-access',
help="Pass the repo access credentials to the workers",
action="store_true",
)
batch_parser.add_argument(
'--use-staging-channel',
help="Uploads built packages to staging channel",
action="store_true",
)
rm_parser = sp.add_parser('rm', help='remove pipelines from server')
rm_parser.add_argument('pipeline_names', nargs="+",
help=("Specify pipeline names on server to remove"))
rm_parser.add_argument('--config-root-dir',
help="path containing config.yml and matrix definitions",
default=cc_conda_build.get('matrix_base_dir'))
rm_parser.add_argument('--do-it-dammit', '-y', help="YOLO", action="store_true")
trigger_parser = sp.add_parser('trigger', help='trigger (failed) jobs of a pipeline')
trigger_parser.add_argument('pipeline_names', nargs='+',
help=("Specify pipeline names to trigger"))
trigger_parser.add_argument('--config-root-dir',
help="path containing config.yml and matrix definitions",
default=cc_conda_build.get('matrix_base_dir'))
trigger_parser.add_argument('--all', dest="trigger_all",
action="store_true", help="trigger all jobs")
abort_parser = sp.add_parser('abort', help='abort jobs of a pipeline')
abort_parser.add_argument('pipeline_names', nargs='+',
help=("Specify pipeline names to abort"))
abort_parser.add_argument('--config-root-dir',
help="path containing config.yml and matrix definitions",
default=cc_conda_build.get('matrix_base_dir'))
return parser.parse_known_args(parse_this)
def main(args=None):
if not args:
args, pass_throughs = parse_args()
else:
args, pass_throughs = parse_args(args)
if args.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
if args.subparser_name == 'submit':
args_dict = args.__dict__
if not args_dict.get('config_root_dir'):
args_dict['config_root_dir'] = args_dict['base_name']
execute.submit(pass_throughs=pass_throughs, **args_dict)
elif args.subparser_name == 'bootstrap':
execute.bootstrap(pass_throughs=pass_throughs, **args.__dict__)
elif args.subparser_name == 'one-off':
execute.submit_one_off(pass_throughs=pass_throughs, **args.__dict__)
elif args.subparser_name == 'batch':
execute.submit_batch(pass_throughs=pass_throughs, **args.__dict__)
elif args.subparser_name == 'rm':
execute.rm_pipeline(pass_throughs=pass_throughs, **args.__dict__)
elif args.subparser_name == 'trigger':
execute.trigger_pipeline(pass_throughs=pass_throughs, **args.__dict__)
elif args.subparser_name == 'abort':
execute.abort_pipeline(pass_throughs=pass_throughs, **args.__dict__)
else:
# this is here so that if future subcommands are added, you don't forget to add a bit
# here to enable them.
raise NotImplementedError("Command {} is not implemented".format(args.subparser_name))
| 50.073826
| 115
| 0.611178
|
74997322d8643623ca4361148bc4de94b30c738c
| 17,544
|
py
|
Python
|
pytorch_lightning/trainer/distrib_parts.py
|
sebastienwood/pytorch-lightning
|
b8e864b2a854851463b9217efcb9616ff7f2c49e
|
[
"Apache-2.0"
] | null | null | null |
pytorch_lightning/trainer/distrib_parts.py
|
sebastienwood/pytorch-lightning
|
b8e864b2a854851463b9217efcb9616ff7f2c49e
|
[
"Apache-2.0"
] | null | null | null |
pytorch_lightning/trainer/distrib_parts.py
|
sebastienwood/pytorch-lightning
|
b8e864b2a854851463b9217efcb9616ff7f2c49e
|
[
"Apache-2.0"
] | null | null | null |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Root module for all distributed operations in Lightning.
Currently supports training on CPU, GPU (dp, ddp, ddp2, horovod) and TPU.
"""
from contextlib import ExitStack
import os
from abc import ABC, abstractmethod
import time
import random
import torch
from torch.optim.lr_scheduler import _LRScheduler
from typing import Union, Callable, Any, List, Optional, Tuple, MutableSequence, NoneType
from pytorch_lightning.core.lightning import LightningModule
from pytorch_lightning import _logger as log
from pytorch_lightning.overrides.data_parallel import (
LightningDistributedDataParallel,
LightningDataParallel,
)
from pytorch_lightning.utilities import move_data_to_device, NATIVE_AMP_AVALAIBLE
from pytorch_lightning.utilities.exceptions import MisconfigurationException
from pytorch_lightning.utilities.distributed import rank_zero_only
from pytorch_lightning.utilities import rank_zero_warn
from pytorch_lightning.utilities.memory import is_oom_error, garbage_collection_cuda
try:
from apex import amp
except ImportError:
APEX_AVAILABLE = False
else:
APEX_AVAILABLE = True
try:
import torch_xla.core.xla_model as xm
except ImportError:
XLA_AVAILABLE = False
else:
XLA_AVAILABLE = True
try:
import horovod.torch as hvd
except (ModuleNotFoundError, ImportError):
HOROVOD_AVAILABLE = False
else:
HOROVOD_AVAILABLE = True
class TrainerDPMixin(ABC):
# this is just a summary on variables used in this abstract class,
# the proper values/initialisation should be done in child class
on_gpu: bool
use_dp: bool
use_ddp2: bool
use_ddp: bool
testing: bool
use_single_gpu: bool
root_gpu: ...
amp_level: str
precision: ...
global_rank: int
tpu_local_core_rank: int
tpu_global_core_rank: int
use_tpu: bool
data_parallel_device_ids: ...
progress_bar_callback: ...
on_colab_kaggle: str
save_spawn_weights: Callable
logger: ...
@property
@abstractmethod
def use_amp(self) -> bool:
"""Warning: this is just empty shell for code implemented in other class."""
@abstractmethod
def call_setup_hook(self, *args):
"""Warning: this is just empty shell for code implemented in other class."""
@abstractmethod
def run_pretrain_routine(self, *args):
"""Warning: this is just empty shell for code implemented in other class."""
@abstractmethod
def init_optimizers(self, *args) -> Tuple[List, List, List]:
"""Warning: this is just empty shell for code implemented in other class."""
@abstractmethod
def get_model(self) -> LightningModule:
"""Warning: this is just empty shell for code implemented in other class."""
@abstractmethod
def reinit_scheduler_properties(self, *args):
"""Warning: this is just empty shell for code implemented in other class."""
@abstractmethod
def setup(self, *args) -> None:
"""Warning: this is just empty shell for code implemented in other class."""
@abstractmethod
def is_function_implemented(self, *args) -> bool:
"""Warning: this is just empty shell for code implemented in other class."""
def copy_trainer_model_properties(self, model):
if isinstance(model, LightningDataParallel):
ref_model = model.module
elif isinstance(model, LightningDistributedDataParallel):
ref_model = model.module
else:
ref_model = model
for m in [model, ref_model]:
m.trainer = self
m.logger = self.logger
m.use_dp = self.use_dp
m.use_ddp2 = self.use_ddp2
m.use_ddp = self.use_ddp
m.use_amp = self.use_amp
m.testing = self.testing
m.use_single_gpu = self.use_single_gpu
m.use_tpu = self.use_tpu
m.tpu_local_core_rank = self.tpu_local_core_rank
m.tpu_global_core_rank = self.tpu_global_core_rank
def transfer_batch_to_tpu(self, batch: Any, tpu_id: Optional[int] = None):
"""
Transfers the data to the TPU.
Args:
batch: A tensor or collection of tensors.
tpu_id: The id of the TPU core. If omitted, the first available core is chosen.
Return:
the tensor on the TPU device.
See Also:
- :func:`~pytorch_lightning.utilities.apply_func.move_data_to_device`
"""
if not XLA_AVAILABLE:
raise MisconfigurationException(
'Requested to transfer batch to TPU but XLA is not available.'
' Are you sure this machine has TPUs?'
)
device = xm.xla_device(tpu_id)
return self.__transfer_batch_to_device(batch, device)
def transfer_batch_to_gpu(self, batch: Any, gpu_id: Optional[int] = None):
"""
Transfers the data to the GPU.
Args:
batch: A tensor or collection of tensors.
gpu_id: The id of the GPU device. If omitted, the first available GPU is chosen.
Return:
the tensor on the GPU device.
See Also:
- :func:`~pytorch_lightning.utilities.apply_func.move_data_to_device`
"""
device = torch.device('cuda', gpu_id)
return self.__transfer_batch_to_device(batch, device)
def __transfer_batch_to_device(self, batch: Any, device: torch.device):
model = self.get_model()
if model is not None:
return model.transfer_batch_to_device(batch, device)
return move_data_to_device(batch, device)
def horovod_train(self, model):
# call setup after the ddp process has connected
self.call_setup_hook(model)
if torch.cuda.is_available() and self.on_gpu:
# Horovod: pin GPU to local rank
assert self.root_gpu == hvd.local_rank()
torch.cuda.set_device(self.root_gpu)
model.cuda(self.root_gpu)
# avoid duplicating progress bar
if hvd.rank() != 0 and self.progress_bar_callback is not None:
self.progress_bar_callback.disable()
# CHOOSE OPTIMIZER
# allow for lr schedulers as well
self.optimizers, self.lr_schedulers, self.optimizer_frequencies = self.init_optimizers(model)
# Horovod: scale the learning rate by the number of workers to account for
# increased total batch size
for optimizer in self.optimizers:
for param_group in optimizer.param_groups:
param_group['lr'] *= hvd.size()
# Horovod: adjust base LR used by schedulers to match scaled optimizer initial LR
for scheduler in self.lr_schedulers:
scheduler = scheduler['scheduler']
if isinstance(scheduler, _LRScheduler):
scheduler.base_lrs = [lr * hvd.size() for lr in scheduler.base_lrs]
if self.use_amp:
model, optimizers = model.configure_apex(amp, model, self.optimizers, self.amp_level)
self.optimizers = optimizers
self.reinit_scheduler_properties(self.optimizers, self.lr_schedulers)
# Horovod: broadcast parameters & optimizer state to ensure consistent initialization
hvd.broadcast_parameters(model.state_dict(), root_rank=0)
for optimizer in self.optimizers:
hvd.broadcast_optimizer_state(optimizer, root_rank=0)
def filter_named_parameters(model, optimizer):
opt_params = set([p for group in optimizer.param_groups for p in group.get('params', [])])
return [(name, p) for name, p in model.named_parameters() if p in opt_params]
# Horovod: wrap optimizers to perform gradient aggregation via allreduce
self.optimizers = [
hvd.DistributedOptimizer(optimizer, named_parameters=filter_named_parameters(model, optimizer))
for optimizer in self.optimizers
]
# Update logger rank info from Horovod to avoid race conditions from different ranks
# creating directories / writing files in the same locations.
self.global_rank = hvd.rank()
rank_zero_only.rank = self.global_rank
with ExitStack() as stack:
for optimizer in self.optimizers:
# Synchronization will be performed explicitly following backward()
stack.enter_context(optimizer.skip_synchronize())
result = self.run_pretrain_routine(model)
# Make sure all workers have finished training before returning to the user
hvd.join()
return result
def _normalize_parse_gpu_string_input(s: Union[int, str, List[int]]) -> Union[int, List[int]]:
if isinstance(s, str):
if s == '-1':
return -1
else:
return [int(x.strip()) for x in s.split(',') if len(x) > 0]
else:
return s
def get_all_available_gpus() -> List[int]:
"""
Returns:
a list of all available gpus
"""
return list(range(torch.cuda.device_count()))
def _check_data_type(device_ids: Any) -> None:
"""
Checks that the device_ids argument is one of: None, Int, String or List.
Raises a MisconfigurationException otherwise.
Args:
device_ids: gpus/tpu_cores parameter as passed to the Trainer
"""
if device_ids is not None and (not isinstance(device_ids, (int, str, MutableSequence)) or isinstance(device_ids, bool)):
raise MisconfigurationException("Device ID's (GPU/TPU) must be int, string or sequence of ints or None.")
def _normalize_parse_gpu_input_to_list(gpus: Union[int, List[int]]) -> Optional[List[int]]:
assert gpus is not None
if isinstance(gpus, MutableSequence):
return list(gpus)
# must be an int
if not gpus: # gpus==0
return None
if gpus == -1:
return get_all_available_gpus()
return list(range(gpus))
def sanitize_gpu_ids(gpus: List[int]) -> List[int]:
"""
Checks that each of the GPUs in the list is actually available.
Raises a MisconfigurationException if any of the GPUs is not available.
Args:
gpus: list of ints corresponding to GPU indices
Returns:
unmodified gpus variable
"""
all_available_gpus = get_all_available_gpus()
misconfig = False
for gpu in gpus:
if gpu not in all_available_gpus:
misconfig = True
if misconfig:
# sometimes auto ddp might have different flags
# but this is not what the user intended
# correct for the user
if len(gpus) == len(all_available_gpus):
gpus = all_available_gpus
else:
raise MisconfigurationException(f"""
You requested GPUs: {gpus}
But your machine only has: {all_available_gpus}
""")
return gpus
def _parse_gpu_ids(gpus: Optional[Union[int, str, List[int]]]) -> Optional[List[int]]:
"""
Parses the GPU ids given in the format as accepted by the
:class:`~pytorch_lightning.trainer.Trainer`.
Args:
gpus: An int -1 or string '-1' indicate that all available GPUs should be used.
A list of ints or a string containing list of comma separated integers
indicates specific GPUs to use.
An int 0 means that no GPUs should be used.
Any int N > 0 indicates that GPUs [0..N) should be used.
Returns:
a list of gpus to be used or ``None`` if no GPUs were requested
If no GPUs are available but the value of gpus variable indicates request for GPUs
then a MisconfigurationException is raised.
"""
# nothing was passed into the GPUs argument
if callable(gpus):
return None
# Check that gpus param is None, Int, String or List
_check_data_type(gpus)
# Handle the case when no gpus are requested
if gpus is None or isinstance(gpus, int) and gpus == 0:
return None
# We know user requested GPUs therefore if some of the
# requested GPUs are not available an exception is thrown.
gpus = _normalize_parse_gpu_string_input(gpus)
gpus = _normalize_parse_gpu_input_to_list(gpus)
if not gpus:
raise MisconfigurationException("GPUs requested but none are available.")
gpus = sanitize_gpu_ids(gpus)
return gpus
def determine_root_gpu_device(gpus: List[int]) -> Optional[int]:
"""
Args:
gpus: non-empty list of ints representing which gpus to use
Returns:
designated root GPU device id
"""
if gpus is None:
return None
assert isinstance(gpus, list), "gpus should be a list"
assert len(gpus) > 0, "gpus should be a non empty list"
# set root gpu
root_gpu = gpus[0]
return root_gpu
def retry_jittered_backoff(func: Callable, num_retries: int = 5, cap_delay: float = 1.0, base_delay: float = 0.01):
"""Retry jittered backoff.
Based on:
https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
Args:
func: tested function
num_retries: number of tries
cap_delay: max sleep time
base_delay: initial sleep time is 10ms
"""
sleep_delay = base_delay # initial sleep time is 10ms
for i in range(num_retries):
try:
return func()
except RuntimeError as err:
if i == num_retries - 1:
raise err
else:
continue
time.sleep(sleep_delay)
sleep_delay = min(cap_delay, random.uniform(base_delay, sleep_delay * 3))
def _parse_tpu_cores(tpu_cores: Union[int, str, List]) -> Optional[Union[List[int], int]]:
"""
Parses the tpu_cores given in the format as accepted by the
:class:`~pytorch_lightning.trainer.Trainer`.
Args:
tpu_cores: An int 1 or string '1' indicate that 1 core with multi-processing should be used
An int 8 or string '8' indicate that all 8 cores with multi-processing should be used
A list of int or a string containing list of comma separated integer
indicates specific TPU core to use.
Returns:
a list of tpu_cores to be used or ``None`` if no TPU cores were requested
"""
if callable(tpu_cores):
return None
_check_data_type(tpu_cores)
if isinstance(tpu_cores, str):
tpu_cores = _parse_tpu_cores_str(tpu_cores.strip())
if not _tpu_cores_valid(tpu_cores):
raise MisconfigurationException("`tpu_cores` can only be 1, 8 or [<1-8>]")
return tpu_cores
def _tpu_cores_valid(tpu_cores):
return tpu_cores in (1, 8, None) or (
isinstance(tpu_cores, (list, tuple, set)) and
len(tpu_cores) == 1 and
tpu_cores[0] in range(1, 9)
)
def _parse_tpu_cores_str(tpu_cores):
if tpu_cores in ('1', '8'):
tpu_cores = int(tpu_cores)
else:
tpu_cores = [int(x.strip()) for x in tpu_cores.split(',') if len(x) > 0]
return tpu_cores
def pick_single_gpu(exclude_gpus: list):
for i in range(torch.cuda.device_count()):
if i in exclude_gpus:
continue
# Try to allocate on device:
device = torch.device(f"cuda:{i}")
try:
torch.ones(1).to(device)
except RuntimeError:
continue
return i
raise RuntimeError("No GPUs available.")
def pick_single_gpu_realist_workload(exclude_gpus: list, model:LightningModule):
for i in range(torch.cuda.device_count()):
if i in exclude_gpus:
continue
# Try to allocate on device:
device = torch.device(f"cuda:{i}")
batch=next(iter(model.train_dataloader))
try:
model_device = model.to(device)
batch_device = batch.to(device)
model_device.train() # record grads
model_device(batch_device)
except RuntimeError as exception:
if is_oom_error(exception): # clean after the failed attempt
garbage_collection_cuda()
else: raise
continue
return i
raise RuntimeError("No GPUs available.")
def pick_multiple_gpus(nb:int, model:Optional[LightningModule] = None) -> list:
r""" Pick available GPUs
Args:
nb: the max number of GPU to pick
model: (optional) a LightningModule with model and train_loader attached
Return:
a list of GPU index availables
Note: if model is not None, a GPU is considered available if it is able to run in `train` mode a batch
"""
torch.set_grad_enabled(True)
picked = []
for _ in range(nb):
if not model: picked.append(pick_single_gpu(exclude_gpus=picked))
else :
assert hasattr(model, 'train_dataloader')
picked.append(pick_single_gpu_realist_workload(exclude_gpus=picked, model=model))
if len(picked) < 1: raise RuntimeError("None of the GPUs could accept the given workload.")
torch.set_grad_enabled(False)
return picked
| 33.803468
| 124
| 0.661879
|
3e576ebbff6bd52e93c4107223d4f5e8c9e18386
| 3,306
|
py
|
Python
|
tests/test_sums.py
|
Autoplectic/ludology
|
e43d7f3c996ae9499d33cd5e1b64acca8b1d29b8
|
[
"BSD-2-Clause"
] | 4
|
2021-03-09T18:10:41.000Z
|
2021-10-14T03:10:46.000Z
|
tests/test_sums.py
|
Autoplectic/ludology
|
e43d7f3c996ae9499d33cd5e1b64acca8b1d29b8
|
[
"BSD-2-Clause"
] | 11
|
2018-05-19T00:40:10.000Z
|
2019-12-09T06:14:35.000Z
|
tests/test_sums.py
|
Autoplectic/ludology
|
e43d7f3c996ae9499d33cd5e1b64acca8b1d29b8
|
[
"BSD-2-Clause"
] | 5
|
2018-08-23T17:33:39.000Z
|
2022-02-04T15:04:55.000Z
|
"""
Tests for ludology.sums.
"""
import pytest
from ludology import Game
from ludology.canonical_form import canonical_form
from ludology.closet import one, pm_one, star, up, zero
from ludology.sums import (conjunctive, continued_conjunctive,
diminished_disjunctive, disjunctive, ordinal,
selective, sequential, shortened_selective, side)
G = Game({0}, {pm_one})
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, Game({1}, {Game({1}, {1})})),
(G, zero, G),
(zero, G, G),
])
def test_disjunctive(G, H, J):
"""
Test that the disjunctive sum matches known results.
"""
assert canonical_form(disjunctive(G, H)) == J
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, Game({1}, {Game({1}, {1})})),
(G, zero, G),
(zero, G, G),
])
def test_disjunctive_2(G, H, J):
"""
Test that the disjunctive sum matches known results, without canonizing.
"""
assert canonical_form(disjunctive(G, H, canon=False)) == J
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, up),
(G, zero, zero),
(zero, G, zero),
])
def test_conjunctive(G, H, J):
"""
Test that the conjunctive sum matches known results.
"""
assert canonical_form(conjunctive(G, H)) == J
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, Game({1}, {Game({1, one + star}, {-1, -one + star}), Game({1}, {1, pm_one})})),
(G, zero, G),
(zero, G, G),
])
def test_selective(G, H, J):
"""
Test that the selective sum matches known results.
"""
assert canonical_form(selective(G, H)) == J
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, up),
(G, zero, zero),
(zero, G, zero),
])
def test_diminished_disjunctive(G, H, J):
"""
Test that the diminished disjunctive sum matches known results.
"""
assert canonical_form(diminished_disjunctive(G, H)) == J
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, one),
(G, zero, G),
(zero, G, G),
])
def test_continued_conjunctive(G, H, J):
"""
Test that the continued conjunctive sum matches known results.
"""
assert canonical_form(continued_conjunctive(G, H)) == J
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, Game({0}, {star, Game({0, star}, {0, star})})),
(G, zero, zero),
(zero, G, zero),
])
def test_shortened_selective(G, H, J):
"""
Test that the shortened selective sum matches known results.
"""
assert canonical_form(shortened_selective(G, H)) == J
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, Game({1}, {Game({1}, {1, pm_one}), pm_one})),
(G, zero, G),
(zero, G, G),
])
def test_ordinal(G, H, J):
"""
Test that the ordinal sum matches known results.
"""
assert canonical_form(ordinal(G, H)) == J
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, Game({0}, {1 / 2})),
(G, zero, G),
(zero, G, G),
])
def test_side(G, H, J):
"""
Test that the side sum matches known results.
"""
assert canonical_form(side(G, H)) == J
@pytest.mark.parametrize(('G', 'H', 'J'), [
(G, up, one),
(G, zero, G),
(zero, G, G),
])
def test_sequential(G, H, J):
"""
Test that the sequential sum matches known results.
"""
assert canonical_form(sequential(G, H)) == J
| 24.308824
| 91
| 0.572293
|
33b43106e49be9783886d263a639d461d747098c
| 17,396
|
py
|
Python
|
reflectivity_ui/interfaces/data_handling/data_info.py
|
jenest/reflectivity_ui
|
9fc746e1729d57268c621e6a655b5022fba3af8b
|
[
"Apache-2.0"
] | null | null | null |
reflectivity_ui/interfaces/data_handling/data_info.py
|
jenest/reflectivity_ui
|
9fc746e1729d57268c621e6a655b5022fba3af8b
|
[
"Apache-2.0"
] | null | null | null |
reflectivity_ui/interfaces/data_handling/data_info.py
|
jenest/reflectivity_ui
|
9fc746e1729d57268c621e6a655b5022fba3af8b
|
[
"Apache-2.0"
] | null | null | null |
"""
Meta-data information for MR reduction
"""
#pylint: disable=too-few-public-methods, wrong-import-position, too-many-instance-attributes, wrong-import-order
from __future__ import absolute_import, division, print_function
import sys
import time
import logging
import math
import copy
import numpy as np
from scipy import ndimage
import scipy.optimize as opt
from .peak_finding import find_peaks, peak_prominences, peak_widths
# Import mantid according to the application configuration
from . import ApplicationConfiguration
sys.path.insert(0, ApplicationConfiguration().mantid_path)
import mantid.simpleapi as api
NX_PIXELS = 304
NY_PIXELS = 256
class DataInfo(object):
"""
Class to hold the relevant information from a run (scattering or direct beam).
"""
peak_range_offset = 0
tolerance = 0.02
def __init__(self, ws, cross_section, configuration):
self.cross_section = cross_section
self.run_number = ws.getRunNumber()
self.is_direct_beam = False
self.data_type = 1
self.peak_position = 0
self.peak_range = [0,0]
self.low_res_range = [0,0]
self.background = configuration.bck_roi
self.n_events_cutoff = 100
# ROI information
self.roi_peak = [0,0]
self.roi_low_res = [0,0]
self.roi_background = [0,0]
# Options to override the ROI
self.force_peak_roi = configuration.force_peak_roi
self.forced_peak_roi = configuration.peak_roi
self.force_low_res_roi = configuration.force_low_res_roi
self.forced_low_res_roi = configuration.low_res_roi
self.force_bck_roi = configuration.force_bck_roi
self.forced_bck_roi = configuration.bck_roi
# Peak found before fitting for the central position
self.found_peak = [0,0]
self.found_low_res = [0,0]
# Processing options
# Use the ROI rather than finding the ranges
self.use_roi = configuration.use_roi
self.use_roi_actual = False
# Use the 2nd ROI as the background, if available
self.use_roi_bck = configuration.use_roi_bck
# Use background as a region on each side of the peak
self.use_tight_bck = configuration.use_tight_bck
# Width of the background on each side of the peak
self.bck_offset = configuration.bck_offset
# Update the specular peak range after finding the peak
# within the ROI
self.update_peak_range = configuration.update_peak_range
self.wl_bandwidth = configuration.wl_bandwidth
self.tof_range = self.get_tof_range(ws)
self.calculated_scattering_angle = 0.0
self.theta_d = 0.0
t_0 = time.time()
self.determine_data_type(ws)
logging.info("INSPECT: %s sec" % (time.time()-t_0))
def get_tof_range(self, ws):
"""
Determine TOF range from the data
:param workspace ws: workspace to work with
"""
run_object = ws.getRun()
sample_detector_distance = run_object['SampleDetDis'].getStatistics().mean
source_sample_distance = run_object['ModeratorSamDis'].getStatistics().mean
# Check units
if not run_object['SampleDetDis'].units in ['m', 'meter']:
sample_detector_distance /= 1000.0
if not run_object['ModeratorSamDis'].units in ['m', 'meter']:
source_sample_distance /= 1000.0
source_detector_distance = source_sample_distance + sample_detector_distance
h = 6.626e-34 # m^2 kg s^-1
m = 1.675e-27 # kg
wl = run_object.getProperty('LambdaRequest').value[0]
chopper_speed = run_object.getProperty('SpeedRequest1').value[0]
wl_offset = 0
cst = source_detector_distance / h * m
half_width = self.wl_bandwidth / 2.0
tof_min = cst * (wl + wl_offset * 60.0 / chopper_speed - half_width * 60.0 / chopper_speed) * 1e-4
tof_max = cst * (wl + wl_offset * 60.0 / chopper_speed + half_width * 60.0 / chopper_speed) * 1e-4
#_tof_min = ws.getTofMin()
#_tof_max = ws.getTofMax()
#tof_min = max(_tof_min, tof_min)
#tof_max = min(_tof_max, tof_max)
self.tof_range = [tof_min, tof_max]
return [tof_min, tof_max]
def process_roi(self, ws):
"""
Process the ROI information and determine the peak
range, the low-resolution range, and the background range.
Starting in June 2018, with the DAS upgrade, the ROIs are
specified with a start/width rather than start/stop.
:param workspace ws: workspace to work with
"""
roi_peak = [0,0]
roi_low_res = [0,0]
roi_background = [0,0]
# Read ROI 1
roi1_valid = True
if 'ROI1StartX' in ws.getRun():
roi1_x0 = ws.getRun()['ROI1StartX'].getStatistics().mean
roi1_y0 = ws.getRun()['ROI1StartY'].getStatistics().mean
if 'ROI1SizeX' in ws.getRun():
size_x = ws.getRun()['ROI1SizeX'].getStatistics().mean
size_y = ws.getRun()['ROI1SizeY'].getStatistics().mean
roi1_x1 = roi1_x0 + size_x
roi1_y1 = roi1_y0 + size_y
else:
roi1_x1 = ws.getRun()['ROI1EndX'].getStatistics().mean
roi1_y1 = ws.getRun()['ROI1EndY'].getStatistics().mean
if roi1_x1 > roi1_x0:
peak1 = [int(roi1_x0), int(roi1_x1)]
else:
peak1 = [int(roi1_x1), int(roi1_x0)]
if roi1_y1 > roi1_y0:
low_res1 = [int(roi1_y0), int(roi1_y1)]
else:
low_res1 = [int(roi1_y1), int(roi1_y0)]
if peak1 == [0,0] and low_res1 == [0,0]:
roi1_valid = False
# Read ROI 2
if 'ROI2StartX' in ws.getRun():
roi2_valid = True
roi2_x0 = ws.getRun()['ROI2StartX'].getStatistics().mean
roi2_y0 = ws.getRun()['ROI2StartY'].getStatistics().mean
if 'ROI2SizeX' in ws.getRun():
size_x = ws.getRun()['ROI2SizeX'].getStatistics().mean
size_y = ws.getRun()['ROI2SizeY'].getStatistics().mean
roi2_x1 = roi2_x0 + size_x
roi2_y1 = roi2_y0 + size_y
else:
roi2_x1 = ws.getRun()['ROI2EndX'].getStatistics().mean
roi2_y1 = ws.getRun()['ROI2EndY'].getStatistics().mean
if roi2_x1 > roi2_x0:
peak2 = [int(roi2_x0), int(roi2_x1)]
else:
peak2 = [int(roi2_x1), int(roi2_x0)]
if roi2_y1 > roi2_y0:
low_res2 = [int(roi2_y0), int(roi2_y1)]
else:
low_res2 = [int(roi2_y1), int(roi2_y0)]
if peak2 == [0,0] and low_res2 == [0,0]:
roi2_valid = False
else:
roi2_valid = False
else:
roi1_valid = False
roi2_valid = False
# Pick the ROI that describes the reflectivity peak
if roi1_valid and not roi2_valid:
roi_peak = peak1
roi_low_res = low_res1
roi_background = [0,0]
elif roi2_valid and not roi1_valid:
roi_peak = peak2
roi_low_res = low_res2
roi_background = [0,0]
elif roi1_valid and roi2_valid:
# If ROI 2 is within ROI 1, treat it as the peak,
# otherwise, use ROI 1
if peak1[0] >= peak2[0] and peak1[1] <= peak2[1]:
roi_peak = peak1
roi_low_res = low_res1
roi_background = peak2
elif peak2[0] >= peak1[0] and peak2[1] <= peak1[1]:
roi_peak = peak2
roi_low_res = low_res2
roi_background = peak1
else:
roi_peak = peak1
roi_low_res = low_res1
roi_background = [0,0]
# After all this, update the ROI according to reduction options
self.roi_peak = roi_peak
self.roi_low_res = roi_low_res
self.roi_background = roi_background
def determine_data_type(self, ws):
"""
Inspect the data and determine peak locations
and data type.
:param workspace ws: Workspace to inspect
"""
# Skip empty data entries
if ws.getNumberEvents() < self.n_events_cutoff:
self.data_type = -1
logging.info("No data for %s %s" % (self.run_number, self.cross_section))
return
# Find reflectivity peak and low resolution ranges
#fitter = Fitter(ws, True)
fitter = Fitter2(ws)
peak, low_res = fitter.fit_2d_peak()
self.found_peak = copy.copy(peak)
self.found_low_res = copy.copy(low_res)
logging.info("Run %s [%s]: Peak found %s" % (self.run_number, self.cross_section, peak))
logging.info("Run %s [%s]: Low-res found %s" %(self.run_number, self.cross_section, str(low_res)))
# Process the ROI information
try:
self.process_roi(ws)
except:
logging.info("Could not process ROI\n%s" % sys.exc_info()[1])
# Keep track of whether we actually used the ROI
self.use_roi_actual = False
# If we were asked to use the ROI but no peak is in it, use the peak we found
# If we were asked to use the ROI and there's a peak in it, use the ROI
if self.use_roi and not self.update_peak_range and not self.roi_peak == [0,0]:
logging.info("Using ROI peak range: [%s %s]" % (self.roi_peak[0], self.roi_peak[1]))
self.use_roi_actual = True
peak = copy.copy(self.roi_peak)
if not self.roi_low_res == [0,0]:
low_res = copy.copy(self.roi_low_res)
if not self.roi_background == [0,0]:
bck_range = copy.copy(self.roi_background)
elif self.use_roi and self.update_peak_range and not self.roi_peak == [0,0]:
logging.info("Using fit peak range: [%s %s]" % (peak[0], peak[1]))
if not self.roi_background == [0,0]:
bck_range = copy.copy(self.roi_background)
# Background
if self.use_tight_bck:
bck_range = [int(max(0.0, peak[0]-self.bck_offset)), int(min(NX_PIXELS, peak[1]+self.bck_offset))]
elif self.use_roi_bck:
bck_range = [int(max(0.0, peak[0]-2*self.bck_offset)), int(max(0.0, peak[0]-self.bck_offset))]
else:
bck_range = self.background
# Store the information we found
self.peak_position = (peak[1]+peak[0])/2.0
self.peak_range = [int(max(0, peak[0])), int(min(peak[1], NX_PIXELS))]
self.low_res_range = [int(max(0, low_res[0])), int(min(low_res[1], NY_PIXELS))]
self.background = [int(max(0, bck_range[0])), int(min(bck_range[1], NY_PIXELS))]
# Computed scattering angle
self.calculated_scattering_angle = api.MRGetTheta(ws, SpecularPixel=self.peak_position)
self.calculated_scattering_angle *= 180.0 / math.pi
# Determine whether we have a direct beam
run_object = ws.getRun()
try:
self.is_direct_beam = run_object.getProperty("data_type").value[0] == 1
self.data_type = 0 if self.is_direct_beam else 1
except:
self.is_direct_beam = False
self.data_type = 1
def chi2(data, model):
""" Returns the chi^2 for a data set and model pair """
err = np.fabs(data)
err[err<=0] = 1
return np.sum((data - model)**2 / err) / len(data)
class Fitter2(object):
DEAD_PIXELS = 10
def __init__(self, workspace):
self.workspace = workspace
self._prepare_data()
def _prepare_data(self):
"""
Read in the data and create arrays for fitting
"""
# Prepare data to fit
self.n_x = int(self.workspace.getInstrument().getNumberParameter("number-of-x-pixels")[0])
self.n_y = int(self.workspace.getInstrument().getNumberParameter("number-of-y-pixels")[0])
_integrated = api.Integration(InputWorkspace=self.workspace)
signal = _integrated.extractY()
self.z=np.reshape(signal, (self.n_x, self.n_y))
self.y = np.arange(0, self.n_y)[self.DEAD_PIXELS:-self.DEAD_PIXELS]
# 1D data x/y vs counts
self.x_vs_counts = np.sum(self.z, 1)
self.y_vs_counts = np.sum(self.z, 0)
self.guess_x = np.argmax(self.x_vs_counts)
self.guess_wx = 6.
def _scan_peaks(self):
f1 = ndimage.gaussian_filter(self.x_vs_counts, 3)
peaks, _ = find_peaks(f1)
prom, _, _ = peak_prominences(f1, peaks)
peaks_w, _, _, _ = peak_widths(f1, peaks)
# The quality factor is the size of the peak (height*width) multiply by
# a factor that peaks in the middle of the detector, where the peak usually is.
nx = 304.
delta = 100.
mid_point = 150.
quality_pos = np.exp(-(mid_point-peaks)**2./2000.)
low_peaks = peaks<delta
high_peaks = peaks>nx-delta
quality_pos[low_peaks] = quality_pos[low_peaks] * (1 - np.abs(delta-peaks[low_peaks])/delta)**3
quality_pos[high_peaks] = quality_pos[high_peaks] * (1 - np.abs(nx-delta-peaks[high_peaks])/delta)**3
quality = -peaks_w * prom * quality_pos
zipped = zip(peaks, peaks_w, quality, prom)
ordered = sorted(zipped, key=lambda a:a[2])
found_peaks = [p[0] for p in ordered]
if found_peaks:
# self.guess_x = ordered[0][0]
# self.guess_ws = ordered[0][1]
i_final = 0
if len(ordered)>1 and (ordered[0][2] - ordered[1][2])/ordered[0][2] < 0.75 and ordered[1][0] < ordered[0][0]:
i_final = 1
self.guess_x = ordered[i_final][0]
self.guess_ws = ordered[i_final][1]
return found_peaks
def fit_2d_peak(self):
""" Backward compatibility """
spec_peak = self.fit_peak()
beam_peak = self.fit_beam_width()
return spec_peak, beam_peak
def fit_peak(self):
self.peaks = self._scan_peaks()
# Package the best results
x_min = max(0, int(self.guess_x-np.fabs(self.guess_wx)))
x_max = min(self.n_x-1, int(self.guess_x+np.fabs(self.guess_wx)))
return [x_min, x_max]
def gaussian_1d(self, value, *p):
"""
1D Gaussian
"""
A, center_x, width_x, background = p
A = np.abs(A)
values = A*np.exp(-(value-center_x)**2/(2.*width_x**2))
values += background
return values
def peak_derivative(self, value, *p):
"""
Double Gaussian to fit the first derivative of a plateau/peak.
"""
A, center_x, width_x, edge_width, background = p
mu_right = center_x + width_x / 2.0
mu_left = center_x - width_x / 2.0
A = np.abs(A)
values = A*np.exp(-(value-mu_left)**2/(2.*edge_width**2)) - A*np.exp(-(value-mu_right)**2/(2.*edge_width**2))
values += background
return values
def _perform_beam_fit(self, y_d, derivative, derivative_err, y_r=None, signal_r=None, gaussian_first=False):
if gaussian_first:
_running_err = np.sqrt(signal_r)
_gauss, _ = opt.curve_fit(self.gaussian_1d, y_r,
signal_r, p0=[np.max(signal_r), 140, 50, 0], sigma=_running_err)
p0 = [np.max(derivative), _gauss[1], 2.0*_gauss[2], 5, 0]
else:
p0 = [np.max(derivative), 140, 60, 5, 0]
#p = A, center_x, width_x, edge_width, background
_coef, _ = opt.curve_fit(self.peak_derivative, y_d, derivative, p0=p0, sigma=derivative_err)
return _coef
def fit_beam_width(self):
"""
Fit the data distribution in y and get its range.
"""
peak_min = 0
peak_max = self.n_x
try:
_integral = [np.sum(self.y_vs_counts[:i]) for i in range(len(self.y_vs_counts))]
_running = 0.1*np.convolve(self.y_vs_counts, np.ones(10), mode='valid')
_deriv = np.asarray([_running[i+1]-_running[i] for i in range(len(_running)-1)])
_deriv_err = np.sqrt(_running)[:-1]
_deriv_err[_deriv_err<1] = 1
_y = np.arange(len(self.y_vs_counts))[5:-5]
_coef = self._perform_beam_fit(_y, _deriv, _deriv_err, gaussian_first=False)
peak_min = _coef[1] - np.abs(_coef[2])/2.0 - 2.0 * np.abs(_coef[3])
peak_max = _coef[1] + np.abs(_coef[2])/2.0 + 2.0 * np.abs(_coef[3])
if peak_max - peak_min < 10:
logging.error("Low statisting: trying again")
_y_running = self.y[5:-4]
_coef = self._perform_beam_fit(_y, _deriv, _deriv_err, _y_running, _running, gaussian_first=True)
self.guess_y = _coef[1]
self.guess_wy = (peak_max - peak_min) / 2.0
peak_min = max(peak_min, self.DEAD_PIXELS)
peak_max = min(peak_max, self.n_x-self.DEAD_PIXELS)
except:
logging.error("Could not fit the beam width: %s", sys.exc_value)
return [peak_min, peak_max]
| 39.899083
| 121
| 0.590423
|
12db84745394ce94d911a93f3780604a01ea9b78
| 325
|
py
|
Python
|
golpy/model/rules/example_rules.py
|
dkuska/golpy
|
a7bc73693090c252fa5ac587fe0d6c77472d9e9c
|
[
"MIT"
] | 1
|
2021-01-06T09:19:19.000Z
|
2021-01-06T09:19:19.000Z
|
golpy/model/rules/example_rules.py
|
dkuska/golpy
|
a7bc73693090c252fa5ac587fe0d6c77472d9e9c
|
[
"MIT"
] | null | null | null |
golpy/model/rules/example_rules.py
|
dkuska/golpy
|
a7bc73693090c252fa5ac587fe0d6c77472d9e9c
|
[
"MIT"
] | null | null | null |
""" https://www.conwaylife.com/wiki/List_of_Life-like_cellular_automata """
gol = "3/23"
gol_generations = "3/23/2"
seeds = "2/"
brians_brain = "2//3"
replicator = "B1357/S1357"
fredkin = "B1357/S02468"
live_free_or_die = "B2/S0"
life_without_death = "B3/S012345678"
highlife = "B36/S230"
day_and_night = "B3678/S34678"
| 19.117647
| 75
| 0.710769
|
ab9ced234870f04571cbaedbfd1483ce55d5be22
| 102
|
py
|
Python
|
hbot_dataset/targets/apps.py
|
CodeZeroAI/hbot-dataset
|
1b20a93e2c0fb9e2f8b887fefae68422b2c74efb
|
[
"MIT"
] | 1
|
2019-01-24T09:31:51.000Z
|
2019-01-24T09:31:51.000Z
|
hbot_dataset/targets/apps.py
|
CodeZeroAI/hbot-dataset
|
1b20a93e2c0fb9e2f8b887fefae68422b2c74efb
|
[
"MIT"
] | null | null | null |
hbot_dataset/targets/apps.py
|
CodeZeroAI/hbot-dataset
|
1b20a93e2c0fb9e2f8b887fefae68422b2c74efb
|
[
"MIT"
] | null | null | null |
from django.apps import AppConfig
class TargetsConfig(AppConfig):
name = 'hbot_dataset.targets'
| 17
| 33
| 0.77451
|
3f308a11060723f183d92f0be5078d870303e5cb
| 22,610
|
py
|
Python
|
orderportal/form.py
|
SciLifeLab/OrderPortal
|
1fd737a694306eba06f290bf58b685929bd4389a
|
[
"MIT"
] | null | null | null |
orderportal/form.py
|
SciLifeLab/OrderPortal
|
1fd737a694306eba06f290bf58b685929bd4389a
|
[
"MIT"
] | null | null | null |
orderportal/form.py
|
SciLifeLab/OrderPortal
|
1fd737a694306eba06f290bf58b685929bd4389a
|
[
"MIT"
] | null | null | null |
"Forms are templates for orders."
from __future__ import print_function, absolute_import
import json
import logging
from collections import OrderedDict as OD
import tornado.web
from . import constants
from . import saver
from . import settings
from . import utils
from .fields import Fields
from .requesthandler import RequestHandler, ApiV1Mixin
class FormSaver(saver.Saver):
doctype = constants.FORM
def initialize(self):
super(FormSaver, self).initialize()
self.doc['fields'] = []
self.doc['ordinal'] = 0
def setup(self):
self.fields = Fields(self.doc)
def add_field(self):
identifier = self.rqh.get_argument('identifier')
if not constants.ID_RX.match(identifier):
raise ValueError('Invalid identifier.')
if self.rqh.get_argument('type') not in constants.TYPES:
raise ValueError('Invalid type.')
if identifier in self.fields:
raise ValueError('Identifier already exists.')
self.changed['fields'] = self.fields.add(identifier, self.rqh)
def update_field(self, identifier):
if identifier not in self.fields:
raise ValueError('No such field.')
self.changed['fields'] = self.fields.update(identifier, self.rqh)
def clone_fields(self, form):
"Clone all fields from the given form."
for field in form['fields']:
self.fields.clone(field)
self.changed['copied'] = u"from {0}".format(form['_id'])
def delete_field(self, identifier):
if identifier not in self.fields:
raise ValueError('No such field.')
self.fields.delete(identifier)
self.changed['fields'] = dict(identifier=identifier, action='deleted')
class FormMixin(object):
"Mixin providing various methods."
def are_fields_editable(self, form):
"Are the form fields editable? Checks status only."
return form['status'] == constants.PENDING
def check_fields_editable(self, form):
"Check if the form fields can be edited. Checks status only."
if not self.are_fields_editable(form):
raise ValueError('Form is not editable.')
def get_order_count(self, form):
"Return number of orders for the form."
view = self.db.view('order/form',
startkey=[form['_id']],
endkey=[form['_id'], constants.CEILING])
try:
return list(view)[0].value
except (TypeError, IndexError):
return 0
class Forms(FormMixin, RequestHandler):
"Forms list page."
@tornado.web.authenticated
def get(self):
self.check_admin()
view = self.db.view('form/modified', descending=True, include_docs=True)
title = 'Recent forms'
forms = [r.doc for r in view]
names = self.get_account_names()
counts = dict([(f['_id'], self.get_order_count(f))
for f in forms])
self.render('forms.html',
title=title,
forms=forms,
account_names=names,
order_counts=counts)
class Form(FormMixin, RequestHandler):
"Form page."
@tornado.web.authenticated
def get(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
self.render('form.html',
form=form,
order_count=self.get_order_count(form),
fields=Fields(form),
is_deletable=self.is_deletable(form),
are_fields_editable=self.are_fields_editable(form),
logs=self.get_logs(form['_id']))
@tornado.web.authenticated
def post(self, iuid):
self.check_admin()
if self.get_argument('_http_method', None) == 'delete':
self.delete(iuid)
return
raise tornado.web.HTTPError(
405, reason='Internal problem; POST only allowed for DELETE.')
@tornado.web.authenticated
def delete(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
if not self.is_deletable(form):
self.see_other('form', form['_id'],
error='Form cannot be deleted.')
return
self.delete_logs(form['_id'])
self.db.delete(form)
self.see_other('forms')
def is_deletable(self, form):
"Can the form be deleted?."
if form['status'] == constants.PENDING: return True
if form['status'] == constants.ENABLED: return False
if self.get_order_count(form) == 0: return True
return False
class FormApiV1(ApiV1Mixin, Form):
"Form API; JSON."
def render(self, templatefilename, **kwargs):
URL = self.absolute_reverse_url
form = kwargs['form']
data = OD()
data['type'] = 'form'
data['iuid'] = form['_id']
data['title'] = form['title']
data['version'] = form.get('version')
data['description'] = form.get('description')
data['instruction'] = form.get('instruction')
data['owner'] = dict(
email=form['owner'],
links=dict(api=dict(href=URL('account_api', form['owner'])),
display=dict(href=URL('account', form['owner']))))
data['status'] = form['status']
data['modified'] = form['modified']
data['created'] = form['created']
data['links'] = dict(api=dict(href=URL('form_api', form['_id'])),
display=dict(href=URL('form', form['_id'])))
data['orders'] = dict(
count=self.get_order_count(form),
# XXX Add API href when available.
display=dict(href=URL('form_orders', form['_id'])))
data['fields'] = form['fields']
self.write(data)
class FormLogs(RequestHandler):
"Form log entries page."
@tornado.web.authenticated
def get(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
self.render('logs.html',
title=u"Logs for form '{0}'".format(form['title']),
entity=form,
logs=self.get_logs(form['_id']))
class FormCreate(RequestHandler):
"Page for creating an form. Allows for importing fields from form JSON."
@tornado.web.authenticated
def get(self):
self.check_admin()
self.render('form_create.html')
@tornado.web.authenticated
def post(self):
self.check_admin()
with FormSaver(rqh=self) as saver:
saver['title'] = self.get_argument('title')
if not saver['title']:
self.see_other('forms', error='No title given.')
return
saver['version'] = self.get_argument('version', None)
saver['description'] = self.get_argument('description', None)
saver['instruction'] = self.get_argument('instruction', None)
saver['status'] = constants.PENDING
try:
infile = self.request.files['import'][0]
# This throws exceptions if not JSON
data = json.loads(infile.body)
if data.get(constants.DOCTYPE) != constants.FORM and \
data.get('type') != 'form':
raise ValueError('Imported JSON is not a form.')
except (KeyError, IndexError):
pass
except Exception, msg:
self.see_other('home', error="Error importing form: %s" % msg)
return
else:
if not saver['version']:
saver['version'] = data.get('version')
if not saver['description']:
saver['description'] = data.get('description')
if not saver['instruction']:
saver['instruction'] = data.get('instruction')
saver['fields'] = data['fields']
self.see_other('form', saver.doc['_id'])
class FormEdit(FormMixin, RequestHandler):
"Page for editing an form; title, version, description, instruction."
@tornado.web.authenticated
def get(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
self.render('form_edit.html',
title=u"Edit form '{0}'".format(form['title']),
form=form)
@tornado.web.authenticated
def post(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
with FormSaver(doc=form, rqh=self) as saver:
saver['title'] = self.get_argument('title')
saver['version'] = self.get_argument('version', None)
saver['description'] = self.get_argument('description', None)
saver['instruction'] = self.get_argument('instruction', None)
try:
saver['ordinal'] = int(self.get_argument('ordinal', 0))
except (ValueError, TypeError):
pass
self.see_other('form', form['_id'])
class FormFieldCreate(FormMixin, RequestHandler):
"Page for creating a field in a form."
@tornado.web.authenticated
def get(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
try:
self.check_fields_editable(form)
except ValueError, msg:
self.see_other('form', form['_id'], error=str(msg))
return
# Get existing field identifiers
identifiers = set()
for row in self.db.view('form/enabled', include_docs=True):
identifiers.update(self._get_identifiers(row.doc['fields']))
identifiers.difference_update(self._get_identifiers(form['fields']))
self.render('field_create.html',
title=u"Create field in form '{0}'".format(form['title']),
form=form,
fields=Fields(form),
identifiers=identifiers)
def _get_identifiers(self, fields):
result = set()
for field in fields:
result.add(field['identifier'])
try:
result.update(self._get_identifiers(field['fields']))
except KeyError:
pass
return result
@tornado.web.authenticated
def post(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
try:
self.check_fields_editable(form)
except ValueError, msg:
self.see_other('form', form['_id'], error=str(msg))
return
try:
with FormSaver(doc=form, rqh=self) as saver:
saver.add_field()
except ValueError, msg:
self.see_other('form', form['_id'], error=str(msg))
else:
self.see_other('form', form['_id'])
class FormFieldEdit(FormMixin, RequestHandler):
"Page for editing or deleting a field in a form."
@tornado.web.authenticated
def get(self, iuid, identifier):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
try:
self.check_fields_editable(form)
except ValueError, msg:
self.see_other('form', form['_id'], error=str(msg))
return
fields = Fields(form)
try:
field = fields[identifier]
except KeyError:
self.see_other('form', form['_id'], error='No such field.')
return
self.render('field_edit.html',
form=form,
field=field,
fields=fields,
siblings=fields.get_siblings(field, form['fields']),
alt_parents=fields.get_alt_parents(field))
@tornado.web.authenticated
def post(self, iuid, identifier):
if self.get_argument('_http_method', None) == 'delete':
self.delete(iuid, identifier)
return
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
try:
self.check_fields_editable(form)
except ValueError, msg:
self.see_other('form', form['_id'], error=str(msg))
return
try:
with FormSaver(doc=form, rqh=self) as saver:
saver.update_field(identifier)
except ValueError, msg:
self.see_other('form', form['_id'], error=str(msg))
else:
self.see_other('form', form['_id'])
@tornado.web.authenticated
def delete(self, iuid, identifier):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
try:
self.check_fields_editable(form)
except ValueError, msg:
self.see_other('form', form['_id'], error=str(msg))
return
try:
with FormSaver(doc=form, rqh=self) as saver:
saver.delete_field(identifier)
except ValueError, msg:
self.see_other('form', form['_id'], error=str(msg))
else:
self.see_other('form', form['_id'])
class FormFieldEditDescr(FormMixin, RequestHandler):
"""Edit the label, clone erase, description of a form field.
This is allowed also for enabled forms."""
@tornado.web.authenticated
def post(self, iuid, identifier):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
with FormSaver(doc=form, rqh=self) as saver:
name = "{0}/label".format(identifier)
saver.fields[identifier]['label'] = self.get_argument(name, '')
name = "{0}/initial_display".format(identifier)
saver.fields[identifier]['initial_display'] = \
utils.to_bool(self.get_argument(name, False))
name = "{0}/erase_on_clone".format(identifier)
saver.fields[identifier]['erase_on_clone'] = \
utils.to_bool(self.get_argument(name, False))
name = "{0}/descr".format(identifier)
saver.fields[identifier]['description'] = self.get_argument(name,'')
self.see_other('form', form['_id'])
class FormClone(RequestHandler):
"Make a clone of a form."
@tornado.web.authenticated
def post(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
with FormSaver(rqh=self) as saver:
saver['title'] = u"Clone of {0}".format(form['title'])
saver['version'] = form.get('version')
saver['description'] = form.get('description')
saver['instruction'] = form.get('instruction')
saver.clone_fields(form)
saver['status'] = constants.PENDING
self.see_other('form_edit', saver.doc['_id'])
class FormPending(RequestHandler):
"""Change status from testing to pending.
To allow editing after testing.
All test orders for this form are deleted."""
@tornado.web.authenticated
def post(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
if form['status'] != constants.TESTING:
raise ValueError('Form does not have status testing.')
with FormSaver(doc=form, rqh=self) as saver:
saver['status'] = constants.PENDING
view = self.db.view('order/form',
reduce=False,
startkey=[form['_id']],
endkey=[form['_id'], constants.CEILING])
for row in view:
self.delete_logs(row.id)
del self.db[row.id]
self.see_other('form', iuid)
class FormTesting(RequestHandler):
"""Change status from pending to testing.
To allow testing making orders from the form."""
@tornado.web.authenticated
def post(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
if form['status'] != constants.PENDING:
raise ValueError('Form does not have status pending.')
with FormSaver(doc=form, rqh=self) as saver:
saver['status'] = constants.TESTING
self.see_other('form', iuid)
class FormEnable(RequestHandler):
"""Change status from pending to enabled.
Allows users to make orders from the form."""
@tornado.web.authenticated
def post(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
if form['status'] == constants.PENDING:
with FormSaver(doc=form, rqh=self) as saver:
if not form.get('version'):
saver['version'] = utils.today()
saver['status'] = constants.ENABLED
self.see_other('form', iuid)
class FormDisable(RequestHandler):
"""Change status from enabled to disabled.
Disable making orders from the form."""
@tornado.web.authenticated
def post(self, iuid):
self.check_admin()
form = self.get_entity(iuid, doctype=constants.FORM)
if form['status'] == constants.ENABLED:
with FormSaver(doc=form, rqh=self) as saver:
saver['status'] = constants.DISABLED
self.see_other('form', iuid)
class FormOrders(RequestHandler):
"Page for a list of all orders for a given form."
@tornado.web.authenticated
def get(self, iuid):
self.check_staff()
form = self.get_entity(iuid, doctype=constants.FORM)
view = self.db.view('order/form',
reduce=False,
include_docs=True,
descending=True,
startkey=[iuid, constants.CEILING],
endkey=[iuid])
orders = [r.doc for r in view]
account_names = self.get_account_names()
self.render('form_orders.html',
form=form,
orders=orders,
account_names=account_names)
class FormOrdersAggregate(RequestHandler):
"Aggregate data from all orders for the form into a CSV file."
TITLES = dict(_id='Order IUID',
email= 'Owner email')
@tornado.web.authenticated
def get(self, iuid):
self.check_staff()
form = self.get_entity(iuid, doctype=constants.FORM)
fields = Fields(form).flatten()
# Remove group fields
fields = [f for f in fields if f['type'] != constants.GROUP]
# Split out table fields
table_fields = [f for f in fields if f['type'] == constants.TABLE]
fields = [f for f in fields if f['type'] != constants.TABLE]
self.render('form_orders_aggregate.html', form=form,
fields=fields, table_fields=table_fields)
@tornado.web.authenticated
def post(self, iuid):
self.check_staff()
form = self.get_entity(iuid, doctype=constants.FORM)
order_fields = self.get_arguments('order')
if not ('iuid' in order_fields or 'identifier' in order_fields):
self.see_other('form_orders_aggregate', form['_id'],
error='IUID or identifier must be included.')
return
history_fields = self.get_arguments('history')
owner_fields = self.get_arguments('owner')
data_fields = self.get_arguments('fields')
table_field = self.get_argument('table_field', None)
if table_field:
table_field = Fields(form)[table_field]
colids = [utils.parse_field_table_column(c)['identifier']
for c in table_field['table']]
file_format = self.get_argument('file_format', 'xlsx').lower()
if file_format == 'xlsx':
writer = utils.XlsxWriter('Aggregate')
elif file_format == 'csv':
writer = utils.CsvWriter()
else:
raise tornado.web.HTTPError(404, reason='unknown file format')
header = [self.TITLES.get(f, f.capitalize()) for f in order_fields]
header.extend(history_fields)
header.extend([self.TITLES.get(f,f.capitalize()) for f in owner_fields])
header.extend(data_fields)
if table_field:
header.extend(["%s: %s" % (table_field['identifier'], ci)
for ci in colids])
writer.writerow(header)
account_lookup = {}
# Get all orders for the given form.
view = self.db.view('order/form',
reduce=False,
include_docs=True,
descending=True,
startkey=[iuid, constants.CEILING],
endkey=[iuid])
orders = [r.doc for r in view]
# Filter by statuses, if any given
statuses = self.get_arguments('status')
if statuses and statuses != ['']:
statuses = set(statuses)
orders = [o for o in orders if o['status'] in statuses]
for order in orders:
row = [order.get(f) for f in order_fields]
row.extend([order['history'].get(s) or '' for s in history_fields])
if owner_fields:
try:
account = account_lookup[order['owner']]
except KeyError:
account = self.get_account(order['owner'])
account_lookup[order['owner']] = account
row.extend([account.get(f) for f in owner_fields])
for data_field in data_fields:
value = order['fields'].get(data_field)
if isinstance(value, list):
value = '|'.join(value)
row.append(value)
if table_field:
table = order['fields'].get(table_field['identifier']) or []
for tr in table:
writer.writerow(row + tr)
else:
writer.writerow(row)
self.write(writer.getvalue())
filename = (form['title'] or form['_id']).replace(' ', '_')
if table_field:
filename += '_' + table_field['identifier']
if file_format == 'xlsx':
self.set_header('Content-Type', constants.XLSX_MIME)
filename = filename + '.xlsx'
elif file_format == 'csv':
self.set_header('Content-Type', constants.CSV_MIME)
filename = filename + '.csv'
self.set_header('Content-Disposition',
'attachment; filename="orders_%s"' % filename)
| 37.55814
| 80
| 0.575763
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.