Upload folder using huggingface_hub (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- code/train/Python/0050467_test_scrubber.py +145 -0
- code/train/Python/0051088_test_utils.py +130 -0
- code/train/Python/0051246_utils.py +153 -0
- code/train/Python/0051270_calendars.py +147 -0
- code/train/Python/0051563_graphs.py +167 -0
- code/train/Python/0051716_test_socketserver.py +180 -0
- code/train/Python/0051801_train_cartpole_pg.py +258 -0
- code/train/Python/0052182_695._Max_Area_of_Island.py +55 -0
- code/train/Python/0052527_530.py +33 -0
- code/train/Python/0052648_plotAlphaSensitivity.py +78 -0
- code/train/Python/0052999_postfix2bdt.py +89 -0
- code/train/Python/0053127_Longest_consecutive_sequence.py +50 -0
- code/train/Python/0053169_utils.py +168 -0
- code/train/Python/0053206_teststep.py +183 -0
- code/train/Python/0053393_document.py +112 -0
- code/train/Python/0053584_test_pyregrid.py +162 -0
- code/train/Python/0053695_timeseries.py +140 -0
- code/train/Python/0054658_8.py +27 -0
- code/train/Python/0054760_vocaCreator.py +82 -0
- code/train/Python/0055295_shuffling.py +71 -0
- code/train/Python/0056031_pyrmEval.py +39 -0
- code/train/Python/0056597_test_study_get.py +141 -0
- code/train/Python/0057109_train_triplets.py +176 -0
- code/train/Python/0057194_summary.py +186 -0
- code/train/Python/0057882_Databases.py +221 -0
- code/train/Python/0057969_loading.py +109 -0
- code/train/Python/0058914_lists.py +103 -0
- code/train/Python/0059093_path.py +89 -0
- code/train/Python/0059516_ranzhi_advanced_tests.py +95 -0
- code/train/Python/0060131_plot_hyperparameter.py +178 -0
- code/train/Python/0060499_market_origin.py +92 -0
- code/train/Python/0060919_base.py +238 -0
- code/train/Python/0061284_answer.py +48 -0
- code/train/Python/0062850_hmi.py +281 -0
- code/train/Python/0062944_rnnlm-batch.py +148 -0
- code/train/Python/0063615_init__.py +165 -0
- code/train/Python/0063702_mass_path_distance.py +76 -0
- code/train/Python/0063710_parser_test.py +114 -0
- code/train/Python/0064061_accuracytest.py +165 -0
- code/train/Python/0065151_list1.py +102 -0
- code/train/Python/0065512_course_grade.py +209 -0
- code/train/Python/0065884_E4.py +43 -0
- code/train/Python/0066105_pascal_voc.py +173 -0
- code/train/Python/0066263_test_extensions.py +155 -0
- code/train/Python/0068007_utils.py +79 -0
- code/train/Python/0068360_462._Minimum_Moves_to_Equal_Array_Elements_II.py +40 -0
- code/train/Python/0069275_flotilla.py +201 -0
- code/train/Python/0069309_dsatur.py +87 -0
- code/train/Python/0070347_config.py +239 -0
- code/train/Python/0070419_config.py +177 -0
code/train/Python/0050467_test_scrubber.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Red Hat, Inc.
|
| 2 |
+
# All Rights Reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
| 5 |
+
# not use this file except in compliance with the License. You may obtain
|
| 6 |
+
# a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
| 12 |
+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
| 13 |
+
# License for the specific language governing permissions and limitations
|
| 14 |
+
# under the License.
|
| 15 |
+
|
| 16 |
+
import uuid
|
| 17 |
+
|
| 18 |
+
import eventlet
|
| 19 |
+
import glance_store
|
| 20 |
+
from mock import patch
|
| 21 |
+
from mox3 import mox
|
| 22 |
+
from oslo_config import cfg
|
| 23 |
+
# NOTE(jokke): simplified transition to py3, behaves like py2 xrange
|
| 24 |
+
from six.moves import range
|
| 25 |
+
|
| 26 |
+
from glance.common import exception
|
| 27 |
+
from glance import scrubber
|
| 28 |
+
from glance.tests import utils as test_utils
|
| 29 |
+
|
| 30 |
+
CONF = cfg.CONF
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestScrubber(test_utils.BaseTestCase):
|
| 34 |
+
|
| 35 |
+
def setUp(self):
|
| 36 |
+
super(TestScrubber, self).setUp()
|
| 37 |
+
glance_store.register_opts(CONF)
|
| 38 |
+
self.config(group='glance_store', default_store='file',
|
| 39 |
+
filesystem_store_datadir=self.test_dir)
|
| 40 |
+
glance_store.create_stores()
|
| 41 |
+
self.mox = mox.Mox()
|
| 42 |
+
|
| 43 |
+
def tearDown(self):
|
| 44 |
+
self.mox.UnsetStubs()
|
| 45 |
+
# These globals impact state outside of this test class, kill them.
|
| 46 |
+
scrubber._file_queue = None
|
| 47 |
+
scrubber._db_queue = None
|
| 48 |
+
super(TestScrubber, self).tearDown()
|
| 49 |
+
|
| 50 |
+
def _scrubber_cleanup_with_store_delete_exception(self, ex):
|
| 51 |
+
uri = 'file://some/path/%s' % uuid.uuid4()
|
| 52 |
+
id = 'helloworldid'
|
| 53 |
+
scrub = scrubber.Scrubber(glance_store)
|
| 54 |
+
scrub.registry = self.mox.CreateMockAnything()
|
| 55 |
+
scrub.registry.get_image(id).AndReturn({'status': 'pending_delete'})
|
| 56 |
+
scrub.registry.update_image(id, {'status': 'deleted'})
|
| 57 |
+
self.mox.StubOutWithMock(glance_store, "delete_from_backend")
|
| 58 |
+
glance_store.delete_from_backend(
|
| 59 |
+
uri,
|
| 60 |
+
mox.IgnoreArg()).AndRaise(ex)
|
| 61 |
+
self.mox.ReplayAll()
|
| 62 |
+
scrub._scrub_image(eventlet.greenpool.GreenPool(1),
|
| 63 |
+
id, [(id, '-', uri)])
|
| 64 |
+
self.mox.VerifyAll()
|
| 65 |
+
|
| 66 |
+
def test_store_delete_unsupported_backend_exception(self):
|
| 67 |
+
ex = glance_store.UnsupportedBackend()
|
| 68 |
+
self._scrubber_cleanup_with_store_delete_exception(ex)
|
| 69 |
+
|
| 70 |
+
def test_store_delete_notfound_exception(self):
|
| 71 |
+
ex = exception.NotFound()
|
| 72 |
+
self._scrubber_cleanup_with_store_delete_exception(ex)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class TestScrubDBQueue(test_utils.BaseTestCase):
|
| 76 |
+
|
| 77 |
+
def setUp(self):
|
| 78 |
+
super(TestScrubDBQueue, self).setUp()
|
| 79 |
+
|
| 80 |
+
def tearDown(self):
|
| 81 |
+
super(TestScrubDBQueue, self).tearDown()
|
| 82 |
+
|
| 83 |
+
def _create_image_list(self, count):
|
| 84 |
+
images = []
|
| 85 |
+
for x in range(count):
|
| 86 |
+
images.append({'id': x})
|
| 87 |
+
|
| 88 |
+
return images
|
| 89 |
+
|
| 90 |
+
def test_get_all_images(self):
|
| 91 |
+
scrub_queue = scrubber.ScrubDBQueue()
|
| 92 |
+
images = self._create_image_list(15)
|
| 93 |
+
image_pager = ImagePager(images)
|
| 94 |
+
|
| 95 |
+
def make_get_images_detailed(pager):
|
| 96 |
+
def mock_get_images_detailed(filters, marker=None):
|
| 97 |
+
return pager()
|
| 98 |
+
return mock_get_images_detailed
|
| 99 |
+
|
| 100 |
+
with patch.object(scrub_queue.registry, 'get_images_detailed') as (
|
| 101 |
+
_mock_get_images_detailed):
|
| 102 |
+
_mock_get_images_detailed.side_effect = (
|
| 103 |
+
make_get_images_detailed(image_pager))
|
| 104 |
+
actual = list(scrub_queue._get_all_images())
|
| 105 |
+
|
| 106 |
+
self.assertEqual(images, actual)
|
| 107 |
+
|
| 108 |
+
def test_get_all_images_paged(self):
|
| 109 |
+
scrub_queue = scrubber.ScrubDBQueue()
|
| 110 |
+
images = self._create_image_list(15)
|
| 111 |
+
image_pager = ImagePager(images, page_size=4)
|
| 112 |
+
|
| 113 |
+
def make_get_images_detailed(pager):
|
| 114 |
+
def mock_get_images_detailed(filters, marker=None):
|
| 115 |
+
return pager()
|
| 116 |
+
return mock_get_images_detailed
|
| 117 |
+
|
| 118 |
+
with patch.object(scrub_queue.registry, 'get_images_detailed') as (
|
| 119 |
+
_mock_get_images_detailed):
|
| 120 |
+
_mock_get_images_detailed.side_effect = (
|
| 121 |
+
make_get_images_detailed(image_pager))
|
| 122 |
+
actual = list(scrub_queue._get_all_images())
|
| 123 |
+
|
| 124 |
+
self.assertEqual(images, actual)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class ImagePager(object):
|
| 128 |
+
def __init__(self, images, page_size=0):
|
| 129 |
+
image_count = len(images)
|
| 130 |
+
if page_size == 0 or page_size > image_count:
|
| 131 |
+
page_size = image_count
|
| 132 |
+
self.image_batches = []
|
| 133 |
+
start = 0
|
| 134 |
+
l = len(images)
|
| 135 |
+
while start < l:
|
| 136 |
+
self.image_batches.append(images[start: start + page_size])
|
| 137 |
+
start += page_size
|
| 138 |
+
if (l - start) < page_size:
|
| 139 |
+
page_size = l - start
|
| 140 |
+
|
| 141 |
+
def __call__(self):
|
| 142 |
+
if len(self.image_batches) == 0:
|
| 143 |
+
return []
|
| 144 |
+
else:
|
| 145 |
+
return self.image_batches.pop(0)
|
code/train/Python/0051088_test_utils.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
# This file is part of pysenslog.
|
| 4 |
+
# Copyright 2015 Leonardo Rossi <leonardo.rossi@studenti.unipr.it>.
|
| 5 |
+
#
|
| 6 |
+
# pysenslog is free software: you can redistribute it and/or modify it under
|
| 7 |
+
# the terms of the GNU Lesser General Public License as published by the Free
|
| 8 |
+
# Software Foundation, either version 3 of the License, or (at your option) any
|
| 9 |
+
# later version.
|
| 10 |
+
#
|
| 11 |
+
# pysenslog is distributed in the hope that it will be useful, but WITHOUT ANY
|
| 12 |
+
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
|
| 13 |
+
# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
| 14 |
+
# details.
|
| 15 |
+
#
|
| 16 |
+
# You should have received a copy of the GNU Lesser General Public License
|
| 17 |
+
# along with pysenslog. If not, see <http://www.gnu.org/licenses/>.
|
| 18 |
+
|
| 19 |
+
"""Test utils."""
|
| 20 |
+
|
| 21 |
+
from __future__ import absolute_import, unicode_literals
|
| 22 |
+
|
| 23 |
+
from numpy import around, matrix, multiply, random
|
| 24 |
+
from pylocating.utils import _points_in_surface_sphere, \
|
| 25 |
+
generate_points_in_surface_sphere, distance, \
|
| 26 |
+
generate_points_random_in_surface_sphere, \
|
| 27 |
+
generate_sequential_points
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestUtils(object):
|
| 31 |
+
|
| 32 |
+
"""Test utils."""
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
def _check_points(radius, points, center=None):
|
| 36 |
+
"""Check points."""
|
| 37 |
+
square_radius = radius * radius
|
| 38 |
+
center = center if center is not None else matrix([0, 0, 0])
|
| 39 |
+
for point in points:
|
| 40 |
+
point = point - center
|
| 41 |
+
val = around(multiply(point, point).sum(), decimals=3)
|
| 42 |
+
assert val == square_radius
|
| 43 |
+
|
| 44 |
+
def test_point_in_surface_sphere(self):
|
| 45 |
+
"""Test point in surface sphere generation."""
|
| 46 |
+
points = _points_in_surface_sphere(num_of_points=256)
|
| 47 |
+
self._check_points(1, points)
|
| 48 |
+
|
| 49 |
+
def test_point_in_surface_sphere_1(self):
|
| 50 |
+
"""Test point in surface sphere generation."""
|
| 51 |
+
radius = 4
|
| 52 |
+
points = generate_points_in_surface_sphere(
|
| 53 |
+
center=matrix([0, 0, 0]), radius=radius, num_of_points=16)
|
| 54 |
+
self._check_points(radius, points)
|
| 55 |
+
|
| 56 |
+
def test_point_in_surface_sphere_2(self):
|
| 57 |
+
"""Test point in surface sphere generation."""
|
| 58 |
+
center = matrix([5, 6, 7])
|
| 59 |
+
radius = 1
|
| 60 |
+
points = generate_points_in_surface_sphere(
|
| 61 |
+
center=center, radius=radius, num_of_points=16)
|
| 62 |
+
self._check_points(radius, points, center=center)
|
| 63 |
+
|
| 64 |
+
def test_distance(self):
|
| 65 |
+
"""Test distance."""
|
| 66 |
+
for i in range(20):
|
| 67 |
+
point = matrix(random.random(3))
|
| 68 |
+
assert 0 == distance(point, point)
|
| 69 |
+
|
| 70 |
+
pa = matrix([5, 3, 4])
|
| 71 |
+
pb = matrix([10, 3, 4])
|
| 72 |
+
assert 5 == distance(pa, pb)
|
| 73 |
+
|
| 74 |
+
pa = matrix([5, 3, 4])
|
| 75 |
+
pb = matrix([5, 7, 4])
|
| 76 |
+
assert 4 == distance(pa, pb)
|
| 77 |
+
|
| 78 |
+
pa = matrix([5, 3, 4])
|
| 79 |
+
pb = matrix([5, 3, 11])
|
| 80 |
+
assert 7 == distance(pa, pb)
|
| 81 |
+
|
| 82 |
+
def test_generate_points_random_in_surface_sphere_1(self):
|
| 83 |
+
"""Test generate points random in surface sphere."""
|
| 84 |
+
center = matrix([0, 0, 0])
|
| 85 |
+
radius = 1
|
| 86 |
+
gen = generate_points_random_in_surface_sphere(center, radius)
|
| 87 |
+
points = []
|
| 88 |
+
for i in range(50):
|
| 89 |
+
points.append(next(gen))
|
| 90 |
+
self._check_points(radius, points, center)
|
| 91 |
+
|
| 92 |
+
def test_generate_points_random_in_surface_sphere_2(self):
|
| 93 |
+
"""Test generate points random in surface sphere."""
|
| 94 |
+
center = matrix([0, 0, 0])
|
| 95 |
+
radius = 55
|
| 96 |
+
gen = generate_points_random_in_surface_sphere(center, radius)
|
| 97 |
+
points = []
|
| 98 |
+
for i in range(50):
|
| 99 |
+
points.append(next(gen))
|
| 100 |
+
self._check_points(radius, points, center)
|
| 101 |
+
|
| 102 |
+
def test_generate_points_random_in_surface_sphere_3(self):
|
| 103 |
+
"""Test generate points random in surface sphere."""
|
| 104 |
+
center = matrix([45, -23, 67])
|
| 105 |
+
radius = 1
|
| 106 |
+
gen = generate_points_random_in_surface_sphere(center, radius)
|
| 107 |
+
points = []
|
| 108 |
+
for i in range(50):
|
| 109 |
+
points.append(next(gen))
|
| 110 |
+
self._check_points(radius, points, center)
|
| 111 |
+
|
| 112 |
+
def test_generate_points_random_in_surface_sphere_4(self):
|
| 113 |
+
"""Test generate points random in surface sphere."""
|
| 114 |
+
center = matrix([45, -23, 67])
|
| 115 |
+
radius = 43
|
| 116 |
+
gen = generate_points_random_in_surface_sphere(center, radius)
|
| 117 |
+
points = []
|
| 118 |
+
for i in range(50):
|
| 119 |
+
points.append(next(gen))
|
| 120 |
+
self._check_points(radius, points, center)
|
| 121 |
+
|
| 122 |
+
def test_generate_sequential_points(self):
|
| 123 |
+
"""Test generate sequential points."""
|
| 124 |
+
gen = generate_sequential_points(matrix([0, 0, 0]), random)
|
| 125 |
+
|
| 126 |
+
point = next(gen)
|
| 127 |
+
for i in range(30):
|
| 128 |
+
next_point = next(gen)
|
| 129 |
+
assert distance(point, next_point) < 0.87
|
| 130 |
+
point = next_point
|
code/train/Python/0051246_utils.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django.conf import settings
|
| 2 |
+
from django.utils.translation import ugettext as _
|
| 3 |
+
|
| 4 |
+
from datetime import datetime, timedelta
|
| 5 |
+
|
| 6 |
+
from .signals import willEvaluateAvailabilityForRange as rangeSignal
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def strfdate(date):
|
| 10 |
+
return date.strftime(settings.TIMESLOTS_DATE_FORMAT)
|
| 11 |
+
|
| 12 |
+
def strftime(time):
|
| 13 |
+
return time.strftime(settings.TIMESLOTS_TIME_FORMAT)
|
| 14 |
+
|
| 15 |
+
def strpdate(date):
|
| 16 |
+
return datetime.strptime(date, settings.TIMESLOTS_DATE_FORMAT).date()
|
| 17 |
+
|
| 18 |
+
def strptime(time):
|
| 19 |
+
return datetime.strptime(time, settings.TIMESLOTS_TIME_FORMAT).time()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
WEEKDAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def __get_timeslots(date, definition):
|
| 26 |
+
# Return timeslots for date given definition
|
| 27 |
+
if date < definition.valid:
|
| 28 |
+
raise ValueError('out of bounds')
|
| 29 |
+
if definition.until and date > definition.until:
|
| 30 |
+
raise ValueError('out of bounds')
|
| 31 |
+
|
| 32 |
+
from copy import copy
|
| 33 |
+
return copy(definition.timeslots[WEEKDAYS[date.weekday()]])
|
| 34 |
+
|
| 35 |
+
def __timeslots_generator(lbound, ubound, constraint):
|
| 36 |
+
|
| 37 |
+
definitions = constraint.definitions.filter(enabled=True)
|
| 38 |
+
|
| 39 |
+
# Select all definitions in the date rage
|
| 40 |
+
future_set = definitions.filter(valid__range=(lbound, ubound))
|
| 41 |
+
current = definitions.filter(valid__lt=lbound).order_by('-valid')[:1]
|
| 42 |
+
|
| 43 |
+
# Union of the current definition and all future definitions in the date
|
| 44 |
+
# range. The union operator | may set me up for all sorts of associativity
|
| 45 |
+
# problems. writing (current | future_set) throws AssertionError: Cannot
|
| 46 |
+
# combine queries once a slice has been taken
|
| 47 |
+
|
| 48 |
+
# There's no risk of getting duplicate rows, so I should be able to drop the
|
| 49 |
+
# call to distinct('id'). only PostgreSQL supports DISTINCT ON
|
| 50 |
+
|
| 51 |
+
# definitions = (future_set | current).distinct('id').order_by('valid')
|
| 52 |
+
definitions = (future_set | current).order_by('valid')
|
| 53 |
+
|
| 54 |
+
# Raise warnings if definitions is over- or underspecified
|
| 55 |
+
|
| 56 |
+
def timeslots(date):
|
| 57 |
+
final = None
|
| 58 |
+
for definition in definitions:
|
| 59 |
+
if definition.valid <= date:
|
| 60 |
+
final = definition
|
| 61 |
+
else:
|
| 62 |
+
break
|
| 63 |
+
return __get_timeslots(date, final) if final else None
|
| 64 |
+
|
| 65 |
+
return timeslots
|
| 66 |
+
|
| 67 |
+
def availability(lbound, ubound, constraint):
|
| 68 |
+
# I can load the entire queryset in one fould sweep here...
|
| 69 |
+
generator = __timeslots_generator(lbound, ubound, constraint)
|
| 70 |
+
|
| 71 |
+
# Take note of holidays
|
| 72 |
+
holidays = constraint.holidays.filter(date__range=(lbound, ubound))
|
| 73 |
+
|
| 74 |
+
# Allow signal listeners to register callback function
|
| 75 |
+
callbacks = rangeSignal.send(__name__, lbound=lbound, ubound=ubound, constraint=constraint)
|
| 76 |
+
|
| 77 |
+
for n in range((ubound-lbound).days):
|
| 78 |
+
date = lbound + timedelta(n)
|
| 79 |
+
# If date is a holiday, bail here
|
| 80 |
+
|
| 81 |
+
if holidays.filter(date=date).count() > 0:
|
| 82 |
+
data = {
|
| 83 |
+
'available' : False,
|
| 84 |
+
'status' : 'holiday',
|
| 85 |
+
'code' : 3,
|
| 86 |
+
# Replace with holiday message
|
| 87 |
+
'msg' : _("holiday"),
|
| 88 |
+
'timeslots' : [],
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
else:
|
| 92 |
+
timeslots = generator(date)
|
| 93 |
+
if timeslots:
|
| 94 |
+
# Allow signal handlers to update timeslots
|
| 95 |
+
for (receiver, callback) in callbacks:
|
| 96 |
+
try:
|
| 97 |
+
callback(date, timeslots)
|
| 98 |
+
except Exception as e:
|
| 99 |
+
import logging
|
| 100 |
+
l = logging.getLogger(__name__)
|
| 101 |
+
l.warning("willEvaluateAvailabilityForRange callback threw an exception.", extra=e)
|
| 102 |
+
# If final is empty then the date is fully booked...
|
| 103 |
+
final = [strftime(k) for (k, v) in timeslots.items() if v > 0]
|
| 104 |
+
data = {
|
| 105 |
+
'available' : True if final else False,
|
| 106 |
+
'status' : 'available' if final else 'fully booked',
|
| 107 |
+
'code' : 0 if final else 2,
|
| 108 |
+
'msg' : _("available") if final else _("fully booked"),
|
| 109 |
+
'timeslots' : final,
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
else:
|
| 113 |
+
data = {
|
| 114 |
+
'available' : False,
|
| 115 |
+
'status' : 'unavailable',
|
| 116 |
+
'code' : 1,
|
| 117 |
+
'msg' : _("unavailable"),
|
| 118 |
+
'timeslots' : [],
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
yield date, data
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def is_available(constraint, date, time):
|
| 125 |
+
# Not available if date is a holiday
|
| 126 |
+
if constraint.holidays.filter(date=date).count() > 0:
|
| 127 |
+
return False
|
| 128 |
+
|
| 129 |
+
# Create a timeslots generator for date only
|
| 130 |
+
generator = __timeslots_generator(date, date, constraint)
|
| 131 |
+
timeslots = generator(date)
|
| 132 |
+
if not timeslots:
|
| 133 |
+
return False
|
| 134 |
+
|
| 135 |
+
# I can reduce the size of timeslots to time (but my callback may throw a warning)
|
| 136 |
+
if time not in timeslots:
|
| 137 |
+
return False
|
| 138 |
+
timeslots = {time: timeslots[time]}
|
| 139 |
+
|
| 140 |
+
# Allow signal listeners to register callback function
|
| 141 |
+
callbacks = rangeSignal.send(__name__, lbound=date, ubound=date, constraint=constraint)
|
| 142 |
+
for (receiver, callback) in callbacks:
|
| 143 |
+
try:
|
| 144 |
+
callback(date, timeslots, supress_warnings=True)
|
| 145 |
+
except Exception as e:
|
| 146 |
+
import logging
|
| 147 |
+
l = logging.getLogger(__name__)
|
| 148 |
+
l.warning("willEvaluateAvailabilityForRange callback threw an exception.", extra=e)
|
| 149 |
+
|
| 150 |
+
if timeslots[time] < 1:
|
| 151 |
+
return False
|
| 152 |
+
|
| 153 |
+
return True
|
code/train/Python/0051270_calendars.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import unicode_literals
|
| 2 |
+
|
| 3 |
+
from django import http
|
| 4 |
+
from django.db import models
|
| 5 |
+
from django.contrib.databrowse.datastructures import EasyModel
|
| 6 |
+
from django.contrib.databrowse.sites import DatabrowsePlugin
|
| 7 |
+
from django.shortcuts import render_to_response
|
| 8 |
+
from django.utils.html import format_html, format_html_join
|
| 9 |
+
from django.utils.text import capfirst
|
| 10 |
+
from django.utils.encoding import force_unicode
|
| 11 |
+
from django.views.generic import dates
|
| 12 |
+
from django.utils import datetime_safe
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class DateViewMixin(object):
|
| 16 |
+
allow_empty = False
|
| 17 |
+
allow_future = True
|
| 18 |
+
root_url = None
|
| 19 |
+
model = None
|
| 20 |
+
field = None
|
| 21 |
+
|
| 22 |
+
def get_context_data(self, **kwargs):
|
| 23 |
+
context = super(DateViewMixin, self).get_context_data(**kwargs)
|
| 24 |
+
context.update({
|
| 25 |
+
'root_url': self.root_url,
|
| 26 |
+
'model': self.model,
|
| 27 |
+
'field': self.field
|
| 28 |
+
})
|
| 29 |
+
return context
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class DayView(DateViewMixin, dates.DayArchiveView):
|
| 33 |
+
template_name = 'databrowse/calendar_day.html'
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class MonthView(DateViewMixin, dates.MonthArchiveView):
|
| 37 |
+
template_name = 'databrowse/calendar_month.html'
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class YearView(DateViewMixin, dates.YearArchiveView):
|
| 41 |
+
template_name = 'databrowse/calendar_year.html'
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class IndexView(DateViewMixin, dates.ArchiveIndexView):
|
| 45 |
+
template_name = 'databrowse/calendar_main.html'
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class CalendarPlugin(DatabrowsePlugin):
|
| 49 |
+
def __init__(self, field_names=None):
|
| 50 |
+
self.field_names = field_names
|
| 51 |
+
|
| 52 |
+
def field_dict(self, model):
|
| 53 |
+
"""
|
| 54 |
+
Helper function that returns a dictionary of all DateFields or
|
| 55 |
+
DateTimeFields in the given model. If self.field_names is set, it takes
|
| 56 |
+
take that into account when building the dictionary.
|
| 57 |
+
"""
|
| 58 |
+
if self.field_names is None:
|
| 59 |
+
return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField)])
|
| 60 |
+
else:
|
| 61 |
+
return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField) and f.name in self.field_names])
|
| 62 |
+
|
| 63 |
+
def model_index_html(self, request, model, site):
|
| 64 |
+
fields = self.field_dict(model)
|
| 65 |
+
if not fields:
|
| 66 |
+
return ''
|
| 67 |
+
return format_html('<p class="filter"><strong>View calendar by:</strong> {0}</p>',
|
| 68 |
+
format_html_join(', ', '<a href="calendars/{0}/">{1}</a>',
|
| 69 |
+
((f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values())))
|
| 70 |
+
|
| 71 |
+
def urls(self, plugin_name, easy_instance_field):
|
| 72 |
+
if isinstance(easy_instance_field.field, models.DateField):
|
| 73 |
+
d = easy_instance_field.raw_value
|
| 74 |
+
return ['%s%s/%s/%s/%s/%s/' % (
|
| 75 |
+
easy_instance_field.model.url(),
|
| 76 |
+
plugin_name, easy_instance_field.field.name,
|
| 77 |
+
str(d.year),
|
| 78 |
+
datetime_safe.new_date(d).strftime('%b').lower(),
|
| 79 |
+
d.day)]
|
| 80 |
+
|
| 81 |
+
def model_view(self, request, model_databrowse, url):
|
| 82 |
+
self.model, self.site = model_databrowse.model, model_databrowse.site
|
| 83 |
+
self.fields = self.field_dict(self.model)
|
| 84 |
+
|
| 85 |
+
# If the model has no DateFields, there's no point in going further.
|
| 86 |
+
if not self.fields:
|
| 87 |
+
raise http.Http404('The requested model has no calendars.')
|
| 88 |
+
|
| 89 |
+
if url is None:
|
| 90 |
+
return self.homepage_view(request)
|
| 91 |
+
url_bits = url.split('/')
|
| 92 |
+
if url_bits[0] in self.fields:
|
| 93 |
+
return self.calendar_view(request, self.fields[url_bits[0]], *url_bits[1:])
|
| 94 |
+
|
| 95 |
+
raise http.Http404('The requested page does not exist.')
|
| 96 |
+
|
| 97 |
+
def homepage_view(self, request):
|
| 98 |
+
easy_model = EasyModel(self.site, self.model)
|
| 99 |
+
field_list = self.fields.values()
|
| 100 |
+
field_list.sort(key=lambda k:k.verbose_name)
|
| 101 |
+
return render_to_response('databrowse/calendar_homepage.html', {
|
| 102 |
+
'root_url': self.site.root_url,
|
| 103 |
+
'model': easy_model,
|
| 104 |
+
'field_list': field_list
|
| 105 |
+
})
|
| 106 |
+
|
| 107 |
+
def calendar_view(self, request, field, year=None, month=None, day=None):
|
| 108 |
+
easy_model = EasyModel(self.site, self.model)
|
| 109 |
+
root_url = self.site.root_url
|
| 110 |
+
|
| 111 |
+
if day is not None:
|
| 112 |
+
return DayView.as_view(
|
| 113 |
+
year=year, month=month, day=day,
|
| 114 |
+
date_field=field.name,
|
| 115 |
+
queryset=easy_model.get_query_set(),
|
| 116 |
+
root_url=root_url,
|
| 117 |
+
model=easy_model,
|
| 118 |
+
field=field
|
| 119 |
+
)(request)
|
| 120 |
+
elif month is not None:
|
| 121 |
+
return MonthView.as_view(
|
| 122 |
+
year=year, month=month,
|
| 123 |
+
date_field=field.name,
|
| 124 |
+
queryset=easy_model.get_query_set(),
|
| 125 |
+
root_url=root_url,
|
| 126 |
+
model=easy_model,
|
| 127 |
+
field=field
|
| 128 |
+
)(request)
|
| 129 |
+
elif year is not None:
|
| 130 |
+
return YearView.as_view(
|
| 131 |
+
year=year,
|
| 132 |
+
date_field=field.name,
|
| 133 |
+
queryset=easy_model.get_query_set(),
|
| 134 |
+
root_url=root_url,
|
| 135 |
+
model=easy_model,
|
| 136 |
+
field=field
|
| 137 |
+
)(request)
|
| 138 |
+
else:
|
| 139 |
+
return IndexView.as_view(
|
| 140 |
+
date_field=field.name,
|
| 141 |
+
queryset=easy_model.get_query_set(),
|
| 142 |
+
root_url=root_url,
|
| 143 |
+
model=easy_model,
|
| 144 |
+
field=field
|
| 145 |
+
)(request)
|
| 146 |
+
|
| 147 |
+
assert False, ('%s, %s, %s, %s' % (field, year, month, day))
|
code/train/Python/0051563_graphs.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -----------------------------------------------------------------------------
|
| 2 |
+
# Name: graphs.py (part of PyGMI)
|
| 3 |
+
#
|
| 4 |
+
# Author: Patrick Cole
|
| 5 |
+
# E-Mail: pcole@geoscience.org.za
|
| 6 |
+
#
|
| 7 |
+
# Copyright: (c) 2019 Council for Geoscience
|
| 8 |
+
# Licence: GPL-3.0
|
| 9 |
+
#
|
| 10 |
+
# This file is part of PyGMI
|
| 11 |
+
#
|
| 12 |
+
# PyGMI is free software: you can redistribute it and/or modify
|
| 13 |
+
# it under the terms of the GNU General Public License as published by
|
| 14 |
+
# the Free Software Foundation, either version 3 of the License, or
|
| 15 |
+
# (at your option) any later version.
|
| 16 |
+
#
|
| 17 |
+
# PyGMI is distributed in the hope that it will be useful,
|
| 18 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 19 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 20 |
+
# GNU General Public License for more details.
|
| 21 |
+
#
|
| 22 |
+
# You should have received a copy of the GNU General Public License
|
| 23 |
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
| 24 |
+
# -----------------------------------------------------------------------------
|
| 25 |
+
"""Plot Vector Data using Matplotlib."""
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
from PyQt5 import QtWidgets, QtCore
|
| 29 |
+
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
|
| 30 |
+
from matplotlib.figure import Figure
|
| 31 |
+
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
|
| 32 |
+
import segyio
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class GraphWindow(QtWidgets.QDialog):
|
| 36 |
+
"""Graph Window - Main QT Dialog class for graphs."""
|
| 37 |
+
|
| 38 |
+
def __init__(self, parent=None):
|
| 39 |
+
super().__init__(parent)
|
| 40 |
+
self.parent = parent
|
| 41 |
+
|
| 42 |
+
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
|
| 43 |
+
self.setWindowTitle('Graph Window')
|
| 44 |
+
|
| 45 |
+
vbl = QtWidgets.QVBoxLayout(self)
|
| 46 |
+
self.mmc = MyMplCanvas(self)
|
| 47 |
+
mpl_toolbar = NavigationToolbar2QT(self.mmc, self.parent)
|
| 48 |
+
|
| 49 |
+
vbl.addWidget(self.mmc)
|
| 50 |
+
vbl.addWidget(mpl_toolbar)
|
| 51 |
+
|
| 52 |
+
self.setFocus()
|
| 53 |
+
|
| 54 |
+
def change_band(self):
|
| 55 |
+
"""
|
| 56 |
+
Combo box to choose band.
|
| 57 |
+
|
| 58 |
+
Returns
|
| 59 |
+
-------
|
| 60 |
+
None.
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class MyMplCanvas(FigureCanvasQTAgg):
|
| 66 |
+
"""
|
| 67 |
+
MPL Canvas class.
|
| 68 |
+
|
| 69 |
+
This routine will also allow the picking and movement of nodes of data.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, parent=None):
|
| 73 |
+
fig = Figure()
|
| 74 |
+
self.axes = fig.add_subplot(111)
|
| 75 |
+
self.line = None
|
| 76 |
+
self.ind = None
|
| 77 |
+
self.background = None
|
| 78 |
+
|
| 79 |
+
super().__init__(fig)
|
| 80 |
+
|
| 81 |
+
def update_segy(self, data):
|
| 82 |
+
"""
|
| 83 |
+
Update the plot from point data.
|
| 84 |
+
|
| 85 |
+
Parameters
|
| 86 |
+
----------
|
| 87 |
+
data : segyio object
|
| 88 |
+
SEG-Y data
|
| 89 |
+
|
| 90 |
+
Returns
|
| 91 |
+
-------
|
| 92 |
+
None.
|
| 93 |
+
|
| 94 |
+
"""
|
| 95 |
+
self.figure.clear()
|
| 96 |
+
|
| 97 |
+
ax1 = self.figure.add_subplot(111, label='SEG-Y')
|
| 98 |
+
|
| 99 |
+
ax1.set_title('SEG-Y')
|
| 100 |
+
self.axes = ax1
|
| 101 |
+
|
| 102 |
+
samplecnt = data.header[0][segyio.TraceField.TRACE_SAMPLE_COUNT]
|
| 103 |
+
sampleint = data.header[0][segyio.TraceField.TRACE_SAMPLE_INTERVAL]/1000.
|
| 104 |
+
rectime = samplecnt*sampleint
|
| 105 |
+
|
| 106 |
+
y = np.linspace(0, rectime, samplecnt)
|
| 107 |
+
start = 0
|
| 108 |
+
finish = samplecnt
|
| 109 |
+
offset = 0
|
| 110 |
+
gdist = 1 # in meters
|
| 111 |
+
tracemult = 2.
|
| 112 |
+
|
| 113 |
+
ax1.invert_yaxis()
|
| 114 |
+
|
| 115 |
+
tmax = -1
|
| 116 |
+
for trace in data.trace:
|
| 117 |
+
tmp = np.max(np.abs([trace.max(), trace.min()]))
|
| 118 |
+
if tmax < tmp:
|
| 119 |
+
tmax = tmp
|
| 120 |
+
tracemult = 1/tmax
|
| 121 |
+
|
| 122 |
+
for trace in data.trace:
|
| 123 |
+
x = tracemult*trace+offset
|
| 124 |
+
ax1.plot(x[start:finish], y[start:finish], 'k-')
|
| 125 |
+
|
| 126 |
+
ax1.fill_betweenx(y, offset, x, where=(x > offset), color='k')
|
| 127 |
+
|
| 128 |
+
ax1.set_xlabel('Trace Number')
|
| 129 |
+
ax1.set_ylabel('Time (ms)')
|
| 130 |
+
|
| 131 |
+
offset += gdist
|
| 132 |
+
|
| 133 |
+
self.figure.tight_layout()
|
| 134 |
+
self.figure.canvas.draw()
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class PlotSEGY(GraphWindow):
|
| 138 |
+
"""Plot SEG-Y Class."""
|
| 139 |
+
|
| 140 |
+
def __init__(self, parent=None):
|
| 141 |
+
super().__init__(parent)
|
| 142 |
+
self.indata = {}
|
| 143 |
+
self.parent = parent
|
| 144 |
+
|
| 145 |
+
def change_band(self):
|
| 146 |
+
"""
|
| 147 |
+
Combo to choose band.
|
| 148 |
+
|
| 149 |
+
Returns
|
| 150 |
+
-------
|
| 151 |
+
None.
|
| 152 |
+
|
| 153 |
+
"""
|
| 154 |
+
data = self.indata['ESEIS']
|
| 155 |
+
self.mmc.update_segy(data)
|
| 156 |
+
|
| 157 |
+
def run(self):
|
| 158 |
+
"""
|
| 159 |
+
Run.
|
| 160 |
+
|
| 161 |
+
Returns
|
| 162 |
+
-------
|
| 163 |
+
None.
|
| 164 |
+
|
| 165 |
+
"""
|
| 166 |
+
self.show()
|
| 167 |
+
self.change_band()
|
code/train/Python/0051716_test_socketserver.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Test suite for SocketServer.py
|
| 2 |
+
|
| 3 |
+
from test import test_support
|
| 4 |
+
from test.test_support import verbose, verify, TESTFN, TestSkipped
|
| 5 |
+
test_support.requires('network')
|
| 6 |
+
|
| 7 |
+
from SocketServer import *
|
| 8 |
+
import socket
|
| 9 |
+
import select
|
| 10 |
+
import time
|
| 11 |
+
import threading
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
NREQ = 3
|
| 15 |
+
DELAY = 0.5
|
| 16 |
+
|
| 17 |
+
class MyMixinHandler:
|
| 18 |
+
def handle(self):
|
| 19 |
+
time.sleep(DELAY)
|
| 20 |
+
line = self.rfile.readline()
|
| 21 |
+
time.sleep(DELAY)
|
| 22 |
+
self.wfile.write(line)
|
| 23 |
+
|
| 24 |
+
class MyStreamHandler(MyMixinHandler, StreamRequestHandler):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
class MyDatagramHandler(MyMixinHandler, DatagramRequestHandler):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
class MyMixinServer:
|
| 31 |
+
def serve_a_few(self):
|
| 32 |
+
for i in range(NREQ):
|
| 33 |
+
self.handle_request()
|
| 34 |
+
def handle_error(self, request, client_address):
|
| 35 |
+
self.close_request(request)
|
| 36 |
+
self.server_close()
|
| 37 |
+
raise
|
| 38 |
+
|
| 39 |
+
teststring = "hello world\n"
|
| 40 |
+
|
| 41 |
+
def receive(sock, n, timeout=20):
|
| 42 |
+
r, w, x = select.select([sock], [], [], timeout)
|
| 43 |
+
if sock in r:
|
| 44 |
+
return sock.recv(n)
|
| 45 |
+
else:
|
| 46 |
+
raise RuntimeError, "timed out on %r" % (sock,)
|
| 47 |
+
|
| 48 |
+
def testdgram(proto, addr):
|
| 49 |
+
s = socket.socket(proto, socket.SOCK_DGRAM)
|
| 50 |
+
s.sendto(teststring, addr)
|
| 51 |
+
buf = data = receive(s, 100)
|
| 52 |
+
while data and '\n' not in buf:
|
| 53 |
+
data = receive(s, 100)
|
| 54 |
+
buf += data
|
| 55 |
+
verify(buf == teststring)
|
| 56 |
+
s.close()
|
| 57 |
+
|
| 58 |
+
def teststream(proto, addr):
|
| 59 |
+
s = socket.socket(proto, socket.SOCK_STREAM)
|
| 60 |
+
s.connect(addr)
|
| 61 |
+
s.sendall(teststring)
|
| 62 |
+
buf = data = receive(s, 100)
|
| 63 |
+
while data and '\n' not in buf:
|
| 64 |
+
data = receive(s, 100)
|
| 65 |
+
buf += data
|
| 66 |
+
verify(buf == teststring)
|
| 67 |
+
s.close()
|
| 68 |
+
|
| 69 |
+
class ServerThread(threading.Thread):
|
| 70 |
+
def __init__(self, addr, svrcls, hdlrcls):
|
| 71 |
+
threading.Thread.__init__(self)
|
| 72 |
+
self.__addr = addr
|
| 73 |
+
self.__svrcls = svrcls
|
| 74 |
+
self.__hdlrcls = hdlrcls
|
| 75 |
+
def run(self):
|
| 76 |
+
class svrcls(MyMixinServer, self.__svrcls):
|
| 77 |
+
pass
|
| 78 |
+
if verbose: print "thread: creating server"
|
| 79 |
+
svr = svrcls(self.__addr, self.__hdlrcls)
|
| 80 |
+
if verbose: print "thread: serving three times"
|
| 81 |
+
svr.serve_a_few()
|
| 82 |
+
if verbose: print "thread: done"
|
| 83 |
+
|
| 84 |
+
seed = 0
|
| 85 |
+
def pickport():
|
| 86 |
+
global seed
|
| 87 |
+
seed += 1
|
| 88 |
+
return 10000 + (os.getpid() % 1000)*10 + seed
|
| 89 |
+
|
| 90 |
+
host = "localhost"
|
| 91 |
+
testfiles = []
|
| 92 |
+
def pickaddr(proto):
|
| 93 |
+
if proto == socket.AF_INET:
|
| 94 |
+
return (host, pickport())
|
| 95 |
+
else:
|
| 96 |
+
fn = TESTFN + str(pickport())
|
| 97 |
+
if os.name == 'os2':
|
| 98 |
+
# AF_UNIX socket names on OS/2 require a specific prefix
|
| 99 |
+
# which can't include a drive letter and must also use
|
| 100 |
+
# backslashes as directory separators
|
| 101 |
+
if fn[1] == ':':
|
| 102 |
+
fn = fn[2:]
|
| 103 |
+
if fn[0] in (os.sep, os.altsep):
|
| 104 |
+
fn = fn[1:]
|
| 105 |
+
fn = os.path.join('\socket', fn)
|
| 106 |
+
if os.sep == '/':
|
| 107 |
+
fn = fn.replace(os.sep, os.altsep)
|
| 108 |
+
else:
|
| 109 |
+
fn = fn.replace(os.altsep, os.sep)
|
| 110 |
+
testfiles.append(fn)
|
| 111 |
+
return fn
|
| 112 |
+
|
| 113 |
+
def cleanup():
|
| 114 |
+
for fn in testfiles:
|
| 115 |
+
try:
|
| 116 |
+
os.remove(fn)
|
| 117 |
+
except os.error:
|
| 118 |
+
pass
|
| 119 |
+
testfiles[:] = []
|
| 120 |
+
|
| 121 |
+
def testloop(proto, servers, hdlrcls, testfunc):
|
| 122 |
+
for svrcls in servers:
|
| 123 |
+
addr = pickaddr(proto)
|
| 124 |
+
if verbose:
|
| 125 |
+
print "ADDR =", addr
|
| 126 |
+
print "CLASS =", svrcls
|
| 127 |
+
t = ServerThread(addr, svrcls, hdlrcls)
|
| 128 |
+
if verbose: print "server created"
|
| 129 |
+
t.start()
|
| 130 |
+
if verbose: print "server running"
|
| 131 |
+
for i in range(NREQ):
|
| 132 |
+
time.sleep(DELAY)
|
| 133 |
+
if verbose: print "test client", i
|
| 134 |
+
testfunc(proto, addr)
|
| 135 |
+
if verbose: print "waiting for server"
|
| 136 |
+
t.join()
|
| 137 |
+
if verbose: print "done"
|
| 138 |
+
|
| 139 |
+
tcpservers = [TCPServer, ThreadingTCPServer]
|
| 140 |
+
if hasattr(os, 'fork') and os.name not in ('os2',):
|
| 141 |
+
tcpservers.append(ForkingTCPServer)
|
| 142 |
+
udpservers = [UDPServer, ThreadingUDPServer]
|
| 143 |
+
if hasattr(os, 'fork') and os.name not in ('os2',):
|
| 144 |
+
udpservers.append(ForkingUDPServer)
|
| 145 |
+
|
| 146 |
+
if not hasattr(socket, 'AF_UNIX'):
|
| 147 |
+
streamservers = []
|
| 148 |
+
dgramservers = []
|
| 149 |
+
else:
|
| 150 |
+
class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): pass
|
| 151 |
+
streamservers = [UnixStreamServer, ThreadingUnixStreamServer]
|
| 152 |
+
if hasattr(os, 'fork') and os.name not in ('os2',):
|
| 153 |
+
streamservers.append(ForkingUnixStreamServer)
|
| 154 |
+
class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): pass
|
| 155 |
+
dgramservers = [UnixDatagramServer, ThreadingUnixDatagramServer]
|
| 156 |
+
if hasattr(os, 'fork') and os.name not in ('os2',):
|
| 157 |
+
dgramservers.append(ForkingUnixDatagramServer)
|
| 158 |
+
|
| 159 |
+
def testall():
|
| 160 |
+
testloop(socket.AF_INET, tcpservers, MyStreamHandler, teststream)
|
| 161 |
+
testloop(socket.AF_INET, udpservers, MyDatagramHandler, testdgram)
|
| 162 |
+
if hasattr(socket, 'AF_UNIX'):
|
| 163 |
+
testloop(socket.AF_UNIX, streamservers, MyStreamHandler, teststream)
|
| 164 |
+
# Alas, on Linux (at least) recvfrom() doesn't return a meaningful
|
| 165 |
+
# client address so this cannot work:
|
| 166 |
+
##testloop(socket.AF_UNIX, dgramservers, MyDatagramHandler, testdgram)
|
| 167 |
+
|
| 168 |
+
def test_main():
|
| 169 |
+
import imp
|
| 170 |
+
if imp.lock_held():
|
| 171 |
+
# If the import lock is held, the threads will hang.
|
| 172 |
+
raise TestSkipped("can't run when import lock is held")
|
| 173 |
+
|
| 174 |
+
try:
|
| 175 |
+
testall()
|
| 176 |
+
finally:
|
| 177 |
+
cleanup()
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
test_main()
|
code/train/Python/0051801_train_cartpole_pg.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tensorflow as tf
|
| 2 |
+
import numpy as np
|
| 3 |
+
import random
|
| 4 |
+
import gym
|
| 5 |
+
import math
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
Vanilla Policy Gradient (PG)
|
| 10 |
+
|
| 11 |
+
- Sources of inspiration:
|
| 12 |
+
- https://github.com/kvfrans/openai-cartpole/blob/master/cartpole-policygradient.py
|
| 13 |
+
- http://kvfrans.com/simple-algoritms-for-solving-cartpole/
|
| 14 |
+
- https://github.com/awjuliani/DeepRL-Agents/blob/master/Vanilla-Policy.ipynb
|
| 15 |
+
- https://gist.github.com/greydanus/7cef68683ec955720ddde6b3edf8820e
|
| 16 |
+
- https://gist.github.com/cgnicholls/0127c885dbff07fde8dc1d7bfe62ac1a
|
| 17 |
+
- https://gist.github.com/mohakbhardwaj/1cebbf58d4c0627c9335d9b7eb55b803
|
| 18 |
+
- https://theneuralperspective.com/2016/11/26/1656/
|
| 19 |
+
- https://theneuralperspective.com/2016/11/25/reinforcement-learning-rl-policy-gradients-i/
|
| 20 |
+
- https://gist.github.com/cgnicholls/0127c885dbff07fde8dc1d7bfe62ac1a
|
| 21 |
+
- https://github.com/dennybritz/reinforcement-learning/tree/master/PolicyGradient
|
| 22 |
+
- https://github.com/dennybritz/reinforcement-learning/blob/master/PolicyGradient/CliffWalk%20REINFORCE%20with%20Baseline%20Solution.ipynb
|
| 23 |
+
|
| 24 |
+
- Paper: http://www-anw.cs.umass.edu/~barto/courses/cs687/williams92simple.pdf
|
| 25 |
+
- Pseudocode (vanilla PG):
|
| 26 |
+
1. Initialize policy (e.g. NNs) parameter $\theta$ and baseline $b$
|
| 27 |
+
2. For iteration=1,2,... do
|
| 28 |
+
2.1 Collect a set of trajectories by executing the current policy obtaining
|
| 29 |
+
$\mathbf{s}_{0:H},\mathbf{a}_{0:H},r_{0:H}$
|
| 30 |
+
2.2 At each timestep in each trajectory, compute
|
| 31 |
+
2.2.1 the return $R_t = \sum_{t'=t}^{T-1} \gamma^{t'-t}r_{t'}$ and
|
| 32 |
+
2.2.2 the advantage estimate $\hat{A_t} = R_t - b(s_t)$.
|
| 33 |
+
2.3 Re-fit the baseline (recomputing the value function) by minimizing
|
| 34 |
+
$|| b(s_t) - R_t||^2$, summed over all trajectories and timesteps.
|
| 35 |
+
|
| 36 |
+
2.3 Re-fit the baseline (recomputing the value function) by minimizing
|
| 37 |
+
$|| b(s_t) - R_t||^2$, summed over all trajectories and timesteps.
|
| 38 |
+
In other words, estimate optimal baseline:
|
| 39 |
+
|
| 40 |
+
$b=\frac{\left\langle \left( \sum\nolimits_{h=0}^{H} \mathbf{\nabla}_{\theta_{k}}\log\pi_{\mathbf{\theta}}
|
| 41 |
+
\left( \mathbf{a}_{h}\left\vert \mathbf{s}_{h}\right. \right) \right) ^{2}\sum\nolimits_{l=0}^{H}
|
| 42 |
+
\gamma r_{l}\right\rangle }{\left\langle \left(
|
| 43 |
+
\sum\nolimits_{h=0}^{H}\mathbf{\nabla}_{\theta_{k}}\log\pi_{\mathbf{\theta}
|
| 44 |
+
}\left( \mathbf{a}_{h}\left\vert \mathbf{x}_{h}\right. \right) \right)
|
| 45 |
+
^{2}\right\rangle }$
|
| 46 |
+
|
| 47 |
+
2.4 Update the policy, using a policy gradient estimate $\hat{g}$,
|
| 48 |
+
which is a sum of terms
|
| 49 |
+
$\nabla_\theta log\pi(a_t | s_t,\theta)\hat(A_t)$
|
| 50 |
+
3. **end for**
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def softmax(x):
|
| 54 |
+
"""
|
| 55 |
+
Softmax function implementation
|
| 56 |
+
"""
|
| 57 |
+
e_x = np.exp(x - np.max(x))
|
| 58 |
+
out = e_x / e_x.sum()
|
| 59 |
+
return out
|
| 60 |
+
|
| 61 |
+
def policy_gradient():
|
| 62 |
+
"""
|
| 63 |
+
Implementation of an optimizer that allows to incrementally update
|
| 64 |
+
the policy.
|
| 65 |
+
|
| 66 |
+
Parameters
|
| 67 |
+
----------
|
| 68 |
+
None
|
| 69 |
+
|
| 70 |
+
Returns
|
| 71 |
+
-------
|
| 72 |
+
probabilities
|
| 73 |
+
tensor containing the probabilities
|
| 74 |
+
state
|
| 75 |
+
tensor containing the state of the environment
|
| 76 |
+
actions
|
| 77 |
+
one-hot encoded vector containing a "one" at the action
|
| 78 |
+
we want to increase probability of.
|
| 79 |
+
advantages
|
| 80 |
+
tensor with the advantage from the environment
|
| 81 |
+
optimizer
|
| 82 |
+
Adam optimizer
|
| 83 |
+
"""
|
| 84 |
+
with tf.variable_scope("policy"):
|
| 85 |
+
params = tf.get_variable("policy_parameters",[4,2])
|
| 86 |
+
state = tf.placeholder("float",[None,4])
|
| 87 |
+
actions = tf.placeholder("float",[None,2])
|
| 88 |
+
advantages = tf.placeholder("float",[None,1])
|
| 89 |
+
linear = tf.matmul(state,params)
|
| 90 |
+
probabilities = tf.nn.softmax(linear)
|
| 91 |
+
good_probabilities = tf.reduce_sum(tf.multiply(probabilities, actions),reduction_indices=[1])
|
| 92 |
+
eligibility = tf.log(good_probabilities) * advantages
|
| 93 |
+
# maximize the log probability
|
| 94 |
+
loss = -tf.reduce_sum(eligibility)
|
| 95 |
+
optimizer = tf.train.AdamOptimizer(0.01).minimize(loss)
|
| 96 |
+
return probabilities, state, actions, advantages, optimizer
|
| 97 |
+
|
| 98 |
+
def value_gradient():
|
| 99 |
+
"""
|
| 100 |
+
Define the value network (the critic) which returns a value
|
| 101 |
+
for each state. Critic is implemented as a single hidden layer
|
| 102 |
+
neural network (with 10 hidden neurons).
|
| 103 |
+
|
| 104 |
+
Returns
|
| 105 |
+
-------
|
| 106 |
+
calculated
|
| 107 |
+
tensor containing the probabilities
|
| 108 |
+
state
|
| 109 |
+
tensor containing the state of the environment
|
| 110 |
+
newvals
|
| 111 |
+
tensor containing updated value function outputs (for optimization)
|
| 112 |
+
optimizer
|
| 113 |
+
Adam optimizer
|
| 114 |
+
loss
|
| 115 |
+
loss tensor. Debug purposes.
|
| 116 |
+
"""
|
| 117 |
+
with tf.variable_scope("value"):
|
| 118 |
+
state = tf.placeholder("float",[None,4])
|
| 119 |
+
newvals = tf.placeholder("float",[None,1])
|
| 120 |
+
w1 = tf.get_variable("w1",[4,10])
|
| 121 |
+
b1 = tf.get_variable("b1",[10])
|
| 122 |
+
h1 = tf.nn.relu(tf.matmul(state,w1) + b1)
|
| 123 |
+
w2 = tf.get_variable("w2",[10,1])
|
| 124 |
+
b2 = tf.get_variable("b2",[1])
|
| 125 |
+
calculated = tf.matmul(h1,w2) + b2
|
| 126 |
+
diffs = calculated - newvals
|
| 127 |
+
loss = tf.nn.l2_loss(diffs)
|
| 128 |
+
optimizer = tf.train.AdamOptimizer(0.1).minimize(loss)
|
| 129 |
+
return calculated, state, newvals, optimizer, loss
|
| 130 |
+
|
| 131 |
+
def run_episode(env, policy_grad, value_grad, sess, render = False):
|
| 132 |
+
"""
|
| 133 |
+
This function implements the main part of PG
|
| 134 |
+
|
| 135 |
+
Params
|
| 136 |
+
-------
|
| 137 |
+
env
|
| 138 |
+
Environment where to use PG
|
| 139 |
+
policy_grad
|
| 140 |
+
Policy gradient function that a) calculates the policy and b) optimizes it
|
| 141 |
+
value_grad
|
| 142 |
+
Value network (the critic)
|
| 143 |
+
sess
|
| 144 |
+
TF session object
|
| 145 |
+
|
| 146 |
+
Returns
|
| 147 |
+
-------
|
| 148 |
+
totalreward
|
| 149 |
+
the total reward of the episode (200 steps)
|
| 150 |
+
|
| 151 |
+
"""
|
| 152 |
+
# initialize variables
|
| 153 |
+
pl_calculated, pl_state, pl_actions, pl_advantages, pl_optimizer = policy_grad
|
| 154 |
+
vl_calculated, vl_state, vl_newvals, vl_optimizer, vl_loss = value_grad
|
| 155 |
+
observation = env.reset()
|
| 156 |
+
totalreward = 0
|
| 157 |
+
states = []
|
| 158 |
+
actions = []
|
| 159 |
+
advantages = []
|
| 160 |
+
transitions = []
|
| 161 |
+
update_vals = []
|
| 162 |
+
|
| 163 |
+
# 2.1 Collect a set of trajectories by executing the current policy obtaining
|
| 164 |
+
# $\mathbf{s}_{0:H},\mathbf{a}_{0:H},r_{0:H}$
|
| 165 |
+
for _ in range(200):
|
| 166 |
+
if render:
|
| 167 |
+
env.render()
|
| 168 |
+
# calculate policy
|
| 169 |
+
obs_vector = np.expand_dims(observation, axis=0)
|
| 170 |
+
probs = sess.run(pl_calculated,feed_dict={pl_state: obs_vector})
|
| 171 |
+
action = 0 if random.uniform(0,1) < probs[0][0] else 1
|
| 172 |
+
# record the transition
|
| 173 |
+
states.append(observation)
|
| 174 |
+
actionblank = np.zeros(2) # hardcode to specific environment
|
| 175 |
+
actionblank[action] = 1
|
| 176 |
+
actions.append(actionblank)
|
| 177 |
+
# take the action in the environment
|
| 178 |
+
old_observation = observation
|
| 179 |
+
observation, reward, done, info = env.step(action)
|
| 180 |
+
transitions.append((old_observation, action, reward))
|
| 181 |
+
totalreward += reward
|
| 182 |
+
|
| 183 |
+
if done:
|
| 184 |
+
break
|
| 185 |
+
# 2.2 At each timestep in each trajectory, compute
|
| 186 |
+
for index, trans in enumerate(transitions):
|
| 187 |
+
# invidivual transition
|
| 188 |
+
obs, action, reward = trans
|
| 189 |
+
|
| 190 |
+
# calculate discounted monte-carlo return
|
| 191 |
+
future_reward = 0
|
| 192 |
+
future_transitions = len(transitions) - index
|
| 193 |
+
decrease = 1
|
| 194 |
+
for index2 in range(future_transitions):
|
| 195 |
+
# 2.2.1 the return $R_t = \sum_{t'=t}^{T-1} \gamma^{t'-t}r_{t'}$
|
| 196 |
+
future_reward += transitions[(index2) + index][2] * decrease
|
| 197 |
+
# here "decrease" represents the gamma
|
| 198 |
+
decrease = decrease * 0.97
|
| 199 |
+
obs_vector = np.expand_dims(obs, axis=0)
|
| 200 |
+
currentval = sess.run(vl_calculated,feed_dict={vl_state: obs_vector})[0][0]
|
| 201 |
+
# 2.2.2 the advantage estimate $\hat{A_t} = R_t - b(s_t)$.
|
| 202 |
+
# advantage: how much better was this action than normal
|
| 203 |
+
advantages.append(future_reward - currentval)
|
| 204 |
+
|
| 205 |
+
# add future_reward to update the value function towards new return
|
| 206 |
+
update_vals.append(future_reward)
|
| 207 |
+
|
| 208 |
+
# 2.3 Re-fit the baseline (recomputing the value function) by minimizing
|
| 209 |
+
# $|| b(s_t) - R_t||^2$, summed over all trajectories and timesteps.
|
| 210 |
+
# In other words, estimate optimal baseline:
|
| 211 |
+
#
|
| 212 |
+
# $b=\frac{\left\langle \left( \sum\nolimits_{h=0}^{H} \mathbf{\nabla}_{\theta_{k}}\log\pi_{\mathbf{\theta}}
|
| 213 |
+
# \left( \mathbf{a}_{h}\left\vert \mathbf{s}_{h}\right. \right) \right) ^{2}\sum\nolimits_{l=0}^{H}
|
| 214 |
+
# \gamma r_{l}\right\rangle }{\left\langle \left(
|
| 215 |
+
# \sum\nolimits_{h=0}^{H}\mathbf{\nabla}_{\theta_{k}}\log\pi_{\mathbf{\theta}
|
| 216 |
+
# }\left( \mathbf{a}_{h}\left\vert \mathbf{x}_{h}\right. \right) \right)
|
| 217 |
+
# ^{2}\right\rangle }$
|
| 218 |
+
# update value function
|
| 219 |
+
update_vals_vector = np.expand_dims(update_vals, axis=1)
|
| 220 |
+
sess.run(vl_optimizer, feed_dict={vl_state: states, vl_newvals: update_vals_vector})
|
| 221 |
+
# real_vl_loss = sess.run(vl_loss, feed_dict={vl_state: states, vl_newvals: update_vals_vector})
|
| 222 |
+
|
| 223 |
+
# 2.4 Update the policy, using a policy gradient estimate $\hat{g}$,
|
| 224 |
+
# which is a sum of terms $\nabla_\theta log\pi(a_t | s_t,\theta)\hat(A_t)$.
|
| 225 |
+
# In other words:
|
| 226 |
+
#
|
| 227 |
+
# $g_{k}=\left\langle \left( \sum\nolimits_{h=0}^{H}\mathbf{\nabla
|
| 228 |
+
# }_{\theta_{k}}\log\pi_{\mathbf{\theta}}\left( \mathbf{a}_{h}\left\vert
|
| 229 |
+
# \mathbf{s}_{h}\right. \right) \right) \left( \sum\nolimits_{l=0}^{H}
|
| 230 |
+
# \gamma r_{l}-b\right) \right\rangle$
|
| 231 |
+
advantages_vector = np.expand_dims(advantages, axis=1)
|
| 232 |
+
sess.run(pl_optimizer, feed_dict={pl_state: states, pl_advantages: advantages_vector, pl_actions: actions})
|
| 233 |
+
|
| 234 |
+
return totalreward
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
env = gym.make('CartPole-v0')
|
| 238 |
+
# 1. Initialize policy (e.g. NNs) parameter $\theta$ and baseline $b$
|
| 239 |
+
policy_grad = policy_gradient()
|
| 240 |
+
value_grad = value_gradient()
|
| 241 |
+
sess = tf.InteractiveSession()
|
| 242 |
+
sess.run(tf.initialize_all_variables())
|
| 243 |
+
# 2. For iteration=1,2,... do
|
| 244 |
+
for i in range(1000):
|
| 245 |
+
reward = run_episode(env, policy_grad, value_grad, sess)
|
| 246 |
+
print("episode ",i, "reward: ",reward)
|
| 247 |
+
# if reward == 200:
|
| 248 |
+
# print("reward 200")
|
| 249 |
+
# print(i)
|
| 250 |
+
# break
|
| 251 |
+
# 3. **end for**
|
| 252 |
+
|
| 253 |
+
# Validate the training in 1000 epidodes
|
| 254 |
+
t = 0
|
| 255 |
+
for _ in range(1000):
|
| 256 |
+
reward = run_episode(env, policy_grad, value_grad, sess, render=True)
|
| 257 |
+
t += reward
|
| 258 |
+
print(t / 1000)
|
code/train/Python/0052182_695._Max_Area_of_Island.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import deque
|
| 2 |
+
class Solution(object):
|
| 3 |
+
def maxAreaOfIsland(self, grid):
|
| 4 |
+
"""
|
| 5 |
+
:type grid: List[List[int]]
|
| 6 |
+
:rtype: int
|
| 7 |
+
"""
|
| 8 |
+
R = len(grid)
|
| 9 |
+
if not R:
|
| 10 |
+
return 0
|
| 11 |
+
C = len(grid[0])
|
| 12 |
+
q = deque()
|
| 13 |
+
|
| 14 |
+
def dfs(r, c):
|
| 15 |
+
q.append( (r, c) )
|
| 16 |
+
grid[r][c] = 2
|
| 17 |
+
size = 0
|
| 18 |
+
while q:
|
| 19 |
+
r, c = q.popleft()
|
| 20 |
+
size += 1
|
| 21 |
+
for nr, nc in ( (r-1, c), (r+1, c), (r, c-1), (r, c+1) ):
|
| 22 |
+
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 1:
|
| 23 |
+
grid[nr][nc] = 2
|
| 24 |
+
q.append( (nr, nc) )
|
| 25 |
+
|
| 26 |
+
return size
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
maxsize = 0
|
| 30 |
+
for r in xrange(R):
|
| 31 |
+
for c in xrange(C):
|
| 32 |
+
if grid[r][c] == 1:
|
| 33 |
+
maxsize = max(maxsize, dfs(r, c))
|
| 34 |
+
|
| 35 |
+
return maxsize
|
| 36 |
+
|
| 37 |
+
print Solution().maxAreaOfIsland(
|
| 38 |
+
[[1,1,0,0,0],
|
| 39 |
+
[1,1,0,0,0],
|
| 40 |
+
[0,0,0,1,1],
|
| 41 |
+
[0,0,0,1,1]])
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
print Solution().maxAreaOfIsland(
|
| 45 |
+
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
|
| 46 |
+
[0,0,0,0,0,0,0,1,1,1,0,0,0],
|
| 47 |
+
[0,1,1,0,1,0,0,0,0,0,0,0,0],
|
| 48 |
+
[0,1,0,0,1,1,0,0,1,0,1,0,0],
|
| 49 |
+
[0,1,0,0,1,1,0,0,1,1,1,0,0],
|
| 50 |
+
[0,0,0,0,0,0,0,0,0,0,1,0,0],
|
| 51 |
+
[0,0,0,0,0,0,0,1,1,1,0,0,0],
|
| 52 |
+
[0,0,0,0,0,0,0,1,1,0,0,0,0]])
|
| 53 |
+
|
| 54 |
+
print Solution().maxAreaOfIsland(
|
| 55 |
+
[[0,0,1,0,0,0,0,1,1,1,0,0,0]])
|
code/train/Python/0052527_530.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
|
| 4 |
+
# Definition for a binary tree node.
|
| 5 |
+
# class TreeNode(object):
|
| 6 |
+
# def __init__(self, x):
|
| 7 |
+
# self.val = x
|
| 8 |
+
# self.left = None
|
| 9 |
+
# self.right = None
|
| 10 |
+
|
| 11 |
+
class Solution(object):
|
| 12 |
+
def getMinimumDifference(self, root):
|
| 13 |
+
"""
|
| 14 |
+
:type root: TreeNode
|
| 15 |
+
:rtype: int
|
| 16 |
+
"""
|
| 17 |
+
l=[]
|
| 18 |
+
self.getAllNums(root,l)
|
| 19 |
+
l.sort()
|
| 20 |
+
Min = 2140000
|
| 21 |
+
for i in range(1,len(l)):
|
| 22 |
+
Min = min(Min,l[i]-l[i-1])
|
| 23 |
+
|
| 24 |
+
return Min
|
| 25 |
+
|
| 26 |
+
def getAllNums(self, root, l):
|
| 27 |
+
if root == None:
|
| 28 |
+
return
|
| 29 |
+
l.append(root.val)
|
| 30 |
+
self.getAllNums(root.left,l)
|
| 31 |
+
self.getAllNums(root.right,l)
|
| 32 |
+
return
|
| 33 |
+
|
code/train/Python/0052648_plotAlphaSensitivity.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import matplotlib as mpl
|
| 2 |
+
mpl.use('Agg')
|
| 3 |
+
import plotter
|
| 4 |
+
import glob
|
| 5 |
+
import scipy.stats as sps
|
| 6 |
+
from matplotlib import pylab as plt
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def alphaSensitivity(db=None, outdir="./"):
|
| 10 |
+
""" Plot results with different values of alpha """
|
| 11 |
+
|
| 12 |
+
pr = plotter.Plotter(db=db)
|
| 13 |
+
cursor = pr.cursor[0]
|
| 14 |
+
refAlpha = 0
|
| 15 |
+
refExpid = None
|
| 16 |
+
|
| 17 |
+
# Get expid and alpha values from "experiment" table
|
| 18 |
+
expRaw = cursor.execute("SELECT id, args FROM experiment ")
|
| 19 |
+
exp = {}
|
| 20 |
+
for expid, args in expRaw:
|
| 21 |
+
alpha = [float(x.rpartition("=")[2]) for x in args.split(",") if x.startswith(" alpha=")]
|
| 22 |
+
exp[expid] = alpha[0]
|
| 23 |
+
if alpha[0]>refAlpha:
|
| 24 |
+
refExpid = expid
|
| 25 |
+
refAlpha= alpha[0]
|
| 26 |
+
|
| 27 |
+
asHegemonyRef = dict(cursor.execute("SELECT asn, hege FROM hegemony WHERE ts=0 AND scope=0 AND expid=?",(refExpid,)))
|
| 28 |
+
# Remove AS with a score == 0.0
|
| 29 |
+
toremove = [asn for asn, score in asHegemonyRef.iteritems() if score==0.0]
|
| 30 |
+
if not toremove is None:
|
| 31 |
+
for asn in toremove:
|
| 32 |
+
del asHegemonyRef[asn]
|
| 33 |
+
minVal = min(asHegemonyRef.values())
|
| 34 |
+
|
| 35 |
+
y = []
|
| 36 |
+
x = []
|
| 37 |
+
for expid, alpha in exp.iteritems():
|
| 38 |
+
asHegemony = dict(cursor.execute("SELECT asn, hege FROM hegemony WHERE ts=0 AND scope=0 AND expid=?", (expid,)))
|
| 39 |
+
if not len(asHegemony):
|
| 40 |
+
continue
|
| 41 |
+
|
| 42 |
+
# Remove AS with a score == 0.0
|
| 43 |
+
toremove = [asn for asn, score in asHegemony.iteritems() if score==0.0]
|
| 44 |
+
if not toremove is None:
|
| 45 |
+
for asn in toremove:
|
| 46 |
+
del asHegemony[asn]
|
| 47 |
+
|
| 48 |
+
# Set the same number of ASN for both distributions
|
| 49 |
+
missingAS = set(asHegemonyRef.keys()).difference(asHegemony.keys())
|
| 50 |
+
if not missingAS is None:
|
| 51 |
+
for asn in missingAS:
|
| 52 |
+
asHegemony[asn] = minVal
|
| 53 |
+
|
| 54 |
+
# Compute the KL-divergence
|
| 55 |
+
dist = [asHegemony[asn] for asn in asHegemonyRef.keys()]
|
| 56 |
+
kldiv = sps.entropy(dist, asHegemonyRef.values())
|
| 57 |
+
y.append(kldiv)
|
| 58 |
+
x.append(alpha)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
sx, sy = zip(*sorted(zip(x,y)))
|
| 62 |
+
plt.figure(figsize=(4,3))
|
| 63 |
+
plt.plot(sx, sy, "+-")
|
| 64 |
+
plt.xlabel("$\\alpha$")
|
| 65 |
+
plt.ylabel("KL divergence")
|
| 66 |
+
plt.tight_layout()
|
| 67 |
+
plt.savefig("results/alphaSensitivity/alphaSensitivity.pdf")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
# parser = argparse.ArgumentParser()
|
| 73 |
+
# parser.add_argument("-i", "--input", help="Folder containing the .sql file produced by ashash", type=str, required=True)
|
| 74 |
+
# parser.add_argument("-t", "--title", help="Title for the figure", type=str, default=None)
|
| 75 |
+
# args = parser.parse_args()
|
| 76 |
+
|
| 77 |
+
db = glob.glob("results/alphaSensitivity/*.sql")
|
| 78 |
+
alphaSensitivity(db=db)
|
code/train/Python/0052999_postfix2bdt.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Title : postfix to binary tree
|
| 2 |
+
# Developed by : Yogesh Mahajan (y.mahajan456@gmail.com) (14D070022 @ IITB EE)
|
| 3 |
+
# OV Shashank (shashank[at]ee.iitb.ac.in) (14D070021 @ IITB EE)
|
| 4 |
+
# Avineil Jain (avineil96[at]ee.iitb.ac.in)(14D170002 @ IITB EE)
|
| 5 |
+
# Description : Convert postfix expression to binary expression tree
|
| 6 |
+
#--------------------------------------------------------------------------------------------------
|
| 7 |
+
from stack import Stack
|
| 8 |
+
|
| 9 |
+
class Op_Node:
|
| 10 |
+
childs_count = 0
|
| 11 |
+
childs = [] #just names of child nodes
|
| 12 |
+
level = None
|
| 13 |
+
|
| 14 |
+
def __init__(self):
|
| 15 |
+
self.name = None
|
| 16 |
+
|
| 17 |
+
def __init__(self,name,*vars):
|
| 18 |
+
self.name = name
|
| 19 |
+
if(len(vars) > 0):
|
| 20 |
+
self.childs = vars[0]
|
| 21 |
+
self.childs_count = len(vars[0])
|
| 22 |
+
|
| 23 |
+
def __str__(self):
|
| 24 |
+
return str([self.name,self.childs,self.level])
|
| 25 |
+
|
| 26 |
+
def node_obj2list(self):
|
| 27 |
+
return [self.name,self.childs,self.level]
|
| 28 |
+
#---------------------------------------------------------------------------------------------------
|
| 29 |
+
# Operand count of operators not having 2 operands
|
| 30 |
+
ns_operand_count = {} # ns for non standard -> not having 2 operands
|
| 31 |
+
ns_operand_count['!'] = 1
|
| 32 |
+
|
| 33 |
+
op_list = ['@','%','*','/','+','-','!','&','^','|']
|
| 34 |
+
|
| 35 |
+
ns_op = list(ns_operand_count.keys())
|
| 36 |
+
#--------------------------------------------------------------------------------------------------
|
| 37 |
+
def postfix2bdt(postfix,prefix = 'n'):
|
| 38 |
+
tmp_stack = Stack()
|
| 39 |
+
node_list = {}
|
| 40 |
+
node_names = []
|
| 41 |
+
for token in postfix:
|
| 42 |
+
if(token not in op_list):
|
| 43 |
+
if(token not in node_names):
|
| 44 |
+
new_var = Op_Node(token)
|
| 45 |
+
new_var.level = 0
|
| 46 |
+
node_names.append(token)
|
| 47 |
+
node_list[token] = new_var
|
| 48 |
+
|
| 49 |
+
tmp_stack.push(token)
|
| 50 |
+
|
| 51 |
+
else:
|
| 52 |
+
operands_list = []
|
| 53 |
+
if(token in ns_op):
|
| 54 |
+
for i in range(ns_operand_count[token]):
|
| 55 |
+
new_operand_node_name = tmp_stack.pop()
|
| 56 |
+
if(new_operand_node_name != None):
|
| 57 |
+
operands_list.append(new_operand_node_name)
|
| 58 |
+
else:
|
| 59 |
+
print("\nNumber of operands mismatch for operator : ", token,"\n")
|
| 60 |
+
return None
|
| 61 |
+
else:
|
| 62 |
+
for i in range(2):
|
| 63 |
+
new_operand = tmp_stack.pop()
|
| 64 |
+
if(new_operand != None):
|
| 65 |
+
operands_list.append(new_operand)
|
| 66 |
+
else:
|
| 67 |
+
print("\nNumber of operands mismatch for operator : ", token,"\n")
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
level_count = 0
|
| 71 |
+
for child in operands_list:
|
| 72 |
+
if(level_count < node_list[child].level):
|
| 73 |
+
level_count = node_list[child].level
|
| 74 |
+
|
| 75 |
+
node_name = prefix+str(len(node_names))
|
| 76 |
+
node_names.append(node_name)
|
| 77 |
+
|
| 78 |
+
new_op_node = Op_Node(token,operands_list)
|
| 79 |
+
new_op_node.level = level_count+1
|
| 80 |
+
|
| 81 |
+
node_list[node_name] = new_op_node
|
| 82 |
+
tmp_stack.push(node_name)
|
| 83 |
+
|
| 84 |
+
bt = {node:node_list[node].node_obj2list() for node in node_names}
|
| 85 |
+
|
| 86 |
+
parent_node = tmp_stack.pop()
|
| 87 |
+
return [bt,parent_node]
|
| 88 |
+
#--------------------------------------------------------------------------------------------------
|
| 89 |
+
|
code/train/Python/0053127_Longest_consecutive_sequence.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
|
| 3 |
+
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
|
| 4 |
+
|
| 5 |
+
For example,
|
| 6 |
+
Given [100, 4, 200, 1, 3, 2],
|
| 7 |
+
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
|
| 8 |
+
|
| 9 |
+
Your algorithm should run in O(n) complexity.
|
| 10 |
+
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
class Solution:
|
| 14 |
+
|
| 15 |
+
# @param num, a list of integer
|
| 16 |
+
# @return an integer
|
| 17 |
+
def longestConsecutive(self, num):
|
| 18 |
+
|
| 19 |
+
# base case
|
| 20 |
+
if len(num) == 0:
|
| 21 |
+
return 0
|
| 22 |
+
|
| 23 |
+
# for O(1) element searching
|
| 24 |
+
s = set(num)
|
| 25 |
+
|
| 26 |
+
# means single element itself is a sequence
|
| 27 |
+
max_count = 1
|
| 28 |
+
|
| 29 |
+
# for each number move left and right to check
|
| 30 |
+
# if there is a sequence
|
| 31 |
+
for n in num:
|
| 32 |
+
left = n - 1
|
| 33 |
+
right = n + 1
|
| 34 |
+
count = 1
|
| 35 |
+
|
| 36 |
+
while left in s:
|
| 37 |
+
s.remove(left)
|
| 38 |
+
left = left - 1
|
| 39 |
+
count = count + 1
|
| 40 |
+
|
| 41 |
+
while right in s:
|
| 42 |
+
s.remove(right)
|
| 43 |
+
right = right + 1
|
| 44 |
+
count = count + 1
|
| 45 |
+
|
| 46 |
+
max_count = max(max_count, count)
|
| 47 |
+
return max_count
|
| 48 |
+
|
| 49 |
+
s = Solution()
|
| 50 |
+
print s.longestConsecutive([100, 4, 200, 1, 3, 2])
|
code/train/Python/0053169_utils.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import
|
| 2 |
+
import socket
|
| 3 |
+
import struct
|
| 4 |
+
|
| 5 |
+
from .consts import *
|
| 6 |
+
import six
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def uint8(n):
|
| 10 |
+
return struct.pack("B", n)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def uint64(n):
|
| 14 |
+
return struct.pack("!Q", n)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Error(Exception):
|
| 18 |
+
def __init__(self, code):
|
| 19 |
+
self.code = code
|
| 20 |
+
|
| 21 |
+
def __str__(self):
|
| 22 |
+
return strerror(self.code)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def pack(cmd, *args):
|
| 26 |
+
msg = []
|
| 27 |
+
for a in args:
|
| 28 |
+
if isinstance(a, six.integer_types):
|
| 29 |
+
msg.append(struct.pack("!I", a))
|
| 30 |
+
elif isinstance(a, bytes):
|
| 31 |
+
msg.append(a)
|
| 32 |
+
else:
|
| 33 |
+
raise TypeError(str(type(a))+str(a))
|
| 34 |
+
header = struct.pack("!II", cmd, sum(len(i) for i in msg))
|
| 35 |
+
return header + b''.join(msg)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def unpack(fmt, buf):
|
| 39 |
+
if not fmt.startswith("!"):
|
| 40 |
+
fmt = "!" + fmt
|
| 41 |
+
return struct.unpack(fmt, buf[:struct.calcsize(fmt)])
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class FileInfo:
|
| 45 |
+
def __init__(self, inode, name, ftype, mode, uid, gid,
|
| 46 |
+
atime, mtime, ctime, nlink, length):
|
| 47 |
+
self.inode = inode
|
| 48 |
+
self.name = name
|
| 49 |
+
self.ftype = self._get_ftype(ftype)
|
| 50 |
+
if ftype == TYPE_DIRECTORY:
|
| 51 |
+
mode |= S_IFDIR
|
| 52 |
+
elif ftype == TYPE_SYMLINK:
|
| 53 |
+
mode |= S_IFLNK
|
| 54 |
+
elif ftype == TYPE_FILE:
|
| 55 |
+
mode |= S_IFREG
|
| 56 |
+
self.mode = mode
|
| 57 |
+
self.uid = uid
|
| 58 |
+
self.gid = gid
|
| 59 |
+
self.atime = atime
|
| 60 |
+
self.mtime = mtime
|
| 61 |
+
self.ctime = ctime
|
| 62 |
+
self.nlink = nlink
|
| 63 |
+
self.length = length
|
| 64 |
+
self.blocks = (length + 511) / 512
|
| 65 |
+
|
| 66 |
+
def __repr__(self):
|
| 67 |
+
return ("FileInfo(%s, inode=%d, type=%s, length=%d)" %
|
| 68 |
+
(self.name, self.inode, self.ftype, self.length))
|
| 69 |
+
|
| 70 |
+
def is_symlink(self):
|
| 71 |
+
return self.ftype == TYPE_SYMLINK
|
| 72 |
+
|
| 73 |
+
def _get_ftype(self, ftype):
|
| 74 |
+
ftype_str_map = {1: TYPE_FILE, 2: TYPE_DIRECTORY, 3: TYPE_SYMLINK,
|
| 75 |
+
4: TYPE_FIFO, 5: TYPE_BLOCKDEV, 6: TYPE_CHARDEV,
|
| 76 |
+
7: TYPE_SOCKET, 8: TYPE_TRASH, 9: TYPE_SUSTAINED}
|
| 77 |
+
if ftype in ftype_str_map:
|
| 78 |
+
return ftype_str_map[ftype]
|
| 79 |
+
return '?'
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def attrToFileInfo(inode, attrs, name='', version=(0, 0, 0)):
|
| 83 |
+
if len(attrs) != 35:
|
| 84 |
+
raise Exception('bad length')
|
| 85 |
+
if version < (1, 7, 32):
|
| 86 |
+
return FileInfo(inode, name, *struct.unpack("!BHIIIIIIQ", attrs))
|
| 87 |
+
else:
|
| 88 |
+
return _unpack_to_file_info(inode, attrs, name)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _unpack_to_file_info(inode, attrs, name):
|
| 92 |
+
tup = struct.unpack("!BHIIIIIIQ", attrs)
|
| 93 |
+
type_mode = tup[1]
|
| 94 |
+
ftype = (type_mode & 0xf000) >> 12
|
| 95 |
+
mode = type_mode & 0x0fff
|
| 96 |
+
return FileInfo(inode, name, ftype, mode, *(tup[2:]))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def read_chunk(host, port, chunkid, version, size, offset=0):
|
| 100 |
+
if offset + size > CHUNKSIZE:
|
| 101 |
+
raise ValueError("size too large %s > %s" %
|
| 102 |
+
(size, CHUNKSIZE-offset))
|
| 103 |
+
|
| 104 |
+
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
| 105 |
+
conn.settimeout(10)
|
| 106 |
+
conn.connect((host, port))
|
| 107 |
+
|
| 108 |
+
msg = pack(CLTOCS_READ, uint64(chunkid), version, offset, size)
|
| 109 |
+
n = conn.send(msg)
|
| 110 |
+
while n < len(msg):
|
| 111 |
+
if not n:
|
| 112 |
+
raise IOError("write failed")
|
| 113 |
+
msg = msg[n:]
|
| 114 |
+
n = conn.send(msg)
|
| 115 |
+
|
| 116 |
+
def recv(n):
|
| 117 |
+
d = conn.recv(n)
|
| 118 |
+
while len(d) < n:
|
| 119 |
+
nd = conn.recv(n-len(d))
|
| 120 |
+
if not nd:
|
| 121 |
+
raise IOError("not enough data")
|
| 122 |
+
d += nd
|
| 123 |
+
return d
|
| 124 |
+
|
| 125 |
+
while size > 0:
|
| 126 |
+
cmd, l = unpack("II", recv(8))
|
| 127 |
+
|
| 128 |
+
if cmd == CSTOCL_READ_STATUS:
|
| 129 |
+
if l != 9:
|
| 130 |
+
raise Exception("readblock: READ_STATUS incorrect message size")
|
| 131 |
+
cid, code = unpack("QB", recv(l))
|
| 132 |
+
if cid != chunkid:
|
| 133 |
+
raise Exception("readblock; READ_STATUS incorrect chunkid")
|
| 134 |
+
conn.close()
|
| 135 |
+
return
|
| 136 |
+
|
| 137 |
+
elif cmd == CSTOCL_READ_DATA:
|
| 138 |
+
if l < 20 :
|
| 139 |
+
raise Exception("readblock; READ_DATA incorrect message size")
|
| 140 |
+
cid, bid, boff, bsize, crc = unpack("QHHII", recv(20))
|
| 141 |
+
if cid != chunkid:
|
| 142 |
+
raise Exception("readblock; READ_STATUS incorrect chunkid")
|
| 143 |
+
if l != 20 + bsize:
|
| 144 |
+
raise Exception("readblock; READ_DATA incorrect message size ")
|
| 145 |
+
if bsize == 0 : # FIXME
|
| 146 |
+
raise Exception("readblock; empty block")
|
| 147 |
+
if bid != offset >> 16:
|
| 148 |
+
raise Exception("readblock; READ_DATA incorrect block number")
|
| 149 |
+
if boff != offset & 0xFFFF:
|
| 150 |
+
raise Exception("readblock; READ_DATA incorrect block offset")
|
| 151 |
+
breq = 65536 - boff
|
| 152 |
+
if size < breq:
|
| 153 |
+
breq = size
|
| 154 |
+
if bsize != breq:
|
| 155 |
+
raise Exception("readblock; READ_DATA incorrect block size")
|
| 156 |
+
|
| 157 |
+
while breq > 0:
|
| 158 |
+
data = conn.recv(breq)
|
| 159 |
+
if not data:
|
| 160 |
+
raise IOError("unexpected ending: need %d" % breq)
|
| 161 |
+
yield data
|
| 162 |
+
breq -= len(data)
|
| 163 |
+
|
| 164 |
+
offset += bsize
|
| 165 |
+
size -= bsize
|
| 166 |
+
else:
|
| 167 |
+
raise Exception("readblock; unknown message: %s" % cmd)
|
| 168 |
+
conn.close()
|
code/train/Python/0053206_teststep.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Copyright (C) 2015 BMW Car IT GmbH
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
|
| 17 |
+
import datetime
|
| 18 |
+
import os
|
| 19 |
+
import signal
|
| 20 |
+
from threading import Thread
|
| 21 |
+
import time
|
| 22 |
+
from subprocess import Popen, PIPE
|
| 23 |
+
|
| 24 |
+
import psutil
|
| 25 |
+
|
| 26 |
+
from pyrate.exception import ParseException
|
| 27 |
+
from pyrate.model.common import needs_token
|
| 28 |
+
from pyrate.output.terminal import STATUS_RUN, STATUS_OK, STATUS_FAILED
|
| 29 |
+
from pyrate.util import duration, resolveVariables
|
| 30 |
+
from pyrate.validator.exitcode import ExitCodeValidator
|
| 31 |
+
from pyrate.validator.stream import StreamValidator
|
| 32 |
+
from pyrate.model.env import parse_env
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class TestStep:
|
| 36 |
+
KEY = 'teststep'
|
| 37 |
+
KEY_NAME = 'name'
|
| 38 |
+
KEY_MESSAGE = 'message'
|
| 39 |
+
KEY_COMMAND = 'command'
|
| 40 |
+
KEY_EXIT = 'exit'
|
| 41 |
+
KEY_STDOUT = 'stdout'
|
| 42 |
+
KEY_STDERR = 'stderr'
|
| 43 |
+
KEY_FATAL = 'fatal'
|
| 44 |
+
KEY_TIMEOUT = 'timeout'
|
| 45 |
+
|
| 46 |
+
def __init__(self, yaml_tree):
|
| 47 |
+
# default values
|
| 48 |
+
self.name = None
|
| 49 |
+
self.message = None
|
| 50 |
+
self.command = None
|
| 51 |
+
self.fatal = False
|
| 52 |
+
self.timeout = 0
|
| 53 |
+
self.validators = []
|
| 54 |
+
|
| 55 |
+
self.failed = False
|
| 56 |
+
self.abort_timeout = False
|
| 57 |
+
self.executed = False
|
| 58 |
+
self.arguments = {}
|
| 59 |
+
|
| 60 |
+
for key, value in yaml_tree.items():
|
| 61 |
+
if key == self.KEY_NAME:
|
| 62 |
+
self.name = value
|
| 63 |
+
elif key == self.KEY_MESSAGE:
|
| 64 |
+
self.message = value
|
| 65 |
+
elif key == self.KEY_COMMAND:
|
| 66 |
+
self.command = value
|
| 67 |
+
elif key == self.KEY_EXIT:
|
| 68 |
+
self.validators.append(ExitCodeValidator(value))
|
| 69 |
+
elif key == self.KEY_STDOUT:
|
| 70 |
+
self.validators.append(StreamValidator(value, 'stdout'))
|
| 71 |
+
elif key == self.KEY_STDERR:
|
| 72 |
+
self.validators.append(StreamValidator(value, 'stderr'))
|
| 73 |
+
elif key == self.KEY_FATAL:
|
| 74 |
+
if type(value) is not bool:
|
| 75 |
+
raise ParseException("%s '%s': error parsing %s (%s) : "
|
| 76 |
+
"must be a bool" %
|
| 77 |
+
(self.KEY,
|
| 78 |
+
self.name,
|
| 79 |
+
self.KEY_FATAL,
|
| 80 |
+
value))
|
| 81 |
+
self.fatal = value
|
| 82 |
+
elif key == self.KEY_TIMEOUT:
|
| 83 |
+
if type(value) is not int:
|
| 84 |
+
raise ParseException("%s '%s': error parsing %s (%s) : "
|
| 85 |
+
"must be an integer" %
|
| 86 |
+
(self.KEY, self.name,
|
| 87 |
+
self.KEY_TIMEOUT, value))
|
| 88 |
+
self.timeout = yaml_tree[self.KEY_TIMEOUT]
|
| 89 |
+
else:
|
| 90 |
+
raise ParseException("%s (%s): Unknown token '%s'" % (
|
| 91 |
+
self.KEY, self.name, key))
|
| 92 |
+
|
| 93 |
+
# validate mandatory fields
|
| 94 |
+
needs_token(self.name, self.KEY, self.KEY_NAME, self.name)
|
| 95 |
+
needs_token(self.command, self.KEY, self.KEY_COMMAND, self.name)
|
| 96 |
+
|
| 97 |
+
def parse_args(self, yaml_tree):
|
| 98 |
+
self.arguments = parse_env(yaml_tree)
|
| 99 |
+
|
| 100 |
+
def process_timeout(self, process):
|
| 101 |
+
try:
|
| 102 |
+
start = datetime.datetime.now()
|
| 103 |
+
|
| 104 |
+
while duration(start) < self.timeout:
|
| 105 |
+
# when abort is signaled there is no need to kill
|
| 106 |
+
# anything anymore
|
| 107 |
+
if self.abort_timeout:
|
| 108 |
+
return
|
| 109 |
+
|
| 110 |
+
time.sleep(0.001)
|
| 111 |
+
|
| 112 |
+
parent = psutil.Process(process.pid)
|
| 113 |
+
for child in parent.children(recursive=True):
|
| 114 |
+
os.kill(child.pid, signal.SIGKILL)
|
| 115 |
+
os.kill(parent.pid, signal.SIGKILL)
|
| 116 |
+
except:
|
| 117 |
+
pass
|
| 118 |
+
|
| 119 |
+
def execute(self, variables):
|
| 120 |
+
command = resolveVariables(self.command, variables)
|
| 121 |
+
|
| 122 |
+
process = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
|
| 123 |
+
|
| 124 |
+
# if a timeout was specified start a thread which kills the process
|
| 125 |
+
# tree if it's still running after the timeout
|
| 126 |
+
kill_thread = None
|
| 127 |
+
if self.timeout > 0:
|
| 128 |
+
self.abort_timeout = False
|
| 129 |
+
kill_thread = Thread(target=self.process_timeout, args=(process,))
|
| 130 |
+
kill_thread.start()
|
| 131 |
+
|
| 132 |
+
stdout, stderr = process.communicate()
|
| 133 |
+
exitcode = process.wait()
|
| 134 |
+
|
| 135 |
+
# if the timeout thread is still there we have to stop it
|
| 136 |
+
if kill_thread is not None:
|
| 137 |
+
self.abort_timeout = True
|
| 138 |
+
kill_thread.join()
|
| 139 |
+
|
| 140 |
+
success = True
|
| 141 |
+
for validator in self.validators:
|
| 142 |
+
if not validator.validate(exitcode,
|
| 143 |
+
stdout.decode("utf-8"),
|
| 144 |
+
stderr.decode("utf-8"),
|
| 145 |
+
variables,
|
| 146 |
+
command):
|
| 147 |
+
success = False
|
| 148 |
+
|
| 149 |
+
# don't print command on further validators
|
| 150 |
+
command = None
|
| 151 |
+
|
| 152 |
+
return success
|
| 153 |
+
|
| 154 |
+
def run(self, testcase, variables):
|
| 155 |
+
self.executed = True
|
| 156 |
+
start = datetime.datetime.now()
|
| 157 |
+
|
| 158 |
+
# merge global and step variables
|
| 159 |
+
# step variables take precedence
|
| 160 |
+
used_variables = {}
|
| 161 |
+
for key, value in variables.items():
|
| 162 |
+
used_variables[key] = value
|
| 163 |
+
for key, value in self.arguments.items():
|
| 164 |
+
used_variables[key] = value
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
description = self.message
|
| 168 |
+
if description is None:
|
| 169 |
+
description = self.name
|
| 170 |
+
|
| 171 |
+
description = resolveVariables(description, used_variables)
|
| 172 |
+
|
| 173 |
+
print("%s %s: %s" % (STATUS_RUN, testcase.name, description))
|
| 174 |
+
|
| 175 |
+
status = STATUS_OK
|
| 176 |
+
if not self.execute(used_variables):
|
| 177 |
+
status = STATUS_FAILED
|
| 178 |
+
self.failed = True
|
| 179 |
+
|
| 180 |
+
print("%s %s: %s (%d ms)" %
|
| 181 |
+
(status, testcase.name, description, duration(start)))
|
| 182 |
+
|
| 183 |
+
return not (self.failed and self.fatal)
|
code/train/Python/0053393_document.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
"""
|
| 3 |
+
import pygame
|
| 4 |
+
|
| 5 |
+
import container
|
| 6 |
+
import layout
|
| 7 |
+
|
| 8 |
+
class _document_widget:
|
| 9 |
+
def __init__(self,w,align=None):
|
| 10 |
+
#w.rect.w,w.rect.h = w.resize()
|
| 11 |
+
#self.rect = w.rect
|
| 12 |
+
self.widget = w
|
| 13 |
+
if align != None: self.align = align
|
| 14 |
+
|
| 15 |
+
class Document(container.Container):
|
| 16 |
+
"""A document container contains many widgets strung together in a document format. (How informative!)
|
| 17 |
+
|
| 18 |
+
<pre>Document()</pre>
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
def __init__(self,**params):
|
| 22 |
+
params.setdefault('cls','document')
|
| 23 |
+
container.Container.__init__(self,**params)
|
| 24 |
+
self.layout = layout.Layout(pygame.Rect(0,0,self.rect.w,self.rect.h))
|
| 25 |
+
|
| 26 |
+
def add(self,e,align=None):
|
| 27 |
+
"""Add a widget.
|
| 28 |
+
|
| 29 |
+
<pre>Document.add(e,align=None)</pre>
|
| 30 |
+
|
| 31 |
+
<dl>
|
| 32 |
+
<dt>e<dd>widget
|
| 33 |
+
<dt>align<dd>alignment (None,-1,0,1)
|
| 34 |
+
</dl>
|
| 35 |
+
"""
|
| 36 |
+
dw = _document_widget(e,align)
|
| 37 |
+
self.layout.add(dw)
|
| 38 |
+
e.container = self
|
| 39 |
+
e._c_dw = dw
|
| 40 |
+
self.widgets.append(e)
|
| 41 |
+
self.chsize()
|
| 42 |
+
|
| 43 |
+
def remove(self,e):
|
| 44 |
+
self.layout._widgets.remove(e._c_dw)
|
| 45 |
+
self.widgets.remove(e)
|
| 46 |
+
self.chsize()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def block(self,align):
|
| 50 |
+
"""Start a new block.
|
| 51 |
+
|
| 52 |
+
<pre>Document.block(align)</pre>
|
| 53 |
+
|
| 54 |
+
<dl>
|
| 55 |
+
<dt>align<dd>alignment of block (-1,0,1)
|
| 56 |
+
</dl>
|
| 57 |
+
"""
|
| 58 |
+
self.layout.add(align)
|
| 59 |
+
|
| 60 |
+
def space(self,e):
|
| 61 |
+
"""Add a spacer.
|
| 62 |
+
|
| 63 |
+
<pre>Document.space(e)</pre>
|
| 64 |
+
|
| 65 |
+
<dl>
|
| 66 |
+
<dt>e<dd>a (w,h) size for the spacer
|
| 67 |
+
</dl>
|
| 68 |
+
"""
|
| 69 |
+
self.layout.add(e)
|
| 70 |
+
|
| 71 |
+
def br(self,height):
|
| 72 |
+
"""Add a line break.
|
| 73 |
+
|
| 74 |
+
<pre>Document.br(height)</pre>
|
| 75 |
+
|
| 76 |
+
<dl>
|
| 77 |
+
<dt>height<dd>height of line break
|
| 78 |
+
</dl>
|
| 79 |
+
"""
|
| 80 |
+
self.layout.add((0,height))
|
| 81 |
+
|
| 82 |
+
def resize(self,width=None,height=None):
|
| 83 |
+
if self.style.width: width = self.style.width
|
| 84 |
+
if self.style.height: height = self.style.height
|
| 85 |
+
|
| 86 |
+
for w in self.widgets:
|
| 87 |
+
w.rect.w,w.rect.h = w.resize()
|
| 88 |
+
|
| 89 |
+
if (width != None and w.rect.w > width) or (height != None and w.rect.h > height):
|
| 90 |
+
w.rect.w,w.rect.h = w.resize(width,height)
|
| 91 |
+
|
| 92 |
+
dw = w._c_dw
|
| 93 |
+
dw.rect = pygame.Rect(0,0,w.rect.w,w.rect.h)
|
| 94 |
+
|
| 95 |
+
if width == None: width = 65535
|
| 96 |
+
self.layout.rect = pygame.Rect(0,0,width,0)
|
| 97 |
+
self.layout.resize()
|
| 98 |
+
|
| 99 |
+
_max_w = 0
|
| 100 |
+
|
| 101 |
+
for w in self.widgets:
|
| 102 |
+
#xt,xl,xb,xr = w.getspacing()
|
| 103 |
+
dw = w._c_dw
|
| 104 |
+
w.style.x,w.style.y,w.rect.w,w.rect.h = dw.rect.x,dw.rect.y,dw.rect.w,dw.rect.h
|
| 105 |
+
#w.resize()
|
| 106 |
+
w.rect.x,w.rect.y = w.style.x,w.style.y
|
| 107 |
+
_max_w = max(_max_w,w.rect.right)
|
| 108 |
+
|
| 109 |
+
#self.rect.w = _max_w #self.layout.rect.w
|
| 110 |
+
#self.rect.h = self.layout.rect.h
|
| 111 |
+
#print 'document',_max_w,self.layout.rect.h
|
| 112 |
+
return _max_w,self.layout.rect.h
|
code/train/Python/0053584_test_pyregrid.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
def build_analytic_field(field, grid, domask):
|
| 3 |
+
'''
|
| 4 |
+
PRECONDITIONS: An ESMP_Field has been created as 'field'. 'grid' has
|
| 5 |
+
been created and coordinates have been set on both the
|
| 6 |
+
center and corner stagger locations. 'mask' holds the
|
| 7 |
+
masked values of 'grid'.\n
|
| 8 |
+
POSTCONDITIONS: The 'field' has been initialized to an analytic field.\n
|
| 9 |
+
RETURN VALUES: \n ESMP_Field :: field \n
|
| 10 |
+
'''
|
| 11 |
+
DEG2RAD = 3.141592653589793/180.0
|
| 12 |
+
|
| 13 |
+
# get the field pointer
|
| 14 |
+
fieldPtr = ESMP.ESMP_FieldGetPtr(field)
|
| 15 |
+
|
| 16 |
+
# get the grid bounds and coordinate pointers
|
| 17 |
+
exLB, exUB = ESMP.ESMP_GridGetCoord(grid, ESMP.ESMP_STAGGERLOC_CENTER)
|
| 18 |
+
|
| 19 |
+
# get the mask
|
| 20 |
+
if domask:
|
| 21 |
+
mask = ESMP.ESMP_GridGetItem(grid, item=ESMP.ESMP_GRIDITEM_MASK)
|
| 22 |
+
|
| 23 |
+
# get the coordinate pointers and set the coordinates
|
| 24 |
+
[x,y] = [0, 1]
|
| 25 |
+
gridXCoord = ESMP.ESMP_GridGetCoordPtr(grid, x, ESMP.ESMP_STAGGERLOC_CENTER)
|
| 26 |
+
gridYCoord = ESMP.ESMP_GridGetCoordPtr(grid, y, ESMP.ESMP_STAGGERLOC_CENTER)
|
| 27 |
+
|
| 28 |
+
p = 0
|
| 29 |
+
for i1 in range(exLB[1], exUB[1]):
|
| 30 |
+
for i0 in range(exLB[0], exUB[0]):
|
| 31 |
+
theta = DEG2RAD*gridXCoord[p]
|
| 32 |
+
phi = DEG2RAD*(90.0 - gridYCoord[p])
|
| 33 |
+
fieldPtr[p] = 2.0 + np.cos(theta)**2 * np.cos(2.0*phi)
|
| 34 |
+
p = p + 1
|
| 35 |
+
|
| 36 |
+
'''
|
| 37 |
+
theta = np.array(DEG2RAD*gridXCoord[:])
|
| 38 |
+
phi = np.array(DEG2RAD*(90. - gridYCoord[:]))
|
| 39 |
+
fieldPtr[:] = 2. + np.cos(theta[:])**2 * np.cos(2.*phi[:])
|
| 40 |
+
'''
|
| 41 |
+
return field
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def compute_mass(valuefield, areafield, fracfield, dofrac):
|
| 45 |
+
'''
|
| 46 |
+
PRECONDITIONS: Two ESMP_Fields have been created and initialized. 'valuefield'
|
| 47 |
+
contains data values of a field built on the cells of a grid,
|
| 48 |
+
'areafield' contains the areas associated with the grid
|
| 49 |
+
cells, and 'fracfield' contains the fractions of each cell
|
| 50 |
+
which contributed to a regridding operation involving
|
| 51 |
+
'valuefield. 'dofrac' is a boolean value that gives the
|
| 52 |
+
option to not use the 'fracfield'.\n
|
| 53 |
+
POSTCONDITIONS: The mass of the data field is computed and returned.\n
|
| 54 |
+
RETURN VALUES: integer :: mass \n
|
| 55 |
+
'''
|
| 56 |
+
|
| 57 |
+
mass = 0.0
|
| 58 |
+
ESMP.ESMP_FieldRegridGetArea(areafield)
|
| 59 |
+
area = ESMP.ESMP_FieldGetPtr(areafield)
|
| 60 |
+
value = ESMP.ESMP_FieldGetPtr(valuefield)
|
| 61 |
+
frac = 0
|
| 62 |
+
if dofrac:
|
| 63 |
+
frac = ESMP.ESMP_FieldGetPtr(fracfield)
|
| 64 |
+
|
| 65 |
+
for i in range(valuefield.size):
|
| 66 |
+
if dofrac:
|
| 67 |
+
mass += area[i]*value[i]*frac[i]
|
| 68 |
+
else:
|
| 69 |
+
mass += area[i]*value[i]
|
| 70 |
+
|
| 71 |
+
return (mass, area)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def compare_fields(interp_field, exact_field, dstfracfield, srcmass, dstmass):
|
| 75 |
+
'''
|
| 76 |
+
PRECONDITIONS: 'interp_field' is a Field that holds the values resulting
|
| 77 |
+
from a regridding operation, 'exact_field' is a Field
|
| 78 |
+
containing the values of the exact solution that is
|
| 79 |
+
expected, and 'dstfracfield' is a Field containing the
|
| 80 |
+
fractions of the 'interp_field' which contributed to the
|
| 81 |
+
regridding product. 'srcmass' and 'dstmass' are the
|
| 82 |
+
mass values for the source and destination data fields. \n
|
| 83 |
+
POSTCONDITIONS: The interpolation accuracy of a regridding operation is
|
| 84 |
+
determined by comparing the 'interp_field' to the
|
| 85 |
+
'exact_field'. The mass conservation is validated by
|
| 86 |
+
comparing the 'srcmass' to the 'dstmass'.\n
|
| 87 |
+
RETURN VALUES: None \n
|
| 88 |
+
'''
|
| 89 |
+
|
| 90 |
+
vm = ESMP.ESMP_VMGetGlobal()
|
| 91 |
+
localPet, _ = ESMP.ESMP_VMGet(vm)
|
| 92 |
+
|
| 93 |
+
# get the data pointers for the fields
|
| 94 |
+
interp = ESMP.ESMP_FieldGetPtr(interp_field)
|
| 95 |
+
exact = ESMP.ESMP_FieldGetPtr(exact_field)
|
| 96 |
+
dstfrac = ESMP.ESMP_FieldGetPtr(dstfracfield)
|
| 97 |
+
|
| 98 |
+
if (interp_field.size != exact_field.size):
|
| 99 |
+
raise TypeError('compare_fields: Fields must be the same size!')
|
| 100 |
+
|
| 101 |
+
# initialize to True, and check for False point values
|
| 102 |
+
total_error = 0.0
|
| 103 |
+
max_error = 0.0
|
| 104 |
+
min_error = 1000000.0
|
| 105 |
+
for i in range(interp_field.size):
|
| 106 |
+
if (exact[i] != 0.0):
|
| 107 |
+
err = abs(interp[i]/dstfrac[i] - exact[i])/abs(exact[i])
|
| 108 |
+
else:
|
| 109 |
+
err = abs(interp[i]/dstfrac[i] - exact[i])
|
| 110 |
+
total_error = total_error + err
|
| 111 |
+
|
| 112 |
+
if (err > max_error):
|
| 113 |
+
max_error = err
|
| 114 |
+
if (err < min_error):
|
| 115 |
+
min_error = err
|
| 116 |
+
|
| 117 |
+
# check the mass
|
| 118 |
+
csrv = False
|
| 119 |
+
csrv_error = abs(dstmass - srcmass)/srcmass
|
| 120 |
+
if (csrv_error < 10e-12):
|
| 121 |
+
csrv = True
|
| 122 |
+
itrp = False
|
| 123 |
+
if (max_error < 10E-2):
|
| 124 |
+
itrp = True
|
| 125 |
+
|
| 126 |
+
if (itrp and csrv):
|
| 127 |
+
print "PASS"
|
| 128 |
+
else:
|
| 129 |
+
print "FAIL"
|
| 130 |
+
print " Total error = "+str(total_error)
|
| 131 |
+
print " Max error = "+str(max_error)
|
| 132 |
+
print " Min error = "+str(min_error)
|
| 133 |
+
print " Csrv error = "+str(csrv_error)
|
| 134 |
+
print " srcmass = "+str(srcmass)
|
| 135 |
+
print " dstmass = "+str(dstmass)
|
| 136 |
+
|
| 137 |
+
return
|
| 138 |
+
|
| 139 |
+
def test_regrid():
|
| 140 |
+
"""
|
| 141 |
+
Check the OASIS grids by regridding and analytic function and comparing to the expected result.
|
| 142 |
+
|
| 143 |
+
This does not pass, although close. Need to experiment with some different grid setups to see
|
| 144 |
+
what's going on. Leave this for now.
|
| 145 |
+
"""
|
| 146 |
+
src_grid, dest_grid, src_field, dest_field, src_frac, dest_frac, src_area, dest_area = setup_grid_and_fields()
|
| 147 |
+
|
| 148 |
+
dest_exact = ESMP.ESMP_FieldCreateGrid(dest_grid, 'dest_exact')
|
| 149 |
+
|
| 150 |
+
# Intialise analytic test field.
|
| 151 |
+
src_field = build_analytic_field(src_field, src_grid, False)
|
| 152 |
+
dest_exact = build_analytic_field(dest_exact, dest_grid, False)
|
| 153 |
+
|
| 154 |
+
# Do the regridding
|
| 155 |
+
dest_field, src_frac, dest_frac = run_regridding(src_field, dest_field, src_frac, dest_frac)
|
| 156 |
+
|
| 157 |
+
# Compute mass
|
| 158 |
+
src_mass, _ = compute_mass(src_field, src_area, src_frac, True)
|
| 159 |
+
dest_mass, _ = compute_mass(dest_field, dest_area, 0, False)
|
| 160 |
+
|
| 161 |
+
compare_fields(dest_field, dest_exact, dest_frac, src_mass, dest_mass)
|
| 162 |
+
|
code/train/Python/0053695_timeseries.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from PyQt4 import QtGui, QtCore
|
| 6 |
+
from qt_ui.ui_timeseries import Ui_Timeseries
|
| 7 |
+
|
| 8 |
+
from PyQt4.Qt import *
|
| 9 |
+
from PyQt4.Qwt5 import *
|
| 10 |
+
from PyQt4.Qwt5.qplt import *
|
| 11 |
+
|
| 12 |
+
import snippet
|
| 13 |
+
|
| 14 |
+
class TimeseriesWindow(QtGui.QWidget):
|
| 15 |
+
def __init__(self, player, parent=None):
|
| 16 |
+
QtGui.QWidget.__init__(self, parent)
|
| 17 |
+
self.ui = Ui_Timeseries()
|
| 18 |
+
self.ui.setupUi(self)
|
| 19 |
+
self.img = None
|
| 20 |
+
|
| 21 |
+
def show_img(self,npimg):
|
| 22 |
+
self.img = cv2.cvtColor(npimg,cv2.COLOR_BGR2BGRA)
|
| 23 |
+
h, w ,c = self.img.shape
|
| 24 |
+
|
| 25 |
+
# Qt expects 32bit BGRA data for color images:
|
| 26 |
+
self.qimg = QtGui.QImage(self.img.data, w, h, QtGui.QImage.Format_RGB32)
|
| 27 |
+
self.qimg.ndarray = self.img
|
| 28 |
+
|
| 29 |
+
scene = QtGui.QGraphicsScene()
|
| 30 |
+
scene.addPixmap(QtGui.QPixmap(self.qimg))
|
| 31 |
+
self.ui.graphicsView.setScene(scene)
|
| 32 |
+
|
| 33 |
+
class TimeSeries:
|
| 34 |
+
"""A time series is a time-ordered vector of (time, value)-vectors. Time is
|
| 35 |
+
given in seconds (float) and value is any numeric format."""
|
| 36 |
+
|
| 37 |
+
def __init__(self, filename, label = "noname", approx = "none"):
|
| 38 |
+
"""filename: path to text-file of tab-separated values
|
| 39 |
+
label (optional): string that describe this time series
|
| 40 |
+
approx (default=none): approximation type between values (actually just none)"""
|
| 41 |
+
|
| 42 |
+
self.filename = filename
|
| 43 |
+
self.data = np.loadtxt(filename)
|
| 44 |
+
self.val_min = np.amin(self.data[:,1])
|
| 45 |
+
self.val_max = np.amax(self.data[:,1])
|
| 46 |
+
self.label = label
|
| 47 |
+
self.equal_tupel_length = self.calc_tupel_length()
|
| 48 |
+
self.approx = approx
|
| 49 |
+
self.act_pos = 0
|
| 50 |
+
|
| 51 |
+
#self.win_w = 300
|
| 52 |
+
#self.win_h = 200
|
| 53 |
+
#self.win = None
|
| 54 |
+
#self.img = np.zeros((self.win_h,self.win_w,3),'uint8')
|
| 55 |
+
|
| 56 |
+
self.p = Plot(
|
| 57 |
+
Curve(self.data[:,0], self.data[:,1], Pen(Magenta, 2), self.label))
|
| 58 |
+
#Curve([self.act_pos, self.act_pos], [self.val_min, self.val_max], Pen(Red), "pos"))
|
| 59 |
+
#self.p.setAxisScale(2,0,200)
|
| 60 |
+
self.m = QwtPlotMarker()
|
| 61 |
+
self.m.setLineStyle(2)
|
| 62 |
+
self.m.attach(self.p)
|
| 63 |
+
|
| 64 |
+
def show(self, time):
|
| 65 |
+
self.act_pos = time
|
| 66 |
+
#if self.p.AxisInterval(2)
|
| 67 |
+
#self.p.set
|
| 68 |
+
self.m.setXValue(self.act_pos)
|
| 69 |
+
self.p.replot()
|
| 70 |
+
"""
|
| 71 |
+
if self.win is None:
|
| 72 |
+
self.win = TimeseriesWindow(self)
|
| 73 |
+
self.win.setWindowTitle(self.label)
|
| 74 |
+
self.win
|
| 75 |
+
self.win.show()
|
| 76 |
+
|
| 77 |
+
val = self.get_elem(time)
|
| 78 |
+
p_val = int((val-self.val_min) / (self.val_max-self.val_min) * self.win_h)
|
| 79 |
+
|
| 80 |
+
# shift left
|
| 81 |
+
self.img[:,0:self.win_w-1,:] = self.img[:,1:self.win_w,:]
|
| 82 |
+
self.img[:,self.win_w-1,:] = 0
|
| 83 |
+
# draw value
|
| 84 |
+
self.img[p_val,self.win_w-1,:] = 255
|
| 85 |
+
|
| 86 |
+
#cv2.imshow('sd',self.img)
|
| 87 |
+
self.win.show_img(self.img)
|
| 88 |
+
|
| 89 |
+
pass
|
| 90 |
+
#self.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
def get_elem(self, request_time):
|
| 94 |
+
"""returns the value of the time series at a specific time point"""
|
| 95 |
+
if self.approx == "none":
|
| 96 |
+
if self.equal_tupel_length > 0:
|
| 97 |
+
n = int( (request_time - self.data[0,0]) / self.equal_tupel_length)
|
| 98 |
+
return self.data[n][1]
|
| 99 |
+
else:
|
| 100 |
+
print "ERROR: not implemented yet" #TODO
|
| 101 |
+
return None
|
| 102 |
+
else:
|
| 103 |
+
print "ERROR: only approx = 'none' implemented"
|
| 104 |
+
|
| 105 |
+
def calc_tupel_length(self):
|
| 106 |
+
"""returns the duration of one tupel, if constant. Otherwise returns -1"""
|
| 107 |
+
dist = self.data[1,0]-self.data[0,0]
|
| 108 |
+
for i in range(len(self.data)-1):
|
| 109 |
+
if dist != (self.data[i+1,0]-self.data[i,0]):
|
| 110 |
+
return -1
|
| 111 |
+
|
| 112 |
+
return dist
|
| 113 |
+
|
| 114 |
+
def get_snippets(self, offset = 0, function = None ):
|
| 115 |
+
"""returns a list of snippets where function returns true if calculated
|
| 116 |
+
with time series values"""
|
| 117 |
+
snippets = []
|
| 118 |
+
if self.approx == "none":
|
| 119 |
+
last_val = False
|
| 120 |
+
begin = 0
|
| 121 |
+
end = 0
|
| 122 |
+
for (i,val) in self.data:
|
| 123 |
+
if function is None:
|
| 124 |
+
act_val = bool(val > 0)
|
| 125 |
+
else:
|
| 126 |
+
act_val = function(val)
|
| 127 |
+
if last_val != act_val:
|
| 128 |
+
if act_val:
|
| 129 |
+
begin = i
|
| 130 |
+
else:
|
| 131 |
+
end = i
|
| 132 |
+
snippets.append(snippet.Snippet(min(max(0,begin+offset),self.data[len(self.data)-1,0]), end-begin, self.label))
|
| 133 |
+
last_val = act_val
|
| 134 |
+
|
| 135 |
+
return snippets
|
| 136 |
+
|
| 137 |
+
# TODO delete (helper function for testing get_snippets)
|
| 138 |
+
def greater_zero(a):
|
| 139 |
+
return a>0
|
| 140 |
+
|
code/train/Python/0054658_8.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The four adjacent digits in the 1000-digit number that have the greatest
|
| 3 |
+
product are 9 × 9 × 8 × 9 = 5832.
|
| 4 |
+
|
| 5 |
+
{{ 8_input.txt }}
|
| 6 |
+
|
| 7 |
+
Find the thirteen adjacent digits in the 1000-digit number that have the
|
| 8 |
+
greatest product. What is the value of this product?
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from os.path import dirname, abspath, join
|
| 12 |
+
|
| 13 |
+
if __name__ == '__main__':
|
| 14 |
+
|
| 15 |
+
digits = 13
|
| 16 |
+
with open(join(dirname(abspath(__file__)), '8_input.txt')) as f:
|
| 17 |
+
number = ''.join(f.read().splitlines())
|
| 18 |
+
|
| 19 |
+
greatest_product = 0
|
| 20 |
+
for i in range(len(number) - digits + 1):
|
| 21 |
+
product = 1
|
| 22 |
+
for j in range(i, i + digits):
|
| 23 |
+
product *= int(number[j])
|
| 24 |
+
if product > greatest_product:
|
| 25 |
+
greatest_product = product
|
| 26 |
+
|
| 27 |
+
print(greatest_product)
|
code/train/Python/0054760_vocaCreator.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests, os
|
| 2 |
+
from bs4 import BeautifulSoup
|
| 3 |
+
from termcolor import colored
|
| 4 |
+
from voca.vocaDict import vocaDict
|
| 5 |
+
from voca.vocaUtil import vocaUtil
|
| 6 |
+
|
| 7 |
+
class vocaCreator(vocaUtil):
|
| 8 |
+
def __init__(self):
|
| 9 |
+
self.refrance_url = 'https://www.vocabulary.com/dictionary/%s'
|
| 10 |
+
self.sentence_url = 'http://sentence.yourdictionary.com/%s'
|
| 11 |
+
self.write_dict_flag = False
|
| 12 |
+
self.short = ''
|
| 13 |
+
self.long = ''
|
| 14 |
+
self.sentences = []
|
| 15 |
+
|
| 16 |
+
def looking_for_list(self, SEARCH_LIST):
|
| 17 |
+
if SEARCH_LIST:
|
| 18 |
+
for word in SEARCH_LIST:
|
| 19 |
+
word = word.lower()
|
| 20 |
+
short_text, long_text, sentences = self.check_word_in_local_dect(word)
|
| 21 |
+
if not short_text:
|
| 22 |
+
self.short, self.long = self.get_description(word)
|
| 23 |
+
if not self.short:
|
| 24 |
+
continue
|
| 25 |
+
self.sentences = self.get_sentences(word)
|
| 26 |
+
self.update_dict(word, self.short, self.long, self.sentences)
|
| 27 |
+
else:
|
| 28 |
+
self.print_short_description(word, short_text)
|
| 29 |
+
self.print_long_description(long_text)
|
| 30 |
+
self.print_sentences(sentences)
|
| 31 |
+
if self.write_dict_flag:
|
| 32 |
+
self.write_dict()
|
| 33 |
+
|
| 34 |
+
def get_description(self, word):
|
| 35 |
+
self.write_dict_flag = True
|
| 36 |
+
content = requests.get(url=self.refrance_url % word).content
|
| 37 |
+
soup = BeautifulSoup(content, 'lxml')
|
| 38 |
+
short = self.get_short_description(word, soup)
|
| 39 |
+
long = self.get_long_description(soup)
|
| 40 |
+
return short, long
|
| 41 |
+
|
| 42 |
+
def get_sentences(self, word):
|
| 43 |
+
sentences = []
|
| 44 |
+
content = requests.get(url=self.sentence_url % word).content
|
| 45 |
+
soup = BeautifulSoup(content, 'lxml')
|
| 46 |
+
data = soup.findAll('div', attrs={'class': 'li_content'})
|
| 47 |
+
if data:
|
| 48 |
+
for index in range(3):
|
| 49 |
+
sentence = data[index].getText()
|
| 50 |
+
sentences.append(sentence)
|
| 51 |
+
vocaCreator.print_sentences(self, sentences)
|
| 52 |
+
return sentences
|
| 53 |
+
|
| 54 |
+
def get_short_description(self, word, soup):
|
| 55 |
+
short = soup.findAll('p', attrs={'class': 'short'})
|
| 56 |
+
if short:
|
| 57 |
+
short_text = short[0].getText()
|
| 58 |
+
vocaCreator.print_short_description(self, word, short_text)
|
| 59 |
+
return short_text
|
| 60 |
+
else:
|
| 61 |
+
print(colored(' * There is no description :( !!', 'red'))
|
| 62 |
+
|
| 63 |
+
def get_long_description(self, soup):
|
| 64 |
+
long = soup.findAll('p', attrs={'class': 'long'})
|
| 65 |
+
if long:
|
| 66 |
+
long_text = long[0].getText()
|
| 67 |
+
vocaCreator.print_long_description(self, long_text)
|
| 68 |
+
return long_text
|
| 69 |
+
|
| 70 |
+
@staticmethod
|
| 71 |
+
def update_dict(word, short, long, sentences):
|
| 72 |
+
vocaDict[word] = {'short': short,
|
| 73 |
+
'long': long,
|
| 74 |
+
'sentences': sentences}
|
| 75 |
+
|
| 76 |
+
@staticmethod
|
| 77 |
+
def write_dict():
|
| 78 |
+
script_dir = os.path.dirname(__file__)
|
| 79 |
+
voca_path = os.path.join(script_dir, 'vocaDict.py')
|
| 80 |
+
tmp = open(voca_path, 'w')
|
| 81 |
+
tmp.write('vocaDict = %s' % str(vocaDict))
|
| 82 |
+
tmp.close()
|
code/train/Python/0055295_shuffling.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import chain, groupby
|
| 2 |
+
from operator import attrgetter
|
| 3 |
+
import random as random_mod
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def weighted_pick(x, key_weight=None):
|
| 7 |
+
"""Returns one element from the sequence x.
|
| 8 |
+
A "heavy" element is more likely to be picked.
|
| 9 |
+
The `key_weight` argument can be used to define how to access the element's weight.
|
| 10 |
+
By default, we assume x to be a sequence of (element, weight) tuples.
|
| 11 |
+
"""
|
| 12 |
+
if key_weight is None:
|
| 13 |
+
key_weight = lambda t: t[1]
|
| 14 |
+
|
| 15 |
+
total_weights = sum(key_weight(e) for e in x)
|
| 16 |
+
target = random_mod.randint(0, total_weights)
|
| 17 |
+
for e in x:
|
| 18 |
+
target -= e[1]
|
| 19 |
+
if target <= 0:
|
| 20 |
+
return e[0]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def weighted_shuffle(x, key_weight=None):
|
| 24 |
+
"""Shuffles the sequence x in place.
|
| 25 |
+
Elements that are "heavier" will be more likely to be at the beginning.
|
| 26 |
+
The `key_weight` argument can be used to define how to access the element's weight.
|
| 27 |
+
By default, we assume x to be a sequence of (element, weight) tuples.
|
| 28 |
+
"""
|
| 29 |
+
if key_weight is None:
|
| 30 |
+
key_weight = lambda t: t[1]
|
| 31 |
+
|
| 32 |
+
weights = [(i, key_weight(e)) for e in enumerate(x)]
|
| 33 |
+
|
| 34 |
+
for i in reversed(xrange(1, len(x))):
|
| 35 |
+
j = weighted_pick(weights[:i+1])
|
| 36 |
+
x[i], x[j] = x[j], x[i]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def shuffled(iterable, weight=None):
|
| 40 |
+
"""
|
| 41 |
+
Return a shuffled copy of the given iterable.
|
| 42 |
+
If a callable is passed for `weight`, then a weighted_shuffle will be used.
|
| 43 |
+
If not, a plain random.shuffle will be used.
|
| 44 |
+
"""
|
| 45 |
+
l = list(iterable) # copy
|
| 46 |
+
if weight is None:
|
| 47 |
+
random_mod.shuffle(l)
|
| 48 |
+
else:
|
| 49 |
+
weighted_shuffle(l, key_weight=weight)
|
| 50 |
+
return l
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def sequential(elements, key=attrgetter('position')):
|
| 54 |
+
return sorted(elements, key=key)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def random(elements):
|
| 58 |
+
return shuffled(elements)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def weighted_random(elements, key=attrgetter('position')):
|
| 62 |
+
l = list(elements)
|
| 63 |
+
weighted_shuffle(l, key_weight=key)
|
| 64 |
+
return l
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def cluster_random(elements, key=attrgetter('position')):
|
| 68 |
+
ordered = sorted(elements, key=key)
|
| 69 |
+
grouped = groupby(ordered, key=key)
|
| 70 |
+
clustered = chain.from_iterable(shuffled(elements) for _, elements in grouped)
|
| 71 |
+
return list(clustered)
|
code/train/Python/0056031_pyrmEval.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import sys
|
| 3 |
+
#slices a list into n nearly-equal-length partitions
|
| 4 |
+
#returns list of lists
|
| 5 |
+
def random_partition(lst, n, shuffle=True):
|
| 6 |
+
if shuffle is True:
|
| 7 |
+
random.shuffle(lst) #optional
|
| 8 |
+
division = len(lst) / float(n)
|
| 9 |
+
return [ lst[int(round(division * i)): int(round(division * (i+1)))] for i in xrange(n) ]
|
| 10 |
+
|
| 11 |
+
#Randomly resamples labeled datasets into comprehensive training set and test set
|
| 12 |
+
#reshuffles data and returns training/test sets as list of dictionaries
|
| 13 |
+
#the arguments should be lists that represent classes
|
| 14 |
+
|
| 15 |
+
#output: tuple
|
| 16 |
+
def make_training_and_test_set(trainProportion, shuffle=True, **kwargs):
|
| 17 |
+
if trainProportion > 1.0 or trainProportion < 0.0:
|
| 18 |
+
raise ValueError('trainPartition can only be between 0 and 1.0')
|
| 19 |
+
training_data = []
|
| 20 |
+
test_data = []
|
| 21 |
+
for key, class_list in kwargs.iteritems():
|
| 22 |
+
if shuffle is True:
|
| 23 |
+
random.shuffle(class_list) #optional
|
| 24 |
+
trainIndex = trainProportion * len(class_list) #calculates index for end of training set
|
| 25 |
+
trainIndex = int(round(trainIndex))
|
| 26 |
+
training_data.append( {key : class_list[:trainIndex]} ) #partitions training set from start to random index
|
| 27 |
+
test_data.append( {key : class_list[trainIndex:]} ) #partition test set from random index to end
|
| 28 |
+
return (training_data, test_data)
|
| 29 |
+
|
| 30 |
+
#perform n-fold cross validation
|
| 31 |
+
#returns list of lists of dictionaries
|
| 32 |
+
def create_cross_validate_set(n, shuffle=True, **kwargs):
|
| 33 |
+
dataset = []
|
| 34 |
+
for key, value_list in kwargs.items():
|
| 35 |
+
for values in value_list:
|
| 36 |
+
dataset.append({ key : values })
|
| 37 |
+
#dataset, filler = make_training_and_test_set(1.0, True, **kwargs)
|
| 38 |
+
subpartitions = random_partition(dataset, n)
|
| 39 |
+
return subpartitions
|
code/train/Python/0056597_test_study_get.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
import sys, os
|
| 3 |
+
from opentreetesting import test_http_json_method, config, get_response_from_http
|
| 4 |
+
from peyotl import convert_nexson_format
|
| 5 |
+
|
| 6 |
+
DOMAIN = config('host', 'apihost')
|
| 7 |
+
SUBMIT_URI = DOMAIN + '/v4/study/list'
|
| 8 |
+
#sys.stderr.write('Calling "{}"...\study_obj'.format(SUBMIT_URI))
|
| 9 |
+
r = test_http_json_method(SUBMIT_URI,
|
| 10 |
+
'GET',
|
| 11 |
+
expected_status=200,
|
| 12 |
+
return_bool_data=True)
|
| 13 |
+
if not r[0]:
|
| 14 |
+
sys.exit(1)
|
| 15 |
+
|
| 16 |
+
def do_tree_test_get(study_id, tree_id):
|
| 17 |
+
NEXUS_SUBMIT_URI = DOMAIN + '/v1/study/{}/tree/{}.nex'.format(study_id, tree_id)
|
| 18 |
+
t = get_response_from_http(NEXUS_SUBMIT_URI, 'GET')
|
| 19 |
+
nexus = t.content
|
| 20 |
+
if not nexus.startswith('#NEXUS'):
|
| 21 |
+
sys.exit('Did not get content starting with #NEXUS')
|
| 22 |
+
data = {'tip_label': 'ot:ottTaxonName'}
|
| 23 |
+
NEWICK_SUBMIT_URI = DOMAIN + '/v1/study/{}/tree/{}.tre'.format(study_id, tree_id)
|
| 24 |
+
r = test_http_json_method(NEWICK_SUBMIT_URI,
|
| 25 |
+
'GET',
|
| 26 |
+
data=data,
|
| 27 |
+
expected_status=200,
|
| 28 |
+
return_bool_data=True,
|
| 29 |
+
is_json=False)
|
| 30 |
+
if r[0]:
|
| 31 |
+
assert r[1].startswith('(')
|
| 32 |
+
assert '[pre-ingroup-marker]' not in r[1]
|
| 33 |
+
else:
|
| 34 |
+
sys.exit(1)
|
| 35 |
+
data['bracket_ingroup'] = True
|
| 36 |
+
r = test_http_json_method(NEWICK_SUBMIT_URI,
|
| 37 |
+
'GET',
|
| 38 |
+
data=data,
|
| 39 |
+
expected_status=200,
|
| 40 |
+
return_bool_data=True,
|
| 41 |
+
is_json=False)
|
| 42 |
+
if r[0]:
|
| 43 |
+
assert r[1].startswith('(')
|
| 44 |
+
assert '[pre-ingroup-marker]' in r[1]
|
| 45 |
+
else:
|
| 46 |
+
sys.exit(1)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def dict_eq(a, b):
|
| 50 |
+
if a == b:
|
| 51 |
+
return True
|
| 52 |
+
d = True
|
| 53 |
+
ka, kb = a.keys(), b.keys()
|
| 54 |
+
ka.sort()
|
| 55 |
+
kb.sort()
|
| 56 |
+
if ka != kb:
|
| 57 |
+
sa = set(ka)
|
| 58 |
+
sb = set(kb)
|
| 59 |
+
ao = sa - sb
|
| 60 |
+
ao = list(ao)
|
| 61 |
+
ao.sort()
|
| 62 |
+
bo = sb - sa
|
| 63 |
+
c = {u'^ot:candidateTreeForSynthesis', u'^ot:tag'}
|
| 64 |
+
bextra = bo - c
|
| 65 |
+
bo = list(bextra)
|
| 66 |
+
bo.sort()
|
| 67 |
+
if bextra or ao:
|
| 68 |
+
sys.stdout.write(' keys in a only "{a}"."\n'.format(a=ao))
|
| 69 |
+
sys.stdout.write(' keys in b only "{a}"."\n'.format(a=bo))
|
| 70 |
+
d = False
|
| 71 |
+
for k in ka:
|
| 72 |
+
if k in kb:
|
| 73 |
+
va = a[k]
|
| 74 |
+
vb = b[k]
|
| 75 |
+
if va != vb:
|
| 76 |
+
if isinstance(va, dict) and isinstance(vb, dict):
|
| 77 |
+
if not dict_eq(va, vb):
|
| 78 |
+
d = False
|
| 79 |
+
elif isinstance(va, list) and isinstance(vb, list):
|
| 80 |
+
for n, ela in enumerate(va):
|
| 81 |
+
elb = vb[n]
|
| 82 |
+
if not dict_eq(ela, elb):
|
| 83 |
+
d = False
|
| 84 |
+
if len(va) != len(vb):
|
| 85 |
+
d = False
|
| 86 |
+
sys.stdout.write(' lists for {} differ in length.\n'.format(k))
|
| 87 |
+
else:
|
| 88 |
+
d = False
|
| 89 |
+
sys.stdout.write(' value for {k}: "{a}" != "{b}"\n'.format(k=k, a=va, b=vb))
|
| 90 |
+
else:
|
| 91 |
+
d = False
|
| 92 |
+
return d
|
| 93 |
+
|
| 94 |
+
# loop over studies to find one with a tree so we can test the tree_get...
|
| 95 |
+
for study_id in r[1]:
|
| 96 |
+
SUBMIT_URI = DOMAIN + '/v1/study/{}'.format(study_id)
|
| 97 |
+
# a bogus value for nexml2json should give us a 400
|
| 98 |
+
data = {'output_nexml2json': 'x1.2.1'}
|
| 99 |
+
test_http_json_method(SUBMIT_URI, 'GET', data=data, expected_status=400)
|
| 100 |
+
# now get the study in the "legacy" format
|
| 101 |
+
data = {'output_nexml2json': '0.0.0'}
|
| 102 |
+
pb = test_http_json_method(SUBMIT_URI, 'GET', data=data, expected_status=200, return_bool_data=True)
|
| 103 |
+
if not pb[0]:
|
| 104 |
+
sys.exit(1)
|
| 105 |
+
# ... and in our transitional format...
|
| 106 |
+
data = {'output_nexml2json': '1.0.0'}
|
| 107 |
+
pl = test_http_json_method(SUBMIT_URI, 'GET', data=data, expected_status=200, return_bool_data=True)
|
| 108 |
+
if not pl[0]:
|
| 109 |
+
sys.exit(1)
|
| 110 |
+
badger = pb[1]['data']
|
| 111 |
+
legacy = pl[1]['data']
|
| 112 |
+
# ...they should differ...
|
| 113 |
+
assert (badger != legacy)
|
| 114 |
+
# ... but convertable to the same info...
|
| 115 |
+
lfromb = convert_nexson_format(badger, '1.0.0', current_format='0.0.0')
|
| 116 |
+
if lfromb != legacy:
|
| 117 |
+
with open('.tmp1', 'w') as fo_one:
|
| 118 |
+
json.dump(legacy, fo_one, indent=0, sort_keys=True)
|
| 119 |
+
with open('.tmp2', 'w') as fo_one:
|
| 120 |
+
json.dump(lfromb, fo_one, indent=0, sort_keys=True)
|
| 121 |
+
assert (dict_eq(lfromb, legacy))
|
| 122 |
+
# ...finally we grab it in HBF...
|
| 123 |
+
data = {'output_nexml2json':'1.2.1'}
|
| 124 |
+
r = test_http_json_method(SUBMIT_URI, 'GET', data=data, expected_status=200, return_bool_data=True)
|
| 125 |
+
if r[0]:
|
| 126 |
+
# ... and do some tests of grabbing just a tree from the study...
|
| 127 |
+
nexm_el = r[1]['data']['nexml']
|
| 128 |
+
if nexm_el["@nexml2json"] != "1.2.1":
|
| 129 |
+
msg = 'requested conversion to NexSON format not performed. nexml_el["@nexml2json"] = {}\n'
|
| 130 |
+
sys.exit(msg.format(nexm_el["@nexml2json"]))
|
| 131 |
+
tree_group_coll_el = nexm_el.get('treesById')
|
| 132 |
+
if tree_group_coll_el:
|
| 133 |
+
for trees_group_id, trees_group in tree_group_coll_el.items():
|
| 134 |
+
if trees_group and trees_group.get('treeById'):
|
| 135 |
+
tree_id_list = list(trees_group['treeById'].keys())
|
| 136 |
+
tree_id_list.sort() #to make the test repeatable...
|
| 137 |
+
tree_id = tree_id_list[0]
|
| 138 |
+
do_tree_test_get(study_id, tree_id)
|
| 139 |
+
sys.exit(0)
|
| 140 |
+
else:
|
| 141 |
+
sys.exit(1)
|
code/train/Python/0057109_train_triplets.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A script to train a triplet distance based model.
|
| 2 |
+
|
| 3 |
+
This script is used to train models that expect to be fed triplets for
|
| 4 |
+
training. Currently it can be used to train EmbedNet, based on the FaceNet
|
| 5 |
+
paper, and TripletNet, based on Hoffer, Ailon: "Deep Metric Learning Using
|
| 6 |
+
Triplet Network".
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
import chainer
|
| 13 |
+
from chainer import cuda
|
| 14 |
+
from chainer import optimizers
|
| 15 |
+
|
| 16 |
+
from tripletembedding.predictors import TripletNet
|
| 17 |
+
from tripletembedding.aux import Logger, load_snapshot
|
| 18 |
+
|
| 19 |
+
from aux import helpers
|
| 20 |
+
from aux.triplet_loader import TripletLoader
|
| 21 |
+
from aux.mcyt_loader import McytLoader
|
| 22 |
+
from aux.index_loader import IndexLoader, load_dict, anchors_in
|
| 23 |
+
|
| 24 |
+
from models.vgg_small import VGGSmall, VGGSmallConv, VGGClf
|
| 25 |
+
from models.vgg_xs import VGGXSClf, VGGXSEmbed
|
| 26 |
+
# import models.vgg_small_legacy as legacy
|
| 27 |
+
import queue
|
| 28 |
+
|
| 29 |
+
import pickle
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
args = helpers.get_args()
|
| 33 |
+
|
| 34 |
+
xp = cuda.cupy if args.gpu >= 0 else np
|
| 35 |
+
dl = IndexLoader(xp)
|
| 36 |
+
|
| 37 |
+
# - old method -
|
| 38 |
+
# train, test = helpers.split_anchors(anchors_in(args.data), args.test)
|
| 39 |
+
|
| 40 |
+
# === inter-class split ===
|
| 41 |
+
data = load_dict(args.data)
|
| 42 |
+
|
| 43 |
+
# - loading existing train/test split for continued training -
|
| 44 |
+
# train_anchors, test_anchors = pickle.load(open('snapshots/16-06-20_vgg_small_triplets/vgg_small_triplets_train_test_split.pkl', 'rb'))
|
| 45 |
+
# - create train and test dictionaries from train/test split -
|
| 46 |
+
# train = {
|
| 47 |
+
# 'Genuine': {label: data['Genuine'][label]
|
| 48 |
+
# for label in train_anchors['Genuine'].keys()},
|
| 49 |
+
# 'Forged': {label: data['Forged'][label]
|
| 50 |
+
# for label in train_anchors['Genuine'].keys()}
|
| 51 |
+
# }
|
| 52 |
+
# test = {
|
| 53 |
+
# 'Genuine': {label: data['Genuine'][label]
|
| 54 |
+
# for label in test_anchors['Genuine'].keys()},
|
| 55 |
+
# 'Forged': {label: data['Forged'][label]
|
| 56 |
+
# for label in test_anchors['Genuine'].keys()}
|
| 57 |
+
# }
|
| 58 |
+
|
| 59 |
+
# - create new inter-class split -
|
| 60 |
+
all_ancs = list(data['Genuine'].keys())
|
| 61 |
+
np.random.shuffle(all_ancs)
|
| 62 |
+
t = int(len(all_ancs) * args.test)
|
| 63 |
+
train_anchors, test_anchors = all_ancs[:-t], all_ancs[-t:]
|
| 64 |
+
# - create train and test dictionaries from train/test split -
|
| 65 |
+
train = {
|
| 66 |
+
'Genuine': {label: data['Genuine'][label] for label in train_anchors},
|
| 67 |
+
'Forged': {label: data['Forged'][label] for label in train_anchors}
|
| 68 |
+
}
|
| 69 |
+
test = {
|
| 70 |
+
'Genuine': {label: data['Genuine'][label] for label in test_anchors},
|
| 71 |
+
'Forged': {label: data['Forged'][label] for label in test_anchors}
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
# === intra-class split -- writer-dependent ===
|
| 75 |
+
# data = load_dict(args.data)
|
| 76 |
+
# train = {group: {} for group in data.keys()}
|
| 77 |
+
# test = {group: {} for group in data.keys()}
|
| 78 |
+
# for group in data.keys():
|
| 79 |
+
# for label in data[group].keys():
|
| 80 |
+
# samples = data[group][label]
|
| 81 |
+
# np.random.shuffle(samples)
|
| 82 |
+
|
| 83 |
+
# t = int(len(samples) * args.test)
|
| 84 |
+
# train[group][label] = samples[:-t]
|
| 85 |
+
# test[group][label] = samples[-t:]
|
| 86 |
+
|
| 87 |
+
# - save train/test split -
|
| 88 |
+
pickle.dump([train, test], open(args.out+'_train_test_split.pkl', 'wb'))
|
| 89 |
+
|
| 90 |
+
model = TripletNet(VGGSmall)
|
| 91 |
+
|
| 92 |
+
if args.gpu >= 0:
|
| 93 |
+
cuda.get_device(args.gpu).use()
|
| 94 |
+
dl.use_device(args.gpu)
|
| 95 |
+
model = model.to_gpu()
|
| 96 |
+
|
| 97 |
+
optimizer = optimizers.MomentumSGD(lr=0.001)
|
| 98 |
+
optimizer.setup(model)
|
| 99 |
+
optimizer.add_hook(chainer.optimizer.WeightDecay(args.weight_decay))
|
| 100 |
+
optimizer.add_hook(chainer.optimizer.GradientClipping(10.0))
|
| 101 |
+
|
| 102 |
+
if args.initmodel and args.resume:
|
| 103 |
+
load_snapshot(args.initmodel, args.resume, model, optimizer)
|
| 104 |
+
print("Continuing from snapshot. LR: {}".format(optimizer.lr))
|
| 105 |
+
|
| 106 |
+
# load pre-trained CNN
|
| 107 |
+
# from chainer import serializers
|
| 108 |
+
# pretrained = VGGClf(100)
|
| 109 |
+
# serializers.load_hdf5(args.initmodel, pretrained)
|
| 110 |
+
# model.cnn.conv.copyparams(pretrained.conv)
|
| 111 |
+
|
| 112 |
+
logger = Logger(args, optimizer, args.out)
|
| 113 |
+
|
| 114 |
+
graph_generated = False
|
| 115 |
+
for _ in range(1, args.epoch + 1):
|
| 116 |
+
time_started = time.time()
|
| 117 |
+
|
| 118 |
+
optimizer.new_epoch()
|
| 119 |
+
print('========\nepoch', optimizer.epoch)
|
| 120 |
+
|
| 121 |
+
# margin = min(3.0, 1.0 + 0.005 * optimizer.epoch**2)
|
| 122 |
+
# print('margin:\t{}'.format(margin))
|
| 123 |
+
margin = 1.0
|
| 124 |
+
|
| 125 |
+
# training
|
| 126 |
+
dl.create_source('train',
|
| 127 |
+
args.batchsize, train, skilled=args.skilled)
|
| 128 |
+
dl.create_source('test',
|
| 129 |
+
args.batchsize, test, skilled=args.skilled)
|
| 130 |
+
|
| 131 |
+
while True:
|
| 132 |
+
model.zerograds()
|
| 133 |
+
model.clean()
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
x_data = dl.get_batch('train')
|
| 137 |
+
except queue.Empty:
|
| 138 |
+
break
|
| 139 |
+
|
| 140 |
+
x = chainer.Variable(x_data)
|
| 141 |
+
optimizer.update(model, x)
|
| 142 |
+
# optimizer.update(model, x, margin)
|
| 143 |
+
logger.log_iteration("train",
|
| 144 |
+
float(model.loss.data), float(model.accuracy),
|
| 145 |
+
float(model.mean_diff), float(model.max_diff))
|
| 146 |
+
|
| 147 |
+
if not graph_generated:
|
| 148 |
+
helpers.write_graph(model.loss)
|
| 149 |
+
graph_generated = True
|
| 150 |
+
|
| 151 |
+
logger.log_mean("train")
|
| 152 |
+
print("iteration time:\t{:.3f} sec"
|
| 153 |
+
.format((time.time() - time_started) / len(train)))
|
| 154 |
+
|
| 155 |
+
if optimizer.epoch % args.lrinterval == 0 and optimizer.lr > 0.000001:
|
| 156 |
+
optimizer.lr *= 0.5
|
| 157 |
+
logger.mark_lr()
|
| 158 |
+
print("learning rate decreased to {}".format(optimizer.lr))
|
| 159 |
+
if optimizer.epoch % args.interval == 0:
|
| 160 |
+
logger.make_snapshot(model)
|
| 161 |
+
|
| 162 |
+
# testing
|
| 163 |
+
while True:
|
| 164 |
+
try:
|
| 165 |
+
x = chainer.Variable(dl.get_batch('test'), volatile=True)
|
| 166 |
+
except queue.Empty:
|
| 167 |
+
break
|
| 168 |
+
loss = model(x)
|
| 169 |
+
logger.log_iteration("test",
|
| 170 |
+
float(model.loss.data), float(model.accuracy),
|
| 171 |
+
float(model.mean_diff), float(model.max_diff))
|
| 172 |
+
logger.log_mean("test")
|
| 173 |
+
|
| 174 |
+
# make final snapshot if not just taken one
|
| 175 |
+
if optimizer.epoch % args.interval != 0:
|
| 176 |
+
logger.make_snapshot(model)
|
code/train/Python/0057194_summary.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from assertEquals.cli.utils import BANNER, BORDER, HEADERS
|
| 7 |
+
from assertEquals.interactive.utils import RefreshError, Process
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger('assertEquals.interactive.summary')
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Summary:
|
| 14 |
+
"""Represent the data from an inter-process summarize() call.
|
| 15 |
+
|
| 16 |
+
This is designed to be a persistent object. Repeated calls to refresh will
|
| 17 |
+
update the dataset. On partial updates, existing data will be marked as
|
| 18 |
+
stale. There is also a show flag for each record; only items for which this
|
| 19 |
+
are true are included in the name index and __len__ calls.
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
module = '' # the current module dotted module name
|
| 24 |
+
data = None # a dictionary, {name:(stats, fresh)}:
|
| 25 |
+
# stats: None or (pass5, fail, err, all)
|
| 26 |
+
# fresh: None or False or True
|
| 27 |
+
names = None # a sorted list of names for which show is True
|
| 28 |
+
run = True # the current state of the run flag
|
| 29 |
+
totals = () # a single 4-tuple per summarize()
|
| 30 |
+
__lines = None # for communication between _set_totals and _set_data
|
| 31 |
+
__raw = '' # for communication between _call and _set_data
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def __init__(self, stopwords=()):
|
| 35 |
+
"""Takes a sequence.
|
| 36 |
+
"""
|
| 37 |
+
self.stopwords = stopwords
|
| 38 |
+
self.data = {}
|
| 39 |
+
self.totals = ()
|
| 40 |
+
self.names = []
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# Container emulation
|
| 44 |
+
# ===================
|
| 45 |
+
|
| 46 |
+
def __getitem__(self, i):
|
| 47 |
+
"""Takes an int index into self.names
|
| 48 |
+
"""
|
| 49 |
+
name = self.names[i]
|
| 50 |
+
return [name] + self.data[name]
|
| 51 |
+
|
| 52 |
+
def __len__(self):
|
| 53 |
+
"""Only count items for which show is True.
|
| 54 |
+
"""
|
| 55 |
+
return len(self.names)
|
| 56 |
+
|
| 57 |
+
def __iter__(self):
|
| 58 |
+
return self.names.__iter__()
|
| 59 |
+
iterkeys = __iter__
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# Main callable
|
| 63 |
+
# =============
|
| 64 |
+
|
| 65 |
+
def refresh(self, module, find_only=True):
|
| 66 |
+
"""Update our information.
|
| 67 |
+
"""
|
| 68 |
+
self.module = module
|
| 69 |
+
self.find_only = find_only
|
| 70 |
+
|
| 71 |
+
self._call()
|
| 72 |
+
|
| 73 |
+
self._set_stale()
|
| 74 |
+
self._set_totals()
|
| 75 |
+
self._set_data()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def update(self, name, pass5, fail, err, all):
|
| 79 |
+
"""Given data on one testcase, update its info.
|
| 80 |
+
|
| 81 |
+
This is called from DetailScreen.
|
| 82 |
+
|
| 83 |
+
"""
|
| 84 |
+
if name not in self.data:
|
| 85 |
+
raise StandardError("Running detail for module not in " +
|
| 86 |
+
"summary: %s." % name)
|
| 87 |
+
self._set_stale()
|
| 88 |
+
self.data[name] = [(pass5, fail, err, all), True]
|
| 89 |
+
self.totals = [pass5, fail, err, all]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# Helpers
|
| 93 |
+
# =======
|
| 94 |
+
|
| 95 |
+
def _call(self):
|
| 96 |
+
"""Invoke a child process and return its output.
|
| 97 |
+
|
| 98 |
+
We hand on our environment and any sys.path manipulations to the child,
|
| 99 |
+
and we capture stderr as well as stdout so we can handle errors.
|
| 100 |
+
|
| 101 |
+
"""
|
| 102 |
+
args = [ sys.executable
|
| 103 |
+
, '-u' # unbuffered, so we can interact with it
|
| 104 |
+
, sys.argv[0]
|
| 105 |
+
, '--stopwords=%s' % ','.join(self.stopwords)
|
| 106 |
+
, '--scripted'
|
| 107 |
+
, self.module
|
| 108 |
+
]
|
| 109 |
+
if self.find_only:
|
| 110 |
+
args.insert(4, '--find-only')
|
| 111 |
+
|
| 112 |
+
environ = os.environ.copy()
|
| 113 |
+
environ['PYTHONPATH'] = ':'.join(sys.path)
|
| 114 |
+
|
| 115 |
+
proc = Process(args=args, env=environ)
|
| 116 |
+
|
| 117 |
+
raw = proc.communicate()
|
| 118 |
+
if BANNER not in raw:
|
| 119 |
+
raise RefreshError(raw)
|
| 120 |
+
self.__raw = raw
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _set_stale(self):
|
| 124 |
+
"""Mark currently fresh data as stale.
|
| 125 |
+
"""
|
| 126 |
+
for name, datum in self.data.iteritems():
|
| 127 |
+
if datum[1] is True:
|
| 128 |
+
datum[1] = False
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _set_totals(self):
|
| 132 |
+
"""Given self.__raw, set totals and __lines on self.
|
| 133 |
+
"""
|
| 134 |
+
lines = self.__raw.splitlines()
|
| 135 |
+
self.totals = tuple(lines[-1].split()[1:])
|
| 136 |
+
del lines[-1]
|
| 137 |
+
self.__lines = lines
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _set_data(self):
|
| 141 |
+
"""Extract and store data from __lines.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
data = {}
|
| 145 |
+
reading_report = False # ignore any output that precedes our report
|
| 146 |
+
|
| 147 |
+
for line in self.__lines:
|
| 148 |
+
|
| 149 |
+
# Decide if we want this line, and if so, split it on spaces.
|
| 150 |
+
# ===========================================================
|
| 151 |
+
|
| 152 |
+
line = line.strip('\n')
|
| 153 |
+
if line == BANNER:
|
| 154 |
+
reading_report = True
|
| 155 |
+
continue
|
| 156 |
+
if (not reading_report) or (not line) or line in (HEADERS, BORDER):
|
| 157 |
+
continue
|
| 158 |
+
tokens = line.split()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# Convert the row to our record format.
|
| 162 |
+
# =====================================
|
| 163 |
+
# The raw report lists TestCases by full dotted name, but we want to
|
| 164 |
+
# only show short names, and indent under a module tree. So we add
|
| 165 |
+
# all parent modules to data, and set their value to (None, None)
|
| 166 |
+
|
| 167 |
+
name = tokens[0]
|
| 168 |
+
stats = tuple(tokens[1:])
|
| 169 |
+
|
| 170 |
+
module_dotted, testcase = name.rsplit('.',1)
|
| 171 |
+
|
| 172 |
+
parts = module_dotted.split('.')
|
| 173 |
+
for i in range(len(parts),self.module.count('.'),-1):
|
| 174 |
+
ancestor = '.'.join(parts[:i])
|
| 175 |
+
data[ancestor] = [None, None]
|
| 176 |
+
|
| 177 |
+
fresh = None
|
| 178 |
+
if '-' not in stats:
|
| 179 |
+
fresh = True
|
| 180 |
+
|
| 181 |
+
data[name] = [stats, fresh]
|
| 182 |
+
|
| 183 |
+
self.data.update(data)
|
| 184 |
+
self.names = sorted(self.data.keys())
|
| 185 |
+
del self.__lines
|
| 186 |
+
|
code/train/Python/0057882_Databases.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#import os
|
| 2 |
+
#os.environ['DYLD_LIBRARY_PATH'] = '/Library/PostgreSQL/9.5/lib'
|
| 3 |
+
import psycopg2
|
| 4 |
+
import time
|
| 5 |
+
import itertools
|
| 6 |
+
|
| 7 |
+
# Dictionary of database connections. Key is the database name (only within python relevant). Value is List of: [host, user, password, database, port]
|
| 8 |
+
databaseSetups = {
|
| 9 |
+
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Database:
|
| 14 |
+
|
| 15 |
+
def __init__(self, setup):
|
| 16 |
+
'''
|
| 17 |
+
@param setup: string. Database Setup. Must match a key from the databaseSetups dictionary (see above)
|
| 18 |
+
Creates an connection to database
|
| 19 |
+
'''
|
| 20 |
+
self.setup = setup
|
| 21 |
+
self.db = self._getConnection()
|
| 22 |
+
|
| 23 |
+
def _getConnection(self):
|
| 24 |
+
'''
|
| 25 |
+
Returns database connection. Function checks if database connection is still alive and if this is not the case it automatically reconnects to database
|
| 26 |
+
@return: MySQLdb connection object
|
| 27 |
+
'''
|
| 28 |
+
try:
|
| 29 |
+
# check if database connection is still alive
|
| 30 |
+
db = self.db
|
| 31 |
+
cursor = db.cursor()
|
| 32 |
+
cursor.execute("SELECT VERSION()")
|
| 33 |
+
results = cursor.fetchone()
|
| 34 |
+
|
| 35 |
+
# if result is not empty connection is alive
|
| 36 |
+
if results:
|
| 37 |
+
return db
|
| 38 |
+
# create new connection
|
| 39 |
+
else:
|
| 40 |
+
connectionDetails = databaseSetups[self.setup]
|
| 41 |
+
self.db = psycopg2.connect(host = connectionDetails[0], user = connectionDetails[1], password = connectionDetails[2], database = connectionDetails[3], port = connectionDetails[4])
|
| 42 |
+
return self.db
|
| 43 |
+
|
| 44 |
+
except:
|
| 45 |
+
# if an exception occurs during checking if database connection is still alive create a new connection; if it's not possible to connect to Datbase Server wait 120 sec and try to connect again
|
| 46 |
+
reConnect = True
|
| 47 |
+
while reConnect is True:
|
| 48 |
+
try:
|
| 49 |
+
connectionDetails = databaseSetups[self.setup]
|
| 50 |
+
self.db = psycopg2.connect(host = connectionDetails[0], user = connectionDetails[1], password = connectionDetails[2], database = connectionDetails[3], port = connectionDetails[4])
|
| 51 |
+
reConnect = False
|
| 52 |
+
except:
|
| 53 |
+
time.sleep(120)
|
| 54 |
+
return self.db
|
| 55 |
+
|
| 56 |
+
def closeConnection(self):
|
| 57 |
+
'''
|
| 58 |
+
@summary: Closes connection to database
|
| 59 |
+
@author: JScelle
|
| 60 |
+
@version: 10.06.2013
|
| 61 |
+
'''
|
| 62 |
+
try:
|
| 63 |
+
self.db.close()
|
| 64 |
+
except:
|
| 65 |
+
# if closing of connection fails ignore it
|
| 66 |
+
pass
|
| 67 |
+
|
| 68 |
+
def getValuesFromTable(self, sqlQueryStatement):
|
| 69 |
+
'''
|
| 70 |
+
gets records from table
|
| 71 |
+
@param sqlQueryStatement: String, sql query statement e.g. "SELECT * FROM employee WHERE country = 'DE'"
|
| 72 |
+
@return: tuple of tuples
|
| 73 |
+
'''
|
| 74 |
+
# get database connection from runTimeController
|
| 75 |
+
try:
|
| 76 |
+
db = self.db
|
| 77 |
+
except Exception as exc:
|
| 78 |
+
print("EXCEPTION: Module: Database, Function: getValuesFromTable, Error: Could not get database connection. ", str(exc.args))
|
| 79 |
+
return ((),)
|
| 80 |
+
|
| 81 |
+
#excecute sql statement
|
| 82 |
+
try:
|
| 83 |
+
# prepare a cursor object using cursor() method
|
| 84 |
+
cursor = db.cursor()
|
| 85 |
+
# Execute the SQL command
|
| 86 |
+
cursor.execute(sqlQueryStatement)
|
| 87 |
+
# Fetch all the rows in a list of lists.
|
| 88 |
+
results = cursor.fetchall()
|
| 89 |
+
db.commit()
|
| 90 |
+
return results
|
| 91 |
+
except Exception as exc:
|
| 92 |
+
# Rollback in case there is any error
|
| 93 |
+
db.rollback()
|
| 94 |
+
print("EXCEPTION: Module: Database, Function: getValuesFromTable, Error: Could not execute query. ", str(exc.args))
|
| 95 |
+
return ((),)
|
| 96 |
+
|
| 97 |
+
def runQuery(self, sqlStatement):
|
| 98 |
+
'''
|
| 99 |
+
Executes any sql statement. For getting data from the database, please use the getValuesFromTable-method
|
| 100 |
+
@param sqlStatement: string. any sql statement e.g. Update, Delete
|
| 101 |
+
@return: Returns True if everything went good.
|
| 102 |
+
'''
|
| 103 |
+
# get database connection from runTimeController
|
| 104 |
+
try:
|
| 105 |
+
db = self.db
|
| 106 |
+
except Exception as exc:
|
| 107 |
+
print("EXCEPTION: Module: Database, Function: runQuery, Error: Could not get database connection. ", str(exc.args))
|
| 108 |
+
return False
|
| 109 |
+
|
| 110 |
+
#excecute sql statement
|
| 111 |
+
try:
|
| 112 |
+
# prepare a cursor object using cursor() method
|
| 113 |
+
cursor = db.cursor()
|
| 114 |
+
# Execute the SQL command
|
| 115 |
+
cursor.execute(sqlStatement)
|
| 116 |
+
# Commit your changes in the Settings.database
|
| 117 |
+
db.commit()
|
| 118 |
+
return True
|
| 119 |
+
except Exception as exc:
|
| 120 |
+
# Rollback in case there is any error
|
| 121 |
+
db.rollback()
|
| 122 |
+
print("EXCEPTION: Module: Database, Function: runQuery, Error: Could not execute query. ", str(exc.args))
|
| 123 |
+
return False
|
| 124 |
+
|
| 125 |
+
def runMultipleQueries(self, sqlStatements):
|
| 126 |
+
"""
|
| 127 |
+
Executes multiple SQL-statements as one transaction
|
| 128 |
+
@param sqlStatements: List of strings. Each String is one SQL-statement
|
| 129 |
+
@return: Returns True if everything went good.
|
| 130 |
+
"""
|
| 131 |
+
# get database connection from runTimeController
|
| 132 |
+
try:
|
| 133 |
+
db = self.db
|
| 134 |
+
except Exception as exc:
|
| 135 |
+
print("EXCEPTION: Module: Database, Function: runMultipleQueries, Error: Could not get database connection. ", str(exc.args))
|
| 136 |
+
return False
|
| 137 |
+
|
| 138 |
+
# excecute sql statement
|
| 139 |
+
try:
|
| 140 |
+
# prepare a cursor object using cursor() method
|
| 141 |
+
cursor = db.cursor()
|
| 142 |
+
for sqlStatement in sqlStatements:
|
| 143 |
+
# Execute the SQL command
|
| 144 |
+
cursor.execute(sqlStatement)
|
| 145 |
+
# Commit your changes in the Settings.database
|
| 146 |
+
db.commit()
|
| 147 |
+
return True
|
| 148 |
+
except Exception as exc:
|
| 149 |
+
# Rollback in case there is any error
|
| 150 |
+
db.rollback()
|
| 151 |
+
print("EXCEPTION: Module: Database, Function: runMultipleQueries, Error: One of the queries could not be executed. ", str(exc.args))
|
| 152 |
+
return False
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def insertValuesIntoTable(self, tableName, fieldList, valueList):
|
| 156 |
+
"""
|
| 157 |
+
calls _executeInsertValuesIntoTable which inserts values into table
|
| 158 |
+
@param tableName: String, name of table
|
| 159 |
+
@param fieldList: List of string, list of field names e.g ,["firstName", "lastName"]
|
| 160 |
+
@param valueList: List of list, e.g [["Sebastian", "Stuetz"],["Ingo", "Tschach"]]
|
| 161 |
+
@return: Returns True if everything went good.
|
| 162 |
+
"""
|
| 163 |
+
try:
|
| 164 |
+
#define INSERT INTO part of sql query
|
| 165 |
+
insertIntoSqlPart = "INSERT INTO " + tableName + " (" + ",".join(fieldList) + ") VALUES"
|
| 166 |
+
#define ON DUPLICATE KEY part of sql query
|
| 167 |
+
onDuplicateKeyPart = " ON DUPLICATE KEY UPDATE "
|
| 168 |
+
for field in fieldList:
|
| 169 |
+
#replace old values with new values
|
| 170 |
+
onDuplicateKeyPart += str(field) + " = VALUES(" + str(field) + "), "
|
| 171 |
+
onDuplicateKeyPart = onDuplicateKeyPart[0:(len(onDuplicateKeyPart) - 2)]
|
| 172 |
+
|
| 173 |
+
return self._executeInsertValuesIntoTable(fieldList, valueList, insertIntoSqlPart, onDuplicateKeyPart)
|
| 174 |
+
|
| 175 |
+
except Exception as exc:
|
| 176 |
+
print("EXCEPTION: Module: Database, Function: insertValuesIntoTable, Error: Error when building the query frame. ", str(exc.args))
|
| 177 |
+
return False
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _executeInsertValuesIntoTable(self, fieldList, valueList, insertIntoSqlPart, onDuplicateKeyPart):
|
| 181 |
+
'''
|
| 182 |
+
inserts values into table
|
| 183 |
+
@param fieldList: List, list of field names e.g ,["firstName", "lastName"]
|
| 184 |
+
@param valueList: List of list, e.g [["Sebastian", "Stuetz"],["Ingo", "Tschach"]]
|
| 185 |
+
@return: Returns True if everything went good.
|
| 186 |
+
'''
|
| 187 |
+
# get database connection from runTimeController
|
| 188 |
+
try:
|
| 189 |
+
db = self.db
|
| 190 |
+
except Exception as exc:
|
| 191 |
+
print("EXCEPTION: Module: Database, Function: _executeInsertValuesIntoTable, Error: Could not get database connection. ", str(exc.args))
|
| 192 |
+
return False
|
| 193 |
+
|
| 194 |
+
try:
|
| 195 |
+
# prepare a cursor object using cursor() method
|
| 196 |
+
cursor = db.cursor()
|
| 197 |
+
|
| 198 |
+
#Insert data
|
| 199 |
+
#divide valueList into chunks to avoid that too big packets are send to sql server
|
| 200 |
+
maxPackets = 5000
|
| 201 |
+
for i in range(0, len(valueList), maxPackets):
|
| 202 |
+
chunk = valueList[i:i + maxPackets]
|
| 203 |
+
#define data part of sql query (string consisting of "%s" for each field for each row)
|
| 204 |
+
dataSqlPart = ",".join(["(" + ",".join(["%s"] * len(fieldList)) + ")"] * len(chunk))
|
| 205 |
+
#put sql parts together
|
| 206 |
+
sql = insertIntoSqlPart + dataSqlPart + onDuplicateKeyPart
|
| 207 |
+
#flatten data list
|
| 208 |
+
valueListChunk = tuple(itertools.chain(*chunk))
|
| 209 |
+
#Insert values into DB
|
| 210 |
+
cursor.execute(sql, valueListChunk)
|
| 211 |
+
|
| 212 |
+
# Commit your changes in the Settings.database
|
| 213 |
+
db.commit()
|
| 214 |
+
|
| 215 |
+
return True
|
| 216 |
+
except Exception as exc:
|
| 217 |
+
# Rollback in case there is any error
|
| 218 |
+
db.rollback()
|
| 219 |
+
print("EXCEPTION: Module: Database, Function: _executeInsertValuesIntoTable, Error: Could not insert values. ", str(exc.args))
|
| 220 |
+
return False
|
| 221 |
+
|
code/train/Python/0057969_loading.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import traceback
|
| 3 |
+
|
| 4 |
+
from django.conf import settings
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class AppNotFoundError(Exception):
|
| 8 |
+
pass
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ClassNotFoundError(Exception):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_class(module_label, classname):
|
| 16 |
+
return get_classes(module_label, [classname, ])[0]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_classes(module_label, classnames):
|
| 20 |
+
""" Imports a set of classes from a given module.
|
| 21 |
+
|
| 22 |
+
Usage::
|
| 23 |
+
|
| 24 |
+
get_classes('forum.models', ['Forum', 'ForumReadTrack', ])
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
app_label = module_label.split('.')[0]
|
| 28 |
+
|
| 29 |
+
app_module_path = _get_app_module_path(module_label)
|
| 30 |
+
if not app_module_path:
|
| 31 |
+
raise AppNotFoundError('No app found matching \'{}\''.format(module_label))
|
| 32 |
+
|
| 33 |
+
# Determines the full module path by appending the module label
|
| 34 |
+
# to the base package path of the considered application.
|
| 35 |
+
module_path = app_module_path
|
| 36 |
+
if '.' in app_module_path:
|
| 37 |
+
base_package = app_module_path.rsplit('.' + app_label, 1)[0]
|
| 38 |
+
module_path = '{}.{}'.format(base_package, module_label)
|
| 39 |
+
|
| 40 |
+
# Try to import this module from the related app that is specified
|
| 41 |
+
# in the Django settings.
|
| 42 |
+
local_imported_module = _import_module(module_path, classnames)
|
| 43 |
+
|
| 44 |
+
# If the module we tried to import is not located inside the machina
|
| 45 |
+
# vanilla apps, try to import it from the corresponding machina app.
|
| 46 |
+
machina_imported_module = None
|
| 47 |
+
if not app_module_path.startswith('machina.apps'):
|
| 48 |
+
machina_imported_module = _import_module(
|
| 49 |
+
'{}.{}'.format('machina.apps', module_label), classnames,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
if local_imported_module is None and machina_imported_module is None:
|
| 53 |
+
raise AppNotFoundError('Error importing \'{}\''.format(module_path))
|
| 54 |
+
|
| 55 |
+
# Any local module is prioritized over the corresponding machina module
|
| 56 |
+
imported_modules = [
|
| 57 |
+
m for m in (local_imported_module, machina_imported_module) if m is not None
|
| 58 |
+
]
|
| 59 |
+
return _pick_up_classes(imported_modules, classnames)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _import_module(module_path, classnames):
|
| 63 |
+
""" Tries to import the given Python module path. """
|
| 64 |
+
try:
|
| 65 |
+
imported_module = __import__(module_path, fromlist=classnames)
|
| 66 |
+
return imported_module
|
| 67 |
+
except ImportError:
|
| 68 |
+
# In case of an ImportError, the module being loaded generally does not exist. But an
|
| 69 |
+
# ImportError can occur if the module being loaded exists and another import located inside
|
| 70 |
+
# it failed.
|
| 71 |
+
#
|
| 72 |
+
# In order to provide a meaningfull traceback, the execution information can be inspected in
|
| 73 |
+
# order to determine which case to consider. If the execution information provides more than
|
| 74 |
+
# a certain amount of frames, this means that an ImportError occured while loading the
|
| 75 |
+
# initial Python module.
|
| 76 |
+
__, __, exc_traceback = sys.exc_info()
|
| 77 |
+
frames = traceback.extract_tb(exc_traceback)
|
| 78 |
+
if len(frames) > 1:
|
| 79 |
+
raise
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _pick_up_classes(modules, classnames):
|
| 83 |
+
""" Given a list of class names to retrieve, try to fetch them from the specified list of
|
| 84 |
+
modules and returns the list of the fetched classes.
|
| 85 |
+
"""
|
| 86 |
+
klasses = []
|
| 87 |
+
for classname in classnames:
|
| 88 |
+
klass = None
|
| 89 |
+
for module in modules:
|
| 90 |
+
if hasattr(module, classname):
|
| 91 |
+
klass = getattr(module, classname)
|
| 92 |
+
break
|
| 93 |
+
if not klass:
|
| 94 |
+
raise ClassNotFoundError('Error fetching \'{}\' in {}'.format(
|
| 95 |
+
classname, str([module.__name__ for module in modules]))
|
| 96 |
+
)
|
| 97 |
+
klasses.append(klass)
|
| 98 |
+
return klasses
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _get_app_module_path(module_label):
|
| 102 |
+
""" Given a module label, loop over the apps specified in the INSTALLED_APPS to find the
|
| 103 |
+
corresponding application module path.
|
| 104 |
+
"""
|
| 105 |
+
app_name = module_label.rsplit('.', 1)[0]
|
| 106 |
+
for app in settings.INSTALLED_APPS:
|
| 107 |
+
if app.endswith('.' + app_name) or app == app_name:
|
| 108 |
+
return app
|
| 109 |
+
return None
|
code/train/Python/0058914_lists.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python2.5
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2008 the Melange authors.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
"""List generation logic.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
__authors__ = [
|
| 21 |
+
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Lists(object):
|
| 26 |
+
"""List array suitable for enumerating over with just 'for in'.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
DEF_PASSTHROUGH_FIELDS = [
|
| 30 |
+
'pagination',
|
| 31 |
+
'pagination_form',
|
| 32 |
+
'description',
|
| 33 |
+
'export',
|
| 34 |
+
'heading',
|
| 35 |
+
'row',
|
| 36 |
+
'limit',
|
| 37 |
+
'newest',
|
| 38 |
+
'prev',
|
| 39 |
+
'next',
|
| 40 |
+
'first',
|
| 41 |
+
'last',
|
| 42 |
+
'idx',
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
def __init__(self, contents):
|
| 46 |
+
"""Constructs a new Lists object with the specified contents.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
# All the contents of all the lists
|
| 50 |
+
self._contents = contents
|
| 51 |
+
self._content = {}
|
| 52 |
+
|
| 53 |
+
# For iterating over all the lists
|
| 54 |
+
self._lists = range(len(contents))
|
| 55 |
+
|
| 56 |
+
def __getattr__(self, attr):
|
| 57 |
+
"""Delegate field lookup to the current list if appropriate.
|
| 58 |
+
|
| 59 |
+
If, and only if, a lookup is done on one of the fields defined in
|
| 60 |
+
DEF_PASSTHROUGH_FIELDS, and the current list defines this field,
|
| 61 |
+
the value from the current list is returned.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
if attr not in self.DEF_PASSTHROUGH_FIELDS:
|
| 65 |
+
raise AttributeError()
|
| 66 |
+
|
| 67 |
+
if attr not in self._content:
|
| 68 |
+
raise AttributeError()
|
| 69 |
+
|
| 70 |
+
return self.get(attr)
|
| 71 |
+
|
| 72 |
+
def get(self, item):
|
| 73 |
+
"""Returns the item for the current list data.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
return self._content[item]
|
| 77 |
+
|
| 78 |
+
def nextList(self):
|
| 79 |
+
"""Shifts out the current list content.
|
| 80 |
+
|
| 81 |
+
The main content of the next list is returned for further processing.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
# Advance the list data once
|
| 85 |
+
self._content = self._contents[0]
|
| 86 |
+
self._contents = self._contents[1:]
|
| 87 |
+
|
| 88 |
+
return self
|
| 89 |
+
|
| 90 |
+
def empty(self):
|
| 91 |
+
"""Returns true iff there are no lists
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
return not self._lists
|
| 95 |
+
|
| 96 |
+
def lists(self):
|
| 97 |
+
"""Returns a list of numbers the size of the amount of lists.
|
| 98 |
+
|
| 99 |
+
This method can be used to iterate over all lists with shift,
|
| 100 |
+
without using a while loop.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
return self._lists
|
code/train/Python/0059093_path.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/env python
|
| 2 |
+
from math import sqrt
|
| 3 |
+
import pygame
|
| 4 |
+
class Path:
|
| 5 |
+
def __init__(self,points=None,filename=None):
|
| 6 |
+
self.points=[]
|
| 7 |
+
if points is not None:
|
| 8 |
+
for px,py in points:
|
| 9 |
+
self.points.append((float(px),float(py)))
|
| 10 |
+
self.calcLength()
|
| 11 |
+
if filename is not None:
|
| 12 |
+
self.load(filename)
|
| 13 |
+
def calcLength(self):
|
| 14 |
+
lastpoint=None
|
| 15 |
+
dist=0.0
|
| 16 |
+
ptotal=[0.0]
|
| 17 |
+
for point in self.points:
|
| 18 |
+
if lastpoint is not None:
|
| 19 |
+
dx=point[0]-lastpoint[0]
|
| 20 |
+
dy=point[1]-lastpoint[1]
|
| 21 |
+
dist+=sqrt(dx*dx + dy*dy)
|
| 22 |
+
ptotal.append(dist)
|
| 23 |
+
lastpoint=point
|
| 24 |
+
|
| 25 |
+
self.length=dist
|
| 26 |
+
self.ptotal=ptotal
|
| 27 |
+
def getLength(self):
|
| 28 |
+
return self.length
|
| 29 |
+
|
| 30 |
+
def setPoints(self,pointlist):
|
| 31 |
+
self.points=[]
|
| 32 |
+
for a,b in pointlist:
|
| 33 |
+
self.points.append((float(a),float(b)))
|
| 34 |
+
self.calcLength()
|
| 35 |
+
def load(self,filename):
|
| 36 |
+
self.points=[]
|
| 37 |
+
for line in open(filename,'r'):
|
| 38 |
+
a,b=line.strip().split(' ')
|
| 39 |
+
pf=(float(a),float(b))
|
| 40 |
+
self.points.append(pf)
|
| 41 |
+
self.calcLength()
|
| 42 |
+
def render(self,size,palette=None,drawlines=True,drawpoints=True,pointsize=2):
|
| 43 |
+
surf=pygame.Surface(size,0,8)
|
| 44 |
+
if palette is not None:
|
| 45 |
+
surf.set_palette(palette)
|
| 46 |
+
bg=12
|
| 47 |
+
linecolor=16
|
| 48 |
+
pointcolor=68
|
| 49 |
+
else:
|
| 50 |
+
surf.set_palette([(255,255,255),(0,0,0),(127,127,127)])
|
| 51 |
+
bg=0
|
| 52 |
+
linecolor=1
|
| 53 |
+
pointcolor=2
|
| 54 |
+
surf.fill(bg)
|
| 55 |
+
if drawlines:
|
| 56 |
+
lastpoint=None
|
| 57 |
+
for point in self.points:
|
| 58 |
+
px=point[0]*size[0]
|
| 59 |
+
py=point[1]*size[1]
|
| 60 |
+
if lastpoint is not None:
|
| 61 |
+
pygame.draw.line(surf,linecolor,lastpoint,(px,py))
|
| 62 |
+
lastpoint=(px,py)
|
| 63 |
+
if drawpoints:
|
| 64 |
+
for point in self.points:
|
| 65 |
+
px=point[0]*size[0]
|
| 66 |
+
py=point[1]*size[1]
|
| 67 |
+
surf.fill(pointcolor,(px-pointsize,py-pointsize,pointsize*2,pointsize*2))
|
| 68 |
+
return surf
|
| 69 |
+
def getPointByPercent(self,amt):
|
| 70 |
+
return self.getPointByDist((amt/100.0)*(self.getLength()))
|
| 71 |
+
def getPointByDist(self,dist):
|
| 72 |
+
fi=None
|
| 73 |
+
fidist=None
|
| 74 |
+
for i,pdist in enumerate(self.ptotal):
|
| 75 |
+
if pdist<=dist and self.ptotal[i+1]>=dist:
|
| 76 |
+
fi=i
|
| 77 |
+
fidist=pdist
|
| 78 |
+
break
|
| 79 |
+
if fi is None: return None
|
| 80 |
+
p1=self.points[fi]
|
| 81 |
+
p2=self.points[fi+1]
|
| 82 |
+
pdx=p1[0]-p2[0]
|
| 83 |
+
pdy=p1[1]-p2[1]
|
| 84 |
+
ldist=sqrt(pdx*pdx + pdy*pdy)
|
| 85 |
+
adist=dist-fidist
|
| 86 |
+
amt=(adist/float(ldist))
|
| 87 |
+
x=p1[0]*(1-amt) + p2[0]*amt
|
| 88 |
+
y=p1[1]*(1-amt) + p2[1]*amt
|
| 89 |
+
return (x,y)
|
code/train/Python/0059516_ranzhi_advanced_tests.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
from box_driver import BoxDriver
|
| 5 |
+
from ranzhi_common import RanzhiCommon
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class RanzhiAdvancedTests(unittest.TestCase):
|
| 9 |
+
"""
|
| 10 |
+
测试主页
|
| 11 |
+
1. 测试登录
|
| 12 |
+
2. 测试语言
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
# 成员变量
|
| 16 |
+
base_driver = None
|
| 17 |
+
base_url = None
|
| 18 |
+
common = None
|
| 19 |
+
|
| 20 |
+
def setUp(self):
|
| 21 |
+
"""
|
| 22 |
+
前置条件
|
| 23 |
+
:return:
|
| 24 |
+
"""
|
| 25 |
+
profile = "C:/python35/chromedriver.exe"
|
| 26 |
+
|
| 27 |
+
self.base_driver = BoxDriver(",", profile, "chrome")
|
| 28 |
+
self.base_driver.clear_cookies()
|
| 29 |
+
self.base_url = "http://localhost/"
|
| 30 |
+
self.common = RanzhiCommon(self.base_driver, self.base_url)
|
| 31 |
+
|
| 32 |
+
def tearDown(self):
|
| 33 |
+
"""
|
| 34 |
+
测试清理
|
| 35 |
+
:return:
|
| 36 |
+
"""
|
| 37 |
+
self.base_driver.quit()
|
| 38 |
+
|
| 39 |
+
def test_add_member_by_csv(self):
|
| 40 |
+
"""
|
| 41 |
+
测试 添加多个用户
|
| 42 |
+
从CSV文件读取数据,并添加到系统各种
|
| 43 |
+
:return:
|
| 44 |
+
"""
|
| 45 |
+
common = self.common
|
| 46 |
+
driver = self.base_driver
|
| 47 |
+
|
| 48 |
+
csv_file = open("member_list_with_header.csv", "r",
|
| 49 |
+
encoding="utf8")
|
| 50 |
+
csv_data = csv.reader(csv_file)
|
| 51 |
+
|
| 52 |
+
is_header = True
|
| 53 |
+
for row in csv_data:
|
| 54 |
+
if is_header:
|
| 55 |
+
is_header = False
|
| 56 |
+
continue
|
| 57 |
+
|
| 58 |
+
lang = "zh_CN"
|
| 59 |
+
common.open_page("")
|
| 60 |
+
common.change_language(lang)
|
| 61 |
+
common.log_in("admin", "123456")
|
| 62 |
+
common.select_admin_app()
|
| 63 |
+
expected_url = self.base_url + "sys/admin/"
|
| 64 |
+
self.assertEqual(expected_url, driver.get_url(),
|
| 65 |
+
"后台管理按钮点击后页面跳转失败!")
|
| 66 |
+
|
| 67 |
+
common.click_add_member_button()
|
| 68 |
+
|
| 69 |
+
expected_url = self.base_url + "sys/user-create.html"
|
| 70 |
+
self.assertEqual(expected_url, driver.get_url(),
|
| 71 |
+
"添加成员按钮点击后页面跳转失败!")
|
| 72 |
+
|
| 73 |
+
# dict 类型的数据
|
| 74 |
+
member_data = {
|
| 75 |
+
"account": row[0],
|
| 76 |
+
"real_name": row[1],
|
| 77 |
+
"gender": row[2],
|
| 78 |
+
"dept": row[3],
|
| 79 |
+
"role": row[4],
|
| 80 |
+
"password": row[5],
|
| 81 |
+
"email": row[6]
|
| 82 |
+
}
|
| 83 |
+
common.add_member_data(member_data)
|
| 84 |
+
expected_url = self.base_url + "sys/user-admin.html"
|
| 85 |
+
self.assertEqual(expected_url, driver.get_url(),
|
| 86 |
+
"添加成员保存失败!")
|
| 87 |
+
|
| 88 |
+
common.log_out(lang)
|
| 89 |
+
common.open_page("")
|
| 90 |
+
common.log_in(member_data["account"], member_data["password"])
|
| 91 |
+
expected_url = self.base_url + "sys/index.html"
|
| 92 |
+
self.assertEqual(expected_url, driver.get_url(),
|
| 93 |
+
"新用户登录失败!")
|
| 94 |
+
common.log_out(lang)
|
| 95 |
+
csv_file.close()
|
code/train/Python/0060131_plot_hyperparameter.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Simple Parallel Model Selection
|
| 3 |
+
===============================
|
| 4 |
+
|
| 5 |
+
In this example, we'll demonstrate how to quickly write a hyperparameter
|
| 6 |
+
tuning script that evaluates a set of hyperparameters in parallel.
|
| 7 |
+
|
| 8 |
+
This script will demonstrate how to use two important parts of the Ray API:
|
| 9 |
+
using ``ray.remote`` to define remote functions and ``ray.wait`` to wait for
|
| 10 |
+
their results to be ready.
|
| 11 |
+
|
| 12 |
+
.. important:: For a production-grade implementation of distributed
|
| 13 |
+
hyperparameter tuning, use `Tune`_, a scalable hyperparameter
|
| 14 |
+
tuning library built using Ray's Actor API.
|
| 15 |
+
|
| 16 |
+
.. _`Tune`: https://ray.readthedocs.io/en/latest/tune.html
|
| 17 |
+
"""
|
| 18 |
+
import os
|
| 19 |
+
import numpy as np
|
| 20 |
+
from filelock import FileLock
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
import torch.optim as optim
|
| 26 |
+
from torchvision import datasets, transforms
|
| 27 |
+
|
| 28 |
+
import ray
|
| 29 |
+
|
| 30 |
+
ray.init()
|
| 31 |
+
|
| 32 |
+
# The number of sets of random hyperparameters to try.
|
| 33 |
+
num_evaluations = 10
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# A function for generating random hyperparameters.
|
| 37 |
+
def generate_hyperparameters():
|
| 38 |
+
return {
|
| 39 |
+
"learning_rate": 10**np.random.uniform(-5, 1),
|
| 40 |
+
"batch_size": np.random.randint(1, 100),
|
| 41 |
+
"momentum": np.random.uniform(0, 1)
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_data_loaders(batch_size):
|
| 46 |
+
mnist_transforms = transforms.Compose(
|
| 47 |
+
[transforms.ToTensor(),
|
| 48 |
+
transforms.Normalize((0.1307, ), (0.3081, ))])
|
| 49 |
+
|
| 50 |
+
# We add FileLock here because multiple workers will want to
|
| 51 |
+
# download data, and this may cause overwrites since
|
| 52 |
+
# DataLoader is not threadsafe.
|
| 53 |
+
with FileLock(os.path.expanduser("~/data.lock")):
|
| 54 |
+
train_loader = torch.utils.data.DataLoader(
|
| 55 |
+
datasets.MNIST(
|
| 56 |
+
"~/data",
|
| 57 |
+
train=True,
|
| 58 |
+
download=True,
|
| 59 |
+
transform=mnist_transforms),
|
| 60 |
+
batch_size=batch_size,
|
| 61 |
+
shuffle=True)
|
| 62 |
+
test_loader = torch.utils.data.DataLoader(
|
| 63 |
+
datasets.MNIST("~/data", train=False, transform=mnist_transforms),
|
| 64 |
+
batch_size=batch_size,
|
| 65 |
+
shuffle=True)
|
| 66 |
+
return train_loader, test_loader
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class ConvNet(nn.Module):
|
| 70 |
+
"""Simple two layer Convolutional Neural Network."""
|
| 71 |
+
|
| 72 |
+
def __init__(self):
|
| 73 |
+
super(ConvNet, self).__init__()
|
| 74 |
+
self.conv1 = nn.Conv2d(1, 3, kernel_size=3)
|
| 75 |
+
self.fc = nn.Linear(192, 10)
|
| 76 |
+
|
| 77 |
+
def forward(self, x):
|
| 78 |
+
x = F.relu(F.max_pool2d(self.conv1(x), 3))
|
| 79 |
+
x = x.view(-1, 192)
|
| 80 |
+
x = self.fc(x)
|
| 81 |
+
return F.log_softmax(x, dim=1)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def train(model, optimizer, train_loader, device=torch.device("cpu")):
|
| 85 |
+
"""Optimize the model with one pass over the data.
|
| 86 |
+
|
| 87 |
+
Cuts off at 1024 samples to simplify training.
|
| 88 |
+
"""
|
| 89 |
+
model.train()
|
| 90 |
+
for batch_idx, (data, target) in enumerate(train_loader):
|
| 91 |
+
if batch_idx * len(data) > 1024:
|
| 92 |
+
return
|
| 93 |
+
data, target = data.to(device), target.to(device)
|
| 94 |
+
optimizer.zero_grad()
|
| 95 |
+
output = model(data)
|
| 96 |
+
loss = F.nll_loss(output, target)
|
| 97 |
+
loss.backward()
|
| 98 |
+
optimizer.step()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test(model, test_loader, device=torch.device("cpu")):
|
| 102 |
+
"""Checks the validation accuracy of the model.
|
| 103 |
+
|
| 104 |
+
Cuts off at 512 samples for simplicity.
|
| 105 |
+
"""
|
| 106 |
+
model.eval()
|
| 107 |
+
correct = 0
|
| 108 |
+
total = 0
|
| 109 |
+
with torch.no_grad():
|
| 110 |
+
for batch_idx, (data, target) in enumerate(test_loader):
|
| 111 |
+
if batch_idx * len(data) > 512:
|
| 112 |
+
break
|
| 113 |
+
data, target = data.to(device), target.to(device)
|
| 114 |
+
outputs = model(data)
|
| 115 |
+
_, predicted = torch.max(outputs.data, 1)
|
| 116 |
+
total += target.size(0)
|
| 117 |
+
correct += (predicted == target).sum().item()
|
| 118 |
+
|
| 119 |
+
return correct / total
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@ray.remote
|
| 123 |
+
def evaluate_hyperparameters(config):
|
| 124 |
+
model = ConvNet()
|
| 125 |
+
train_loader, test_loader = get_data_loaders(config["batch_size"])
|
| 126 |
+
optimizer = optim.SGD(
|
| 127 |
+
model.parameters(),
|
| 128 |
+
lr=config["learning_rate"],
|
| 129 |
+
momentum=config["momentum"])
|
| 130 |
+
train(model, optimizer, train_loader)
|
| 131 |
+
return test(model, test_loader)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# Keep track of the best hyperparameters and the best accuracy.
|
| 135 |
+
best_hyperparameters = None
|
| 136 |
+
best_accuracy = 0
|
| 137 |
+
# A list holding the object IDs for all of the experiments that we have
|
| 138 |
+
# launched but have not yet been processed.
|
| 139 |
+
remaining_ids = []
|
| 140 |
+
# A dictionary mapping an experiment's object ID to its hyperparameters.
|
| 141 |
+
# hyerparameters used for that experiment.
|
| 142 |
+
hyperparameters_mapping = {}
|
| 143 |
+
|
| 144 |
+
# Randomly generate sets of hyperparameters and launch a task to test each set.
|
| 145 |
+
for i in range(num_evaluations):
|
| 146 |
+
hyperparameters = generate_hyperparameters()
|
| 147 |
+
accuracy_id = evaluate_hyperparameters.remote(hyperparameters)
|
| 148 |
+
remaining_ids.append(accuracy_id)
|
| 149 |
+
hyperparameters_mapping[accuracy_id] = hyperparameters
|
| 150 |
+
|
| 151 |
+
# Fetch and print the results of the tasks in the order that they complete.
|
| 152 |
+
while remaining_ids:
|
| 153 |
+
# Use ray.wait to get the object ID of the first task that completes.
|
| 154 |
+
done_ids, remaining_ids = ray.wait(remaining_ids)
|
| 155 |
+
# There is only one return result by default.
|
| 156 |
+
result_id = done_ids[0]
|
| 157 |
+
|
| 158 |
+
hyperparameters = hyperparameters_mapping[result_id]
|
| 159 |
+
accuracy = ray.get(result_id)
|
| 160 |
+
print("""We achieve accuracy {:.3}% with
|
| 161 |
+
learning_rate: {:.2}
|
| 162 |
+
batch_size: {}
|
| 163 |
+
momentum: {:.2}
|
| 164 |
+
""".format(100 * accuracy, hyperparameters["learning_rate"],
|
| 165 |
+
hyperparameters["batch_size"], hyperparameters["momentum"]))
|
| 166 |
+
if accuracy > best_accuracy:
|
| 167 |
+
best_hyperparameters = hyperparameters
|
| 168 |
+
best_accuracy = accuracy
|
| 169 |
+
|
| 170 |
+
# Record the best performing set of hyperparameters.
|
| 171 |
+
print("""Best accuracy over {} trials was {:.3} with
|
| 172 |
+
learning_rate: {:.2}
|
| 173 |
+
batch_size: {}
|
| 174 |
+
momentum: {:.2}
|
| 175 |
+
""".format(num_evaluations, 100 * best_accuracy,
|
| 176 |
+
best_hyperparameters["learning_rate"],
|
| 177 |
+
best_hyperparameters["batch_size"],
|
| 178 |
+
best_hyperparameters["momentum"]))
|
code/train/Python/0060499_market_origin.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: UTF-8 -*-
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
import requests
|
| 8 |
+
|
| 9 |
+
from quant import config
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Market(object):
|
| 13 |
+
def __init__(self, base_currency, market_currency, pair_code, fee_rate):
|
| 14 |
+
self._name = None
|
| 15 |
+
self.base_currency = base_currency
|
| 16 |
+
self.market_currency = market_currency
|
| 17 |
+
self.pair_code = pair_code
|
| 18 |
+
self.fee_rate = fee_rate
|
| 19 |
+
|
| 20 |
+
self.depth_updated = 0
|
| 21 |
+
self.update_rate = 3
|
| 22 |
+
|
| 23 |
+
self.is_terminated = False
|
| 24 |
+
self.request_timeout = 5 # 5s
|
| 25 |
+
self.depth = {'asks': [{'price': 0, 'amount': 0}], 'bids': [
|
| 26 |
+
{'price': 0, 'amount': 0}]}
|
| 27 |
+
|
| 28 |
+
def request_get(self, url):
|
| 29 |
+
try:
|
| 30 |
+
resp = requests.get(url, timeout=self.request_timeout)
|
| 31 |
+
except requests.exceptions.RequestException as e:
|
| 32 |
+
logging.debug("get %s failed: " % url + str(e))
|
| 33 |
+
else:
|
| 34 |
+
if resp.status_code == requests.codes.ok:
|
| 35 |
+
return resp.json()
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def name(self):
|
| 39 |
+
return self._name
|
| 40 |
+
|
| 41 |
+
@name.setter
|
| 42 |
+
def name(self, value):
|
| 43 |
+
self._name = value
|
| 44 |
+
|
| 45 |
+
def terminate(self):
|
| 46 |
+
self.is_terminated = True
|
| 47 |
+
|
| 48 |
+
def get_depth(self):
|
| 49 |
+
time_diff = time.time() - self.depth_updated
|
| 50 |
+
# logging.warn('Market: %s order book1:(%s>%s)', self.name, time_diff, self.depth_updated)
|
| 51 |
+
if time_diff > self.update_rate:
|
| 52 |
+
logging.debug('%s should update...', self.name)
|
| 53 |
+
if not self.ask_update_depth():
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
time_diff = time.time() - self.depth_updated
|
| 57 |
+
# logging.warn('Market: %s order book2:(%s>%s)', self.name, time_diff, self.depth_updated)
|
| 58 |
+
|
| 59 |
+
if time_diff > config.market_expiration_time:
|
| 60 |
+
# logging.warn('Market: %s order book is expired(%s>%s)', self.name, timediff,
|
| 61 |
+
# config.market_expiration_time)
|
| 62 |
+
return None
|
| 63 |
+
return self.depth
|
| 64 |
+
|
| 65 |
+
def ask_update_depth(self):
|
| 66 |
+
try:
|
| 67 |
+
self.update_depth()
|
| 68 |
+
# self.convert_to_usd()
|
| 69 |
+
self.depth_updated = time.time()
|
| 70 |
+
return True
|
| 71 |
+
except Exception as e:
|
| 72 |
+
logging.error("Can't update market: %s - err:%s" % (self.name, str(e)))
|
| 73 |
+
# log_exception(logging.DEBUG)
|
| 74 |
+
return False
|
| 75 |
+
# traceback.print_exc()
|
| 76 |
+
|
| 77 |
+
def get_ticker(self):
|
| 78 |
+
depth = self.get_depth()
|
| 79 |
+
if not depth:
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
res = {'ask': {'price': 0, 'amount': 0}, 'bid': {'price': 0, 'amount': 0}}
|
| 83 |
+
|
| 84 |
+
if len(depth['asks']) > 0:
|
| 85 |
+
res['ask'] = depth['asks'][0]
|
| 86 |
+
if len(depth["bids"]) > 0:
|
| 87 |
+
res['bid'] = depth['bids'][0]
|
| 88 |
+
return res
|
| 89 |
+
|
| 90 |
+
def update_depth(self):
|
| 91 |
+
"""子类重写该方法,每个market的数据不一样"""
|
| 92 |
+
pass
|
code/train/Python/0060919_base.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#
|
| 3 |
+
# vim: tabstop=4 shiftwidth=4
|
| 4 |
+
|
| 5 |
+
# This program is free software; you can redistribute it and/or modify it
|
| 6 |
+
# under the terms of the GNU General Public License as published by the
|
| 7 |
+
# Free Software Foundation; only version 2 of the License is applicable.
|
| 8 |
+
#
|
| 9 |
+
# This program is distributed in the hope that it will be useful, but
|
| 10 |
+
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 11 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
| 12 |
+
# General Public License for more details.
|
| 13 |
+
#
|
| 14 |
+
# You should have received a copy of the GNU General Public License along
|
| 15 |
+
# with this program; if not, write to the Free Software Foundation, Inc.,
|
| 16 |
+
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
| 17 |
+
#
|
| 18 |
+
# Authors:
|
| 19 |
+
# Ricardo Rocha <ricardo@catalyst.net.nz>
|
| 20 |
+
#
|
| 21 |
+
# About this plugin:
|
| 22 |
+
# Helper object for all plugins.
|
| 23 |
+
#
|
| 24 |
+
# collectd:
|
| 25 |
+
# http://collectd.org
|
| 26 |
+
# collectd-python:
|
| 27 |
+
# http://collectd.org/documentation/manpages/collectd-python.5.shtml
|
| 28 |
+
#
|
| 29 |
+
|
| 30 |
+
import collectd
|
| 31 |
+
import datetime
|
| 32 |
+
import traceback
|
| 33 |
+
import socket
|
| 34 |
+
import json
|
| 35 |
+
import struct
|
| 36 |
+
import re
|
| 37 |
+
|
| 38 |
+
from ceph_argparse import parse_json_funcsigs, validate_command
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Base(object):
|
| 42 |
+
|
| 43 |
+
def __init__(self):
|
| 44 |
+
self.verbose = False
|
| 45 |
+
self.debug = False
|
| 46 |
+
self.prefix = ''
|
| 47 |
+
self.cluster = 'ceph'
|
| 48 |
+
self.testpool = 'test'
|
| 49 |
+
self.interval = 60.0
|
| 50 |
+
|
| 51 |
+
def config_callback(self, conf):
|
| 52 |
+
"""Takes a collectd conf object and fills in the local config."""
|
| 53 |
+
for node in conf.children:
|
| 54 |
+
if node.key == "Verbose":
|
| 55 |
+
if node.values[0] in ['True', 'true']:
|
| 56 |
+
self.verbose = True
|
| 57 |
+
elif node.key == "Debug":
|
| 58 |
+
if node.values[0] in ['True', 'true']:
|
| 59 |
+
self.debug = True
|
| 60 |
+
elif node.key == "Prefix":
|
| 61 |
+
self.prefix = node.values[0]
|
| 62 |
+
elif node.key == 'Cluster':
|
| 63 |
+
self.cluster = node.values[0]
|
| 64 |
+
elif node.key == 'TestPool':
|
| 65 |
+
self.testpool = node.values[0]
|
| 66 |
+
elif node.key == 'Interval':
|
| 67 |
+
self.interval = float(node.values[0])
|
| 68 |
+
else:
|
| 69 |
+
collectd.warning("%s: unknown config key: %s" % (self.prefix, node.key))
|
| 70 |
+
|
| 71 |
+
def dispatch(self, stats):
|
| 72 |
+
"""
|
| 73 |
+
Dispatches the given stats.
|
| 74 |
+
|
| 75 |
+
stats should be something like:
|
| 76 |
+
|
| 77 |
+
{'plugin': {'plugin_instance': {'type': {'type_instance': <value>, ...}}}}
|
| 78 |
+
"""
|
| 79 |
+
if not stats:
|
| 80 |
+
collectd.error("%s: failed to retrieve stats" % self.prefix)
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
self.logdebug("dispatching %d new stats :: %s" % (len(stats), stats))
|
| 84 |
+
try:
|
| 85 |
+
for plugin in stats.keys():
|
| 86 |
+
for plugin_instance in stats[plugin].keys():
|
| 87 |
+
for type in stats[plugin][plugin_instance].keys():
|
| 88 |
+
type_value = stats[plugin][plugin_instance][type]
|
| 89 |
+
if not isinstance(type_value, dict):
|
| 90 |
+
self.dispatch_value(plugin, plugin_instance, type, None, type_value)
|
| 91 |
+
else:
|
| 92 |
+
for type_instance in stats[plugin][plugin_instance][type].keys():
|
| 93 |
+
self.dispatch_value(plugin, plugin_instance,
|
| 94 |
+
type, type_instance,
|
| 95 |
+
stats[plugin][plugin_instance][type][type_instance])
|
| 96 |
+
except Exception as exc:
|
| 97 |
+
collectd.error("%s: failed to dispatch values :: %s :: %s"
|
| 98 |
+
% (self.prefix, exc, traceback.format_exc()))
|
| 99 |
+
|
| 100 |
+
def dispatch_value(self, plugin, plugin_instance, type, type_instance, value):
|
| 101 |
+
"""Looks for the given stat in stats, and dispatches it"""
|
| 102 |
+
self.logdebug("dispatching value %s.%s.%s.%s=%s"
|
| 103 |
+
% (plugin, plugin_instance, type, type_instance, value))
|
| 104 |
+
|
| 105 |
+
val = collectd.Values(type='gauge')
|
| 106 |
+
val.plugin=plugin
|
| 107 |
+
val.plugin_instance=plugin_instance
|
| 108 |
+
if type_instance is not None:
|
| 109 |
+
val.type_instance="%s-%s" % (type, type_instance)
|
| 110 |
+
# val.type_instance = "%s" % type_instance
|
| 111 |
+
else:
|
| 112 |
+
val.type_instance=type
|
| 113 |
+
val.values=[value]
|
| 114 |
+
val.interval = self.interval
|
| 115 |
+
val.dispatch()
|
| 116 |
+
self.logdebug("sent metric %s.%s.%s.%s.%s"
|
| 117 |
+
% (plugin, plugin_instance, type, type_instance, value))
|
| 118 |
+
|
| 119 |
+
#
|
| 120 |
+
# From /usr/bin/ceph: do socket IO against a ceph admin socket
|
| 121 |
+
#
|
| 122 |
+
# We copy / paste the code instead of just invoking /usr/bin/ceph to prevent a python interpreter start everytime
|
| 123 |
+
#
|
| 124 |
+
def admin_socket(self, asok_path, cmd, format=''):
|
| 125 |
+
"""
|
| 126 |
+
Send a daemon (--admin-daemon) command 'cmd'. asok_path is the
|
| 127 |
+
path to the admin socket; cmd is a list of strings; format may be
|
| 128 |
+
set to one of the formatted forms to get output in that form
|
| 129 |
+
(daemon commands don't support 'plain' output).
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
def do_sockio(path, cmd):
|
| 133 |
+
""" helper: do all the actual low-level stream I/O """
|
| 134 |
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
| 135 |
+
sock.connect(path)
|
| 136 |
+
try:
|
| 137 |
+
sock.sendall(cmd + '\0')
|
| 138 |
+
len_str = sock.recv(4)
|
| 139 |
+
if len(len_str) < 4:
|
| 140 |
+
raise RuntimeError("no data returned from admin socket")
|
| 141 |
+
l, = struct.unpack(">I", len_str)
|
| 142 |
+
ret = ''
|
| 143 |
+
|
| 144 |
+
got = 0
|
| 145 |
+
while got < l:
|
| 146 |
+
bit = sock.recv(l - got)
|
| 147 |
+
ret += bit
|
| 148 |
+
got += len(bit)
|
| 149 |
+
|
| 150 |
+
except Exception as e:
|
| 151 |
+
raise RuntimeError('exception: ' + str(e))
|
| 152 |
+
return ret
|
| 153 |
+
|
| 154 |
+
try:
|
| 155 |
+
cmd_json = do_sockio(asok_path,
|
| 156 |
+
json.dumps({"prefix":"get_command_descriptions"}))
|
| 157 |
+
except Exception as e:
|
| 158 |
+
raise RuntimeError('exception getting command descriptions: ' + str(e))
|
| 159 |
+
|
| 160 |
+
if cmd == 'get_command_descriptions':
|
| 161 |
+
return cmd_json
|
| 162 |
+
|
| 163 |
+
sigdict = parse_json_funcsigs(cmd_json, 'cli')
|
| 164 |
+
valid_dict = validate_command(sigdict, cmd)
|
| 165 |
+
if not valid_dict:
|
| 166 |
+
raise RuntimeError('invalid command')
|
| 167 |
+
|
| 168 |
+
if format:
|
| 169 |
+
valid_dict['format'] = format
|
| 170 |
+
|
| 171 |
+
try:
|
| 172 |
+
ret = do_sockio(asok_path, json.dumps(valid_dict))
|
| 173 |
+
except Exception as e:
|
| 174 |
+
raise RuntimeError('exception: ' + str(e))
|
| 175 |
+
|
| 176 |
+
return ret
|
| 177 |
+
|
| 178 |
+
def copy_stats(self, source_hash, selection):
|
| 179 |
+
"""
|
| 180 |
+
Copy stats from source_hash to target_hash based on applying the selection regex against the names
|
| 181 |
+
in the hash at the root level on the source hash.
|
| 182 |
+
|
| 183 |
+
Additonally, the following transformations are applied:
|
| 184 |
+
|
| 185 |
+
- For stat names ending in latency and referencing a hash the latency is calculated and substitutes
|
| 186 |
+
the hash in the target hash
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
target_hash = {}
|
| 190 |
+
|
| 191 |
+
for key in source_hash.keys():
|
| 192 |
+
|
| 193 |
+
stat_name = key
|
| 194 |
+
stat_value = source_hash[key]
|
| 195 |
+
|
| 196 |
+
# print 'Checking stat "%s"' % stat_name
|
| 197 |
+
|
| 198 |
+
if not re.match(r'%s' % selection, stat_name):
|
| 199 |
+
# Ignore not selected stats
|
| 200 |
+
continue
|
| 201 |
+
|
| 202 |
+
# Process latency
|
| 203 |
+
if isinstance(stat_value, dict):
|
| 204 |
+
lat_sum = float(stat_value['sum'])
|
| 205 |
+
lat_avgcount = float(stat_value['avgcount'])
|
| 206 |
+
if lat_avgcount == 0:
|
| 207 |
+
target_hash[stat_name] = 0
|
| 208 |
+
else:
|
| 209 |
+
target_hash[stat_name] = lat_sum / lat_avgcount
|
| 210 |
+
continue
|
| 211 |
+
|
| 212 |
+
# Process simple stats
|
| 213 |
+
target_hash[stat_name] = stat_value
|
| 214 |
+
|
| 215 |
+
return target_hash
|
| 216 |
+
|
| 217 |
+
def read_callback(self):
|
| 218 |
+
try:
|
| 219 |
+
start = datetime.datetime.now()
|
| 220 |
+
stats = self.get_stats()
|
| 221 |
+
self.logverbose("collectd new data from service :: took %d seconds"
|
| 222 |
+
% (datetime.datetime.now() - start).seconds)
|
| 223 |
+
except Exception as exc:
|
| 224 |
+
collectd.error("%s: failed to get stats :: %s :: %s"
|
| 225 |
+
% (self.prefix, exc, traceback.format_exc()))
|
| 226 |
+
self.dispatch(stats)
|
| 227 |
+
|
| 228 |
+
def get_stats(self):
|
| 229 |
+
collectd.error('Not implemented, should be subclassed')
|
| 230 |
+
|
| 231 |
+
def logverbose(self, msg):
|
| 232 |
+
if self.verbose:
|
| 233 |
+
collectd.info("%s: %s" % (self.prefix, msg))
|
| 234 |
+
|
| 235 |
+
def logdebug(self, msg):
|
| 236 |
+
if self.debug:
|
| 237 |
+
collectd.info("%s: %s" % (self.prefix, msg))
|
| 238 |
+
|
code/train/Python/0061284_answer.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
|
| 3 |
+
class Solution(object):
|
| 4 |
+
def lengthOfLongestSubstring(self, s):
|
| 5 |
+
"""
|
| 6 |
+
:type s: str
|
| 7 |
+
:rtype: int
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
length = 0
|
| 11 |
+
i = 0
|
| 12 |
+
j = 0
|
| 13 |
+
substring = set()
|
| 14 |
+
while i < len(s) and j < len(s):
|
| 15 |
+
if not s[i] in substring:
|
| 16 |
+
substring.add(s[i])
|
| 17 |
+
i += 1
|
| 18 |
+
length = max(length, i - j)
|
| 19 |
+
else:
|
| 20 |
+
substring.remove(s[j])
|
| 21 |
+
j += 1
|
| 22 |
+
return length
|
| 23 |
+
#-------------------------------------------------------------------------------
|
| 24 |
+
# Optimized o(n) solution
|
| 25 |
+
|
| 26 |
+
class Optimized(object):
|
| 27 |
+
def lengthOfLongestSubstring(self, s):
|
| 28 |
+
length = 0
|
| 29 |
+
i = 0
|
| 30 |
+
j = 0
|
| 31 |
+
dict = {}
|
| 32 |
+
for j in range (0, len(s)):
|
| 33 |
+
if s[j] in dict:
|
| 34 |
+
i = max(dict[s[j]], i)
|
| 35 |
+
length = max(length, j - i + 1)
|
| 36 |
+
dict[s[j]] = j + 1
|
| 37 |
+
|
| 38 |
+
return length
|
| 39 |
+
|
| 40 |
+
#-------------------------------------------------------------------------------
|
| 41 |
+
#Testing
|
| 42 |
+
|
| 43 |
+
def main():
|
| 44 |
+
x = Optimized()
|
| 45 |
+
y = x.lengthOfLongestSubstring("abcdedfffqwertyuioplkjtksladnf")
|
| 46 |
+
print y
|
| 47 |
+
|
| 48 |
+
main()
|
code/train/Python/0062850_hmi.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# (c) 2015,2016 - Jaguar Land Rover.
|
| 2 |
+
#
|
| 3 |
+
# Mozilla Public License 2.0
|
| 4 |
+
#
|
| 5 |
+
# Python-based hmi PoC for Software Loading Manager
|
| 6 |
+
#
|
| 7 |
+
|
| 8 |
+
import gtk
|
| 9 |
+
import dbus
|
| 10 |
+
import dbus.service
|
| 11 |
+
from dbus.mainloop.glib import DBusGMainLoop
|
| 12 |
+
import time
|
| 13 |
+
import threading
|
| 14 |
+
import code, signal
|
| 15 |
+
import traceback
|
| 16 |
+
import swm
|
| 17 |
+
from termios import tcflush, TCIOFLUSH
|
| 18 |
+
import settings
|
| 19 |
+
import sys
|
| 20 |
+
import os
|
| 21 |
+
import getopt
|
| 22 |
+
import daemon
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class DisplayProgress(threading.Thread):
|
| 26 |
+
|
| 27 |
+
def __init__(self, *arg):
|
| 28 |
+
super(DisplayProgress, self).__init__(*arg)
|
| 29 |
+
self.in_progress = True
|
| 30 |
+
self.update_description = None
|
| 31 |
+
self.update_start_time = None
|
| 32 |
+
self.update_stop_time = None
|
| 33 |
+
self.operation_hmi_message = None
|
| 34 |
+
self.operation_start_time = None
|
| 35 |
+
self.operation_stop_time = None
|
| 36 |
+
|
| 37 |
+
def set_manifest(self, description, start_time, stop_time):
|
| 38 |
+
self.update_description = description
|
| 39 |
+
self.update_start_time = start_time
|
| 40 |
+
self.update_stop_time = stop_time
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def set_operation(self, hmi_message, start_time, stop_time):
|
| 44 |
+
self.operation_hmi_message = hmi_message
|
| 45 |
+
self.operation_start_time = start_time
|
| 46 |
+
self.operation_stop_time = stop_time
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def exit_thread(self):
|
| 50 |
+
self.in_progress = False
|
| 51 |
+
self.join()
|
| 52 |
+
|
| 53 |
+
def run(self):
|
| 54 |
+
while self.in_progress:
|
| 55 |
+
if not self.update_description:
|
| 56 |
+
time.sleep(0.5)
|
| 57 |
+
continue
|
| 58 |
+
|
| 59 |
+
time.sleep(0.1)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
ct = time.time()
|
| 63 |
+
if self.update_stop_time >= ct:
|
| 64 |
+
completion = (self.update_stop_time - ct) / (self.update_stop_time - self.update_start_time)
|
| 65 |
+
else:
|
| 66 |
+
completion = 0.0
|
| 67 |
+
|
| 68 |
+
print "\033[HUpdate: {}\033[K".format(self.update_description)
|
| 69 |
+
|
| 70 |
+
print "{}{}\033[K".format("+"*int(60.0 - completion*60), "-"*int(completion*60))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# If no operation is in progress, clear sreen
|
| 74 |
+
if not self.operation_start_time:
|
| 75 |
+
continue
|
| 76 |
+
|
| 77 |
+
if self.update_stop_time >= ct:
|
| 78 |
+
completion = (self.operation_stop_time - ct) / (self.operation_stop_time - self.operation_start_time)
|
| 79 |
+
else:
|
| 80 |
+
completion = 0.0
|
| 81 |
+
|
| 82 |
+
print "\nOperation: {}\033[K".format(self.operation_hmi_message)
|
| 83 |
+
print "{}{}".format("+"*int(60.0 - completion*60), "-"*int(completion*60))
|
| 84 |
+
print "\033[J"
|
| 85 |
+
|
| 86 |
+
#
|
| 87 |
+
# Human Machine Interface Service
|
| 88 |
+
#
|
| 89 |
+
class HMIService(dbus.service.Object):
|
| 90 |
+
def __init__(self):
|
| 91 |
+
bus_name = dbus.service.BusName('org.genivi.Hmi',
|
| 92 |
+
bus=dbus.SessionBus())
|
| 93 |
+
|
| 94 |
+
dbus.service.Object.__init__(self, bus_name, '/org/genivi/Hmi')
|
| 95 |
+
self.progress_thread = DisplayProgress()
|
| 96 |
+
self.progress_thread.start()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@dbus.service.method('org.genivi.Hmi',
|
| 100 |
+
async_callbacks=('send_reply', 'send_error'))
|
| 101 |
+
def updateNotification(self,
|
| 102 |
+
update_id,
|
| 103 |
+
description,
|
| 104 |
+
send_reply,
|
| 105 |
+
send_error):
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
print "HMI: updateNotification()"
|
| 109 |
+
print " ID: {}".format(update_id)
|
| 110 |
+
print " description: {}".format(description)
|
| 111 |
+
print "---"
|
| 112 |
+
|
| 113 |
+
#
|
| 114 |
+
# Send back an async reply to the invoking SoftwareLoadingManager
|
| 115 |
+
# so that we can continue with user interaction without
|
| 116 |
+
# risking a DBUS timeout
|
| 117 |
+
#
|
| 118 |
+
send_reply(True)
|
| 119 |
+
|
| 120 |
+
print
|
| 121 |
+
print
|
| 122 |
+
print "DIALOG:"
|
| 123 |
+
print "DIALOG: UPDATE AVAILABLE"
|
| 124 |
+
print "DIALOG: update_id: {}".format(update_id)
|
| 125 |
+
print "DIALOG: Description: {}".format(description)
|
| 126 |
+
print "DIALOG:"
|
| 127 |
+
print "DIALOG: Process? (yes/no)"
|
| 128 |
+
|
| 129 |
+
# If we use input or raw_input, the whole dbus loop hangs after
|
| 130 |
+
# this method returns, for some reason.
|
| 131 |
+
tcflush(sys.stdin, TCIOFLUSH)
|
| 132 |
+
resp = sys.stdin.read(1)
|
| 133 |
+
tcflush(sys.stdin, TCIOFLUSH)
|
| 134 |
+
|
| 135 |
+
# resp = raw_input("DIALOG: Process? (yes/no): ")
|
| 136 |
+
print
|
| 137 |
+
|
| 138 |
+
if len(resp) == 0 or (resp[0] != 'y' and resp[0] != 'Y'):
|
| 139 |
+
approved = False
|
| 140 |
+
else:
|
| 141 |
+
approved = True
|
| 142 |
+
|
| 143 |
+
#
|
| 144 |
+
# Call SoftwareLoadingManager.package_confirmation()
|
| 145 |
+
# to inform it of user approval / decline.
|
| 146 |
+
#
|
| 147 |
+
swm.dbus_method('org.genivi.SoftwareLoadingManager','updateConfirmation', update_id, approved)
|
| 148 |
+
|
| 149 |
+
except Exception as e:
|
| 150 |
+
print "Exception: {}".format(e)
|
| 151 |
+
traceback.print_exc()
|
| 152 |
+
|
| 153 |
+
return None
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@dbus.service.method('org.genivi.Hmi',
|
| 157 |
+
async_callbacks=('send_reply', 'send_error'))
|
| 158 |
+
def manifestStarted(self,
|
| 159 |
+
update_id,
|
| 160 |
+
total_time_estimate,
|
| 161 |
+
description,
|
| 162 |
+
send_reply,
|
| 163 |
+
send_error):
|
| 164 |
+
try:
|
| 165 |
+
print "Manifest started"
|
| 166 |
+
send_reply(True)
|
| 167 |
+
print "\033[H\033[J"
|
| 168 |
+
ct = time.time()
|
| 169 |
+
self.progress_thread.set_manifest(description,
|
| 170 |
+
ct,
|
| 171 |
+
ct + float(total_time_estimate) / 1000.0)
|
| 172 |
+
|
| 173 |
+
except Exception as e:
|
| 174 |
+
print "Exception: {}".format(e)
|
| 175 |
+
traceback.print_exc()
|
| 176 |
+
|
| 177 |
+
return None
|
| 178 |
+
|
| 179 |
+
@dbus.service.method('org.genivi.Hmi',
|
| 180 |
+
async_callbacks=('send_reply', 'send_error'))
|
| 181 |
+
def operationStarted(self,
|
| 182 |
+
operation_id,
|
| 183 |
+
time_estimate,
|
| 184 |
+
description,
|
| 185 |
+
send_reply,
|
| 186 |
+
send_error):
|
| 187 |
+
|
| 188 |
+
try:
|
| 189 |
+
print "Op started"
|
| 190 |
+
send_reply(True)
|
| 191 |
+
ct = time.time()
|
| 192 |
+
self.progress_thread.set_operation(description, ct, ct + float(time_estimate) / 1000.0)
|
| 193 |
+
except Exception as e:
|
| 194 |
+
print "Exception: {}".format(e)
|
| 195 |
+
traceback.print_exc()
|
| 196 |
+
return None
|
| 197 |
+
|
| 198 |
+
@dbus.service.method('org.genivi.Hmi',
|
| 199 |
+
async_callbacks=('send_reply', 'send_error'))
|
| 200 |
+
def updateReport(self,
|
| 201 |
+
update_id,
|
| 202 |
+
results,
|
| 203 |
+
send_reply,
|
| 204 |
+
send_error):
|
| 205 |
+
try:
|
| 206 |
+
send_reply(True)
|
| 207 |
+
self.progress_thread.exit_thread()
|
| 208 |
+
print "Update report"
|
| 209 |
+
print " ID: {}".format(update_id)
|
| 210 |
+
print " results:"
|
| 211 |
+
for result in results:
|
| 212 |
+
print " operation_id: {}".format(result['id'])
|
| 213 |
+
print " code: {}".format(result['result_code'])
|
| 214 |
+
print " text: {}".format(result['result_text'])
|
| 215 |
+
print " ---"
|
| 216 |
+
print "---"
|
| 217 |
+
except Exception as e:
|
| 218 |
+
print "Exception: {}".format(e)
|
| 219 |
+
traceback.print_exc()
|
| 220 |
+
return None
|
| 221 |
+
|
| 222 |
+
class HMIDaemon(daemon.Daemon):
|
| 223 |
+
"""
|
| 224 |
+
"""
|
| 225 |
+
|
| 226 |
+
def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
|
| 227 |
+
super(HMIDaemon, self).__init__(pidfile, stdin, stdout, stderr)
|
| 228 |
+
|
| 229 |
+
def run(self):
|
| 230 |
+
gtk.gdk.threads_init()
|
| 231 |
+
DBusGMainLoop(set_as_default=True)
|
| 232 |
+
hmi = HMIService()
|
| 233 |
+
while True:
|
| 234 |
+
gtk.main_iteration()
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def usage():
|
| 238 |
+
print "Usage:", sys.argv[0], "foreground|start|stop|restart"
|
| 239 |
+
print
|
| 240 |
+
print " foreground Start in foreground"
|
| 241 |
+
print " start Start in background"
|
| 242 |
+
print " stop Stop daemon running in background"
|
| 243 |
+
print " restart Restart daemon running in background"
|
| 244 |
+
print
|
| 245 |
+
print "Example:", sys.argv[0],"foreground"
|
| 246 |
+
sys.exit(1)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
print "HMI Simulator - Initializing"
|
| 251 |
+
pid_file = settings.PID_FILE_DIR + os.path.splitext(os.path.basename(__file__))[0] + '.pid'
|
| 252 |
+
|
| 253 |
+
try:
|
| 254 |
+
opts, args = getopt.getopt(sys.argv[1:], "")
|
| 255 |
+
except getopt.GetoptError:
|
| 256 |
+
print "HMI Simulator - Could not parse arguments."
|
| 257 |
+
usage()
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
for a in args:
|
| 261 |
+
if a in ('foreground', 'fg'):
|
| 262 |
+
print "HMI Simulator - Running"
|
| 263 |
+
print "Please enter package installation approval when prompted"
|
| 264 |
+
hmi_daemon = HMIDaemon(pid_file, stdin='/dev/stdin', stdout='/dev/stdout', stderr='/dev/stderr')
|
| 265 |
+
hmi_daemon.run()
|
| 266 |
+
elif a in ('start', 'st'):
|
| 267 |
+
print "HMI Simulator - Starting"
|
| 268 |
+
hmi_daemon = HMIDaemon(pid_file, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null')
|
| 269 |
+
hmi_daemon.start()
|
| 270 |
+
elif a in ('stop', 'sp'):
|
| 271 |
+
print "HMI Simulator - Stopping"
|
| 272 |
+
hmi_daemon = HMIDaemon(pid_file, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null')
|
| 273 |
+
hmi_daemon.stop()
|
| 274 |
+
elif a in ('restart', 're'):
|
| 275 |
+
print "HMI Simulator - Restarting"
|
| 276 |
+
hmi_daemon = HMIDaemon(pid_file, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null')
|
| 277 |
+
hmi_daemon.restart()
|
| 278 |
+
else:
|
| 279 |
+
print "Unknown command: {}".format(a)
|
| 280 |
+
usage()
|
| 281 |
+
sys.exit(1)
|
code/train/Python/0062944_rnnlm-batch.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dynet import *
|
| 2 |
+
import time
|
| 3 |
+
import random
|
| 4 |
+
|
| 5 |
+
LAYERS = 2
|
| 6 |
+
INPUT_DIM = 256 #50 #256
|
| 7 |
+
HIDDEN_DIM = 256 # 50 #1024
|
| 8 |
+
VOCAB_SIZE = 0
|
| 9 |
+
MB_SIZE = 50 # mini batch size
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
from itertools import count
|
| 14 |
+
import sys
|
| 15 |
+
import util
|
| 16 |
+
|
| 17 |
+
class RNNLanguageModel:
|
| 18 |
+
def __init__(self, model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOCAB_SIZE, builder=SimpleRNNBuilder):
|
| 19 |
+
# Char-level LSTM (layers=2, input=256, hidden=128, model)
|
| 20 |
+
self.builder = builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model)
|
| 21 |
+
# Lookup parameters for word embeddings
|
| 22 |
+
self.lookup = model.add_lookup_parameters((VOCAB_SIZE, INPUT_DIM))
|
| 23 |
+
# Softmax weights/biases on top of LSTM outputs
|
| 24 |
+
self.R = model.add_parameters((VOCAB_SIZE, HIDDEN_DIM))
|
| 25 |
+
self.bias = model.add_parameters((VOCAB_SIZE))
|
| 26 |
+
|
| 27 |
+
# Build the language model graph
|
| 28 |
+
def BuildLMGraph(self, sents):
|
| 29 |
+
renew_cg()
|
| 30 |
+
# initialize the RNN
|
| 31 |
+
init_state = self.builder.initial_state()
|
| 32 |
+
# parameters -> expressions
|
| 33 |
+
R = parameter(self.R)
|
| 34 |
+
bias = parameter(self.bias)
|
| 35 |
+
|
| 36 |
+
S = vocab.w2i["<s>"]
|
| 37 |
+
# get the cids and masks for each step
|
| 38 |
+
tot_chars = 0
|
| 39 |
+
cids = []
|
| 40 |
+
masks = []
|
| 41 |
+
|
| 42 |
+
for i in range(len(sents[0])):
|
| 43 |
+
cids.append([(vocab.w2i[sent[i]] if len(sent) > i else S) for sent in sents])
|
| 44 |
+
mask = [(1 if len(sent)>i else 0) for sent in sents]
|
| 45 |
+
masks.append(mask)
|
| 46 |
+
tot_chars += sum(mask)
|
| 47 |
+
|
| 48 |
+
# start the rnn with "<s>"
|
| 49 |
+
init_ids = cids[0]
|
| 50 |
+
s = init_state.add_input(lookup_batch(self.lookup, init_ids))
|
| 51 |
+
|
| 52 |
+
losses = []
|
| 53 |
+
|
| 54 |
+
# feed char vectors into the RNN and predict the next char
|
| 55 |
+
for cid, mask in zip(cids[1:], masks[1:]):
|
| 56 |
+
score = affine_transform([bias, R, s.output()])
|
| 57 |
+
loss = pickneglogsoftmax_batch(score, cid)
|
| 58 |
+
# mask the loss if at least one sentence is shorter
|
| 59 |
+
if mask[-1] != 1:
|
| 60 |
+
mask_expr = inputVector(mask)
|
| 61 |
+
mask_expr = reshape(mask_expr, (1,), len(sents))
|
| 62 |
+
loss = loss * mask_expr
|
| 63 |
+
|
| 64 |
+
losses.append(loss)
|
| 65 |
+
# update the state of the RNN
|
| 66 |
+
cemb = lookup_batch(self.lookup, cid)
|
| 67 |
+
s = s.add_input(cemb)
|
| 68 |
+
|
| 69 |
+
return sum_batches(esum(losses)), tot_chars
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def sample(self, first=1, nchars=0, stop=-1):
|
| 73 |
+
res = [first]
|
| 74 |
+
renew_cg()
|
| 75 |
+
state = self.builder.initial_state()
|
| 76 |
+
|
| 77 |
+
R = parameter(self.R)
|
| 78 |
+
bias = parameter(self.bias)
|
| 79 |
+
cw = first
|
| 80 |
+
while True:
|
| 81 |
+
x_t = lookup(self.lookup, cw)
|
| 82 |
+
state = state.add_input(x_t)
|
| 83 |
+
y_t = state.output()
|
| 84 |
+
r_t = bias + (R * y_t)
|
| 85 |
+
ydist = softmax(r_t)
|
| 86 |
+
dist = ydist.vec_value()
|
| 87 |
+
rnd = random.random()
|
| 88 |
+
for i,p in enumerate(dist):
|
| 89 |
+
rnd -= p
|
| 90 |
+
if rnd <= 0: break
|
| 91 |
+
res.append(i)
|
| 92 |
+
cw = i
|
| 93 |
+
if cw == stop: break
|
| 94 |
+
if nchars and len(res) > nchars: break
|
| 95 |
+
return res
|
| 96 |
+
|
| 97 |
+
if __name__ == '__main__':
|
| 98 |
+
parser = argparse.ArgumentParser()
|
| 99 |
+
parser.add_argument('corpus', help='Path to the corpus file.')
|
| 100 |
+
args = parser.parse_args()
|
| 101 |
+
|
| 102 |
+
train = util.CharsCorpusReader(args.corpus, begin="<s>")
|
| 103 |
+
vocab = util.Vocab.from_corpus(train)
|
| 104 |
+
|
| 105 |
+
VOCAB_SIZE = vocab.size()
|
| 106 |
+
|
| 107 |
+
model = Model()
|
| 108 |
+
sgd = SimpleSGDTrainer(model)
|
| 109 |
+
|
| 110 |
+
#lm = RNNLanguageModel(model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOCAB_SIZE, builder=SimpleRNNBuilder)
|
| 111 |
+
lm = RNNLanguageModel(model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOCAB_SIZE, builder=LSTMBuilder)
|
| 112 |
+
|
| 113 |
+
train = list(train)
|
| 114 |
+
# Sort training sentences in descending order and count minibatches
|
| 115 |
+
train.sort(key=lambda x: -len(x))
|
| 116 |
+
train_order = [x*MB_SIZE for x in range(int((len(train)-1)/MB_SIZE + 1))]
|
| 117 |
+
|
| 118 |
+
# Perform training
|
| 119 |
+
i = 0
|
| 120 |
+
chars = loss = 0.0
|
| 121 |
+
for ITER in range(100):
|
| 122 |
+
random.shuffle(train_order)
|
| 123 |
+
#_start = time.time()
|
| 124 |
+
for sid in train_order:
|
| 125 |
+
i += 1
|
| 126 |
+
#if i % int(50) == 0:
|
| 127 |
+
sgd.status()
|
| 128 |
+
if chars > 0: print(loss / chars,)
|
| 129 |
+
for _ in range(1):
|
| 130 |
+
samp = lm.sample(first=vocab.w2i["<s>"],stop=vocab.w2i["\n"])
|
| 131 |
+
print("".join([vocab.i2w[c] for c in samp]).strip())
|
| 132 |
+
loss = 0.0
|
| 133 |
+
chars = 0.0
|
| 134 |
+
|
| 135 |
+
# train on the minibatch
|
| 136 |
+
errs, mb_chars = lm.BuildLMGraph(train[sid: sid + MB_SIZE])
|
| 137 |
+
loss += errs.scalar_value()
|
| 138 |
+
chars += mb_chars
|
| 139 |
+
errs.backward()
|
| 140 |
+
sgd.update()
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
#print "TM:",(time.time() - _start)/chars
|
| 144 |
+
print("ITER",ITER,loss)
|
| 145 |
+
#print(loss / chars,)
|
| 146 |
+
#print "TM:",(time.time() - _start)/len(train)
|
| 147 |
+
sgd.status()
|
| 148 |
+
sgd.update_epoch(1.0)
|
code/train/Python/0063615_init__.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import asyncio
|
| 3 |
+
from pitcrew import task
|
| 4 |
+
from uuid import uuid4
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class DeployPitcrew(task.BaseTask):
|
| 8 |
+
"""This example builds and deploys pitcrew.io. It uses s3, cloudfront and acm to deploy
|
| 9 |
+
this website using ssl. """
|
| 10 |
+
|
| 11 |
+
async def run(self):
|
| 12 |
+
# make sure the build requirements are installed
|
| 13 |
+
await self.sh("pip install -r requirements-build.txt")
|
| 14 |
+
# create the bucket
|
| 15 |
+
await self.sh("aws s3api create-bucket --bucket pitcrew-site")
|
| 16 |
+
# setup aws & build + upload site
|
| 17 |
+
await asyncio.gather(self.setup_aws(), self.build_and_sync())
|
| 18 |
+
|
| 19 |
+
async def setup_aws(self):
|
| 20 |
+
# first find the zone
|
| 21 |
+
zones = json.loads(await self.sh("aws route53 list-hosted-zones"))[
|
| 22 |
+
"HostedZones"
|
| 23 |
+
]
|
| 24 |
+
zone_id = None
|
| 25 |
+
for zone in zones:
|
| 26 |
+
if zone["Name"] == "pitcrew.io.":
|
| 27 |
+
zone_id = zone["Id"]
|
| 28 |
+
break
|
| 29 |
+
|
| 30 |
+
assert zone_id, "no zone_id found for pitcrew.io"
|
| 31 |
+
|
| 32 |
+
# setup the certificate
|
| 33 |
+
cert_arn = await self.setup_acm(zone_id)
|
| 34 |
+
# setup the CDN
|
| 35 |
+
cf_id = await self.setup_cloudfront(zone_id, cert_arn)
|
| 36 |
+
dist = json.loads(
|
| 37 |
+
await self.sh(f"aws cloudfront get-distribution --id {self.esc(cf_id)}")
|
| 38 |
+
)["Distribution"]
|
| 39 |
+
domain_name = dist["DomainName"]
|
| 40 |
+
|
| 41 |
+
# add the DNS records
|
| 42 |
+
await self.ensure.aws.route53.has_records(
|
| 43 |
+
zone_id,
|
| 44 |
+
[
|
| 45 |
+
{
|
| 46 |
+
"Name": "pitcrew.io.",
|
| 47 |
+
"Type": "A",
|
| 48 |
+
"AliasTarget": {
|
| 49 |
+
"HostedZoneId": "Z2FDTNDATAQYW2",
|
| 50 |
+
"DNSName": f"{domain_name}.",
|
| 51 |
+
"EvaluateTargetHealth": False,
|
| 52 |
+
},
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"Name": "pitcrew.io.",
|
| 56 |
+
"Type": "AAAA",
|
| 57 |
+
"AliasTarget": {
|
| 58 |
+
"HostedZoneId": "Z2FDTNDATAQYW2",
|
| 59 |
+
"DNSName": f"{domain_name}.",
|
| 60 |
+
"EvaluateTargetHealth": False,
|
| 61 |
+
},
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"Name": "www.pitcrew.io.",
|
| 65 |
+
"Type": "CNAME",
|
| 66 |
+
"TTL": 300,
|
| 67 |
+
"ResourceRecords": [{"Value": domain_name}],
|
| 68 |
+
},
|
| 69 |
+
],
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
async def setup_acm(self, zone_id) -> str:
|
| 73 |
+
# look for the certificate
|
| 74 |
+
certs = json.loads(
|
| 75 |
+
await self.sh("aws acm list-certificates --certificate-statuses ISSUED")
|
| 76 |
+
)["CertificateSummaryList"]
|
| 77 |
+
for cert in certs:
|
| 78 |
+
if cert["DomainName"] == "pitcrew.io":
|
| 79 |
+
return cert["CertificateArn"]
|
| 80 |
+
|
| 81 |
+
# if it doesn't exist, create it
|
| 82 |
+
arn = json.loads(
|
| 83 |
+
await self.sh(
|
| 84 |
+
f"aws acm request-certificate --domain-name pitcrew.io --validation-method DNS --subject-alternative-names {self.esc('*.pitcrew.io')}"
|
| 85 |
+
)
|
| 86 |
+
)["CertificateArn"]
|
| 87 |
+
cert_description = json.loads(
|
| 88 |
+
await self.sh(
|
| 89 |
+
f"aws acm describe-certificate --certificate-arn {self.esc(arn)}"
|
| 90 |
+
)
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
validation = cert_description["Certificate"]["DomainValidationOptions"][0]
|
| 94 |
+
await self.ensure.aws.route53.has_records(
|
| 95 |
+
zone_id,
|
| 96 |
+
[
|
| 97 |
+
{
|
| 98 |
+
"Name": validation["ResourceRecord"]["Name"],
|
| 99 |
+
"Type": validation["ResourceRecord"]["Type"],
|
| 100 |
+
"TTL": 60,
|
| 101 |
+
"ResourceRecords": [
|
| 102 |
+
{"Value": validation["ResourceRecord"]["Value"]}
|
| 103 |
+
],
|
| 104 |
+
}
|
| 105 |
+
],
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
await self.sh(
|
| 109 |
+
f"aws acm wait certificate-validated --certificate-arn {self.esc(arn)}"
|
| 110 |
+
)
|
| 111 |
+
return arn
|
| 112 |
+
|
| 113 |
+
async def setup_cloudfront(self, zone_id, cert_arn) -> str:
|
| 114 |
+
s3_origin = "pitcrew-site.s3.amazonaws.com"
|
| 115 |
+
|
| 116 |
+
list_distributions = json.loads(
|
| 117 |
+
await self.sh(f"aws cloudfront list-distributions")
|
| 118 |
+
)
|
| 119 |
+
for dist in list_distributions["DistributionList"]["Items"]:
|
| 120 |
+
if dist["Origins"]["Items"][0]["DomainName"] == s3_origin:
|
| 121 |
+
return dist["Id"]
|
| 122 |
+
|
| 123 |
+
config = {
|
| 124 |
+
"DefaultRootObject": "index.html",
|
| 125 |
+
"Aliases": {"Quantity": 2, "Items": ["pitcrew.io", "www.pitcrew.io"]},
|
| 126 |
+
"Origins": {
|
| 127 |
+
"Quantity": 1,
|
| 128 |
+
"Items": [
|
| 129 |
+
{
|
| 130 |
+
"Id": "pitcrew-origin",
|
| 131 |
+
"DomainName": s3_origin,
|
| 132 |
+
"S3OriginConfig": {"OriginAccessIdentity": ""},
|
| 133 |
+
}
|
| 134 |
+
],
|
| 135 |
+
},
|
| 136 |
+
"DefaultCacheBehavior": {
|
| 137 |
+
"TargetOriginId": "pitcrew-origin",
|
| 138 |
+
"ForwardedValues": {
|
| 139 |
+
"QueryString": True,
|
| 140 |
+
"Cookies": {"Forward": "none"},
|
| 141 |
+
},
|
| 142 |
+
"TrustedSigners": {"Enabled": False, "Quantity": 0},
|
| 143 |
+
"ViewerProtocolPolicy": "redirect-to-https",
|
| 144 |
+
"MinTTL": 180,
|
| 145 |
+
},
|
| 146 |
+
"CallerReference": str(uuid4()),
|
| 147 |
+
"Comment": "Created by crew",
|
| 148 |
+
"Enabled": True,
|
| 149 |
+
"ViewerCertificate": {
|
| 150 |
+
"ACMCertificateArn": cert_arn,
|
| 151 |
+
"SSLSupportMethod": "sni-only",
|
| 152 |
+
},
|
| 153 |
+
}
|
| 154 |
+
create_distribution = json.loads(
|
| 155 |
+
await self.sh(
|
| 156 |
+
f"aws cloudfront create-distribution --distribution-config {self.esc(json.dumps(config))}"
|
| 157 |
+
)
|
| 158 |
+
)
|
| 159 |
+
cf_id = create_distribution["Distribution"]["Id"]
|
| 160 |
+
await self.sh(f"aws cloudfront wait distribution-deployed --id {cf_id}")
|
| 161 |
+
return cf_id
|
| 162 |
+
|
| 163 |
+
async def build_and_sync(self):
|
| 164 |
+
await self.examples.deploy_pitcrew.build()
|
| 165 |
+
await self.sh("aws s3 sync --acl public-read out/ s3://pitcrew-site/")
|
code/train/Python/0063702_mass_path_distance.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Created on Wed May 15 19:23:23 2013
|
| 4 |
+
|
| 5 |
+
@author: andres
|
| 6 |
+
"""
|
| 7 |
+
import networkx as nx
|
| 8 |
+
import networkb, numpy, json
|
| 9 |
+
from scipy import spatial
|
| 10 |
+
import logging
|
| 11 |
+
logger = logging.getLogger('networkb.algorithms.mass_path_distance')
|
| 12 |
+
|
| 13 |
+
def mass_path_distance(bn,N_clus,op='first',correlation='both'):
|
| 14 |
+
"""
|
| 15 |
+
Returns mass, maximun radio, maximun path length and average path
|
| 16 |
+
length for all clusters at critical threshold. If op='first' the
|
| 17 |
+
critical threshold is the nearest to 1 and if op='biggest' the
|
| 18 |
+
threshold is the one with the biggest jump in the percolation curve.
|
| 19 |
+
"""
|
| 20 |
+
N=[]
|
| 21 |
+
lmean=[]
|
| 22 |
+
lmax=[]
|
| 23 |
+
rmax=[]
|
| 24 |
+
voxels=bn.get_node2voxel()
|
| 25 |
+
affine=bn.get_affine()
|
| 26 |
+
|
| 27 |
+
jumps=networkb.find_th_jumps(bn,N_clus)
|
| 28 |
+
if op=='first':
|
| 29 |
+
if len(jumps)==0:
|
| 30 |
+
print 'no jumps'
|
| 31 |
+
return {'N':[],'rmax':[],'lmax':[],'lmean':[]}
|
| 32 |
+
pc=max([jump[0] for jump in jumps])
|
| 33 |
+
elif op=='biggest':
|
| 34 |
+
gap=0
|
| 35 |
+
pc=1
|
| 36 |
+
gc=bn.get_gc()[0]
|
| 37 |
+
th=bn.get_th()
|
| 38 |
+
if len(jumps)==0:
|
| 39 |
+
print 'no jumps'
|
| 40 |
+
return {'N':[],'rmax':[],'lmax':[],'lmean':[]}
|
| 41 |
+
for jump in jumps:
|
| 42 |
+
j=th.index(jump)
|
| 43 |
+
if gc[j-1]-gc[j]>gap:
|
| 44 |
+
pc=jump[0]
|
| 45 |
+
gap=gc[j-1]-gc[j]
|
| 46 |
+
logger.info('pc=%f',pc)
|
| 47 |
+
G=bn.get_Graph(pc,correlation=correlation)
|
| 48 |
+
logger.info('number of nodes in network at pc: %i',G.number_of_nodes())
|
| 49 |
+
cluster_list=nx.connected_components(G)
|
| 50 |
+
edge_list=G.edges()
|
| 51 |
+
logger.info('number of clusters: %i',len(cluster_list))
|
| 52 |
+
N=[len(x) for x in cluster_list]
|
| 53 |
+
for i,nodelist in enumerate(cluster_list):
|
| 54 |
+
if i<10:
|
| 55 |
+
logger.info('procesing cluster %i of mass %i',i,N[i])
|
| 56 |
+
else:
|
| 57 |
+
logger.debug('procesing cluster %i of mass %i',i,N[i])
|
| 58 |
+
Gsub=bn.get_SubGraph(float(pc),nodelist,edge_list)
|
| 59 |
+
A=numpy.zeros([N[i],3])
|
| 60 |
+
pos=numpy.array([0,0,0,1])
|
| 61 |
+
path_length=[]
|
| 62 |
+
H = Gsub.copy()
|
| 63 |
+
for j,node in enumerate(H):
|
| 64 |
+
temp=[x for x in nx.single_source_shortest_path_length(Gsub, node).values() if x>0]
|
| 65 |
+
path_length.extend(temp)
|
| 66 |
+
pos[0:3]=voxels[str(node)]
|
| 67 |
+
A[j,:]=numpy.dot(affine, numpy.transpose(pos))[0:3]
|
| 68 |
+
Gsub.remove_node(node)
|
| 69 |
+
D=spatial.distance.cdist(A,A)
|
| 70 |
+
rmax.append(numpy.max(D))
|
| 71 |
+
lmax.append(max(path_length))
|
| 72 |
+
lmean.append(numpy.mean(path_length))
|
| 73 |
+
del Gsub, D, A, pos, path_length
|
| 74 |
+
json.dump({'N':N,'rmax':rmax,'lmax':lmax,'lmean':lmean},
|
| 75 |
+
open(bn.cluster_properties_file,'w'))
|
| 76 |
+
return {'N':N,'rmax':rmax,'lmax':lmax,'lmean':lmean}
|
code/train/Python/0063710_parser_test.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlite3 import dbapi2
|
| 2 |
+
from os.path import dirname
|
| 3 |
+
from unittest import main, TestCase
|
| 4 |
+
from sqlalchemy.engine.url import URL
|
| 5 |
+
from datetime import date
|
| 6 |
+
|
| 7 |
+
from medic import orm
|
| 8 |
+
from medic.parser import MedlineXMLParser, PubMedXMLParser
|
| 9 |
+
|
| 10 |
+
__author__ = 'Florian Leitner'
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ParserTest(TestCase):
|
| 14 |
+
MEDLINE_STRUCTURE_FILE = dirname(__file__) + '/medline.xml'
|
| 15 |
+
PMID = 123
|
| 16 |
+
|
| 17 |
+
ITEMS = [
|
| 18 |
+
orm.Identifier(PMID, 'doi', 'valid doi'),
|
| 19 |
+
orm.Identifier(PMID, 'pii', 'invalid pii'),
|
| 20 |
+
orm.Abstract(PMID, 'NLM', 'copyright info'),
|
| 21 |
+
orm.Section(PMID, 'NLM', 1, 'Background', 'background text', 'background label'),
|
| 22 |
+
orm.Section(PMID, 'NLM', 2, 'Objective', 'objective text', 'objective label'),
|
| 23 |
+
orm.Section(PMID, 'NLM', 3, 'Methods', 'methods text', 'methods label'),
|
| 24 |
+
orm.Section(PMID, 'NLM', 4, 'Methods', 'duplicate methods', 'methods label'),
|
| 25 |
+
orm.Section(PMID, 'NLM', 5, 'Results', 'results text', 'results label'),
|
| 26 |
+
orm.Section(PMID, 'NLM', 6, 'Conclusions', 'conclusions text', 'conclusions label'),
|
| 27 |
+
orm.Section(PMID, 'NLM', 7, 'Unlabelled', 'unlabelled text with\xa0encoding\x96errors'),
|
| 28 |
+
orm.Section(PMID, 'NLM', 8, 'Unassigned', 'abstract text', 'abstract label'),
|
| 29 |
+
orm.Section(PMID, 'NLM', 9, 'Abstract', 'default text'),
|
| 30 |
+
orm.Author(PMID, 1, 'Author', forename='First'),
|
| 31 |
+
orm.Author(PMID, 2, 'Middle', suffix='Suf'),
|
| 32 |
+
orm.Author(PMID, 3, 'Author', forename='P Last', initials='PL'),
|
| 33 |
+
orm.Database(PMID, 'db1', 'acc1'),
|
| 34 |
+
orm.Database(PMID, 'db1', 'acc2'),
|
| 35 |
+
orm.Database(PMID, 'db1', 'acc3'),
|
| 36 |
+
orm.Database(PMID, 'db2', 'acc'),
|
| 37 |
+
orm.PublicationType(PMID, 'publication type 1'.upper()),
|
| 38 |
+
orm.PublicationType(PMID, 'publication type 2'.upper()),
|
| 39 |
+
orm.Chemical(PMID, 1, "chemical substance 1"),
|
| 40 |
+
orm.Chemical(PMID, 2, "chemical substance 2", "EC 1.1.1.1"),
|
| 41 |
+
orm.Descriptor(PMID, 1, 'minor geographic descriptor'),
|
| 42 |
+
orm.Qualifier(PMID, 1, 1, 'minor qualifier'),
|
| 43 |
+
orm.Descriptor(PMID, 2, 'major descriptor', True),
|
| 44 |
+
orm.Qualifier(PMID, 2, 1, 'major qualifier', True),
|
| 45 |
+
orm.Qualifier(PMID, 2, 2, 'another qualifier'),
|
| 46 |
+
orm.Descriptor(PMID, 3, 'major descriptor', True),
|
| 47 |
+
orm.Qualifier(PMID, 3, 1, 'minor qualifier'),
|
| 48 |
+
orm.Descriptor(PMID, 4, 'minor descriptor'),
|
| 49 |
+
orm.Qualifier(PMID, 4, 1, 'major qualifier', True),
|
| 50 |
+
orm.Identifier(PMID, 'pmc', 'PMC12345'),
|
| 51 |
+
orm.Abstract(PMID, 'Publisher'),
|
| 52 |
+
orm.Section(PMID, 'Publisher', 1, 'Unassigned', 'explanation for publisher abstract',
|
| 53 |
+
truncated=True),
|
| 54 |
+
orm.Abstract(PMID, 'NASA', 'NASA copyright'),
|
| 55 |
+
orm.Section(PMID, 'NASA', 1, 'Conclusions', 'NASA conclusions', 'NASA label'),
|
| 56 |
+
orm.Keyword(PMID, 'NLM', 1, 'NLM minor keyword'),
|
| 57 |
+
orm.Keyword(PMID, 'NLM', 2, 'major keyword', True),
|
| 58 |
+
orm.Keyword(PMID, 'NLM', 3, 'minor keyword'),
|
| 59 |
+
orm.Keyword(PMID, 'NASA', 1, 'NASA keyword'),
|
| 60 |
+
orm.Citation(PMID, 'MEDLINE', '[a translated title].', 'NLM Jour Abbrev', '1950 some random date string',
|
| 61 |
+
date(1974, 2, 19), date(1974, 11, 19), date(2006, 2, 14),
|
| 62 |
+
'vol 1(no 1)', '100-10'),
|
| 63 |
+
orm.Citation(987, 'MEDLINE', 'title', 'NLM Jour Abbrev', '1990 season',
|
| 64 |
+
date(1974, 2, 19), date(1974, 11, 19), date(2006, 2, 14)),
|
| 65 |
+
orm.Identifier(987, 'doi', 'some doi'),
|
| 66 |
+
]
|
| 67 |
+
def setUp(self):
|
| 68 |
+
self.stream = open(ParserTest.MEDLINE_STRUCTURE_FILE)
|
| 69 |
+
|
| 70 |
+
def parse(self, parser, items):
|
| 71 |
+
reps = sorted(str(i) for i in items)
|
| 72 |
+
recv = []
|
| 73 |
+
to_delete = [123, 987]
|
| 74 |
+
last_item = None
|
| 75 |
+
count = -1
|
| 76 |
+
|
| 77 |
+
for item in parser.parse(self.stream):
|
| 78 |
+
if type(item) == int:
|
| 79 |
+
# DeleteCitation elements
|
| 80 |
+
assert item in to_delete, item
|
| 81 |
+
to_delete.remove(item)
|
| 82 |
+
else:
|
| 83 |
+
count += 1
|
| 84 |
+
recv.append(str(item))
|
| 85 |
+
self.assertTrue(item in items, "\n" + str(item) + str(items[count]))
|
| 86 |
+
last_item = item
|
| 87 |
+
yield item
|
| 88 |
+
|
| 89 |
+
self.assertEqual(len(items), count + 1, repr(last_item))
|
| 90 |
+
|
| 91 |
+
for expected, received in zip(reps, sorted(recv)):
|
| 92 |
+
self.assertEqual(expected, received)
|
| 93 |
+
|
| 94 |
+
def testParseToDB(self):
|
| 95 |
+
orm.InitDb(URL('sqlite'), module=dbapi2)
|
| 96 |
+
self.sess = orm.Session()
|
| 97 |
+
parser = PubMedXMLParser(unique=False) # do not skip records with versions
|
| 98 |
+
|
| 99 |
+
for item in self.parse(parser, ParserTest.ITEMS):
|
| 100 |
+
self.sess.add(item)
|
| 101 |
+
|
| 102 |
+
self.sess.commit()
|
| 103 |
+
|
| 104 |
+
def testParseAll(self):
|
| 105 |
+
parser = PubMedXMLParser(unique=False) # do not skip records with versions
|
| 106 |
+
list(self.parse(parser, ParserTest.ITEMS))
|
| 107 |
+
|
| 108 |
+
def testParseSkipVersion(self):
|
| 109 |
+
parser = MedlineXMLParser(unique=True) # skip records with versions
|
| 110 |
+
list(self.parse(parser, ParserTest.ITEMS[:-2]))
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if __name__ == '__main__':
|
| 114 |
+
main()
|
code/train/Python/0064061_accuracytest.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import print_function
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import math
|
| 5 |
+
import string
|
| 6 |
+
import random
|
| 7 |
+
import unittest
|
| 8 |
+
import tempfile
|
| 9 |
+
|
| 10 |
+
import pybloomfilter
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestAccuracyMixin(object):
|
| 14 |
+
FILTER_SIZE = 1000
|
| 15 |
+
|
| 16 |
+
def _gen_random_items(self, n, exclude=None):
|
| 17 |
+
# Yield n unique random items; if an existing set is provided,
|
| 18 |
+
# items already in that set will not be yielded.
|
| 19 |
+
if exclude is not None:
|
| 20 |
+
yielded = exclude
|
| 21 |
+
else:
|
| 22 |
+
yielded = set()
|
| 23 |
+
|
| 24 |
+
yield_count = 0
|
| 25 |
+
while yield_count < n:
|
| 26 |
+
random_item = self._random_item()
|
| 27 |
+
if random_item not in yielded:
|
| 28 |
+
yield random_item
|
| 29 |
+
yielded.add(random_item)
|
| 30 |
+
yield_count += 1
|
| 31 |
+
|
| 32 |
+
def test_false_pos_degredation(self):
|
| 33 |
+
# we'll check 10% to 0.01%
|
| 34 |
+
for error_rate in (0.1, 0.01, 0.001, 0.0001):
|
| 35 |
+
bf = self._bf(error_rate)
|
| 36 |
+
items_in_filter = set(
|
| 37 |
+
self._gen_random_items(bf.capacity))
|
| 38 |
+
|
| 39 |
+
items_in_filter_list = list(items_in_filter)
|
| 40 |
+
n = 0
|
| 41 |
+
chunk_count = 10
|
| 42 |
+
chunk_size = int(math.ceil(float(bf.capacity) / chunk_count))
|
| 43 |
+
print('error_rate = %.4f' % error_rate)
|
| 44 |
+
print(' %6s %9s %s' % ('n', 'false_pos',
|
| 45 |
+
'estimated error_rate'))
|
| 46 |
+
for i in range(chunk_count):
|
| 47 |
+
chunk = items_in_filter_list[i*chunk_size:(i+1)*chunk_size]
|
| 48 |
+
n += len(chunk)
|
| 49 |
+
bf.update(chunk)
|
| 50 |
+
pos_test_count = int(5 * 1.0 / error_rate)
|
| 51 |
+
false_pos = len(list(filter(bf.__contains__,
|
| 52 |
+
self._gen_random_items(
|
| 53 |
+
pos_test_count, items_in_filter))))
|
| 54 |
+
est_error_rate = float(false_pos) / pos_test_count
|
| 55 |
+
print(' %6d %9d %.8f %s' % (
|
| 56 |
+
n, false_pos, est_error_rate,
|
| 57 |
+
'******' if est_error_rate > error_rate else ''))
|
| 58 |
+
|
| 59 |
+
def test_accuracy(self):
|
| 60 |
+
print('\n%14s\t%14s\t%17s' % ('pos_test_count', 'false_pos_rate',
|
| 61 |
+
'error_rate_target'))
|
| 62 |
+
# we'll check 10% to 0.01%
|
| 63 |
+
for error_rate in (0.1, 0.01, 0.001, 0.0001):
|
| 64 |
+
bf = self._bf(error_rate)
|
| 65 |
+
items_in_filter = set(
|
| 66 |
+
self._gen_random_items(bf.capacity))
|
| 67 |
+
bf.update(items_in_filter)
|
| 68 |
+
|
| 69 |
+
# sanity check
|
| 70 |
+
self.assertEqual(bf.capacity, len(items_in_filter))
|
| 71 |
+
|
| 72 |
+
false_neg = len(items_in_filter) - \
|
| 73 |
+
len(list(filter(bf.__contains__, items_in_filter)))
|
| 74 |
+
|
| 75 |
+
pos_test_count = int(10 * (1.0 / error_rate))
|
| 76 |
+
false_pos = len(list(filter(bf.__contains__, self._gen_random_items(
|
| 77 |
+
pos_test_count, items_in_filter))))
|
| 78 |
+
false_pos = 0
|
| 79 |
+
for test in self._gen_random_items(pos_test_count,
|
| 80 |
+
items_in_filter):
|
| 81 |
+
if test in bf:
|
| 82 |
+
false_pos += 1
|
| 83 |
+
|
| 84 |
+
false_pos_rate = float(false_pos) / pos_test_count
|
| 85 |
+
false_neg_rate = float(false_neg) / len(items_in_filter)
|
| 86 |
+
error_rate_target = error_rate * 2 # cut it some slack
|
| 87 |
+
|
| 88 |
+
print('%14d\t%14f\t%17f' % (pos_test_count, false_pos_rate,
|
| 89 |
+
error_rate_target))
|
| 90 |
+
self.assertTrue(
|
| 91 |
+
false_pos_rate <= error_rate_target,
|
| 92 |
+
"false_pos: %r / %r = %r > %r" % (
|
| 93 |
+
false_pos, pos_test_count,
|
| 94 |
+
false_pos / float(pos_test_count), error_rate_target))
|
| 95 |
+
self.assertEqual(false_neg_rate, 0.0,
|
| 96 |
+
"false negative rate is nonzero: %0.6f" %
|
| 97 |
+
(false_neg_rate,))
|
| 98 |
+
del bf
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class StringAccuracyMallocTestCase(unittest.TestCase, TestAccuracyMixin):
|
| 102 |
+
CHARS = string.ascii_letters
|
| 103 |
+
STR_LEN = 10
|
| 104 |
+
|
| 105 |
+
def _random_item(self):
|
| 106 |
+
return ''.join(random.choice(self.CHARS)
|
| 107 |
+
for _ in range(self.STR_LEN))
|
| 108 |
+
|
| 109 |
+
def _bf(self, error_rate):
|
| 110 |
+
return pybloomfilter.BloomFilter(self.FILTER_SIZE, error_rate)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class StringAccuracyMmapTestCase(unittest.TestCase, TestAccuracyMixin):
|
| 114 |
+
CHARS = string.ascii_letters
|
| 115 |
+
STR_LEN = 10
|
| 116 |
+
|
| 117 |
+
def setUp(self):
|
| 118 |
+
self.temp_file = tempfile.NamedTemporaryFile(suffix='.bloom',
|
| 119 |
+
delete=False)
|
| 120 |
+
|
| 121 |
+
def tearDown(self):
|
| 122 |
+
os.unlink(self.temp_file.name)
|
| 123 |
+
|
| 124 |
+
def _random_item(self):
|
| 125 |
+
return ''.join(random.choice(self.CHARS)
|
| 126 |
+
for _ in range(self.STR_LEN))
|
| 127 |
+
|
| 128 |
+
def _bf(self, error_rate):
|
| 129 |
+
return pybloomfilter.BloomFilter(self.FILTER_SIZE, error_rate,
|
| 130 |
+
self.temp_file.name)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class IntegerAccuracyMallocTestCase(unittest.TestCase, TestAccuracyMixin):
|
| 134 |
+
|
| 135 |
+
def _random_item(self):
|
| 136 |
+
return random.randint(-2**31, 2**31)
|
| 137 |
+
|
| 138 |
+
def _bf(self, error_rate):
|
| 139 |
+
return pybloomfilter.BloomFilter(self.FILTER_SIZE, error_rate)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class IntegerAccuracyMmapTestCase(unittest.TestCase, TestAccuracyMixin):
|
| 143 |
+
|
| 144 |
+
def setUp(self):
|
| 145 |
+
self.temp_file = tempfile.NamedTemporaryFile(suffix='.bloom',
|
| 146 |
+
delete=False)
|
| 147 |
+
|
| 148 |
+
def tearDown(self):
|
| 149 |
+
os.unlink(self.temp_file.name)
|
| 150 |
+
|
| 151 |
+
def _random_item(self):
|
| 152 |
+
return random.randint(-2**31, 2**31)
|
| 153 |
+
|
| 154 |
+
def _bf(self, error_rate):
|
| 155 |
+
return pybloomfilter.BloomFilter(self.FILTER_SIZE, error_rate,
|
| 156 |
+
self.temp_file.name)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def suite():
|
| 160 |
+
suite = unittest.TestSuite()
|
| 161 |
+
suite.addTest(unittest.makeSuite(StringAccuracyMmapTestCase))
|
| 162 |
+
suite.addTest(unittest.makeSuite(StringAccuracyMallocTestCase))
|
| 163 |
+
suite.addTest(unittest.makeSuite(IntegerAccuracyMmapTestCase))
|
| 164 |
+
suite.addTest(unittest.makeSuite(IntegerAccuracyMallocTestCase))
|
| 165 |
+
return suite
|
code/train/Python/0065151_list1.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python -tt
|
| 2 |
+
# Copyright 2010 Google Inc.
|
| 3 |
+
# Licensed under the Apache License, Version 2.0
|
| 4 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 5 |
+
|
| 6 |
+
# Google's Python Class
|
| 7 |
+
# http://code.google.com/edu/languages/google-python-class/
|
| 8 |
+
|
| 9 |
+
# Basic list exercises
|
| 10 |
+
# Fill in the code for the functions below. main() is already set up
|
| 11 |
+
# to call the functions with a few different inputs,
|
| 12 |
+
# printing 'OK' when each function is correct.
|
| 13 |
+
# The starter code for each function includes a 'return'
|
| 14 |
+
# which is just a placeholder for your code.
|
| 15 |
+
# It's ok if you do not complete all the functions, and there
|
| 16 |
+
# are some additional functions to try in list2.py.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# A. match_ends
|
| 20 |
+
# Given a list of strings, return the count of the number of
|
| 21 |
+
# strings where the string length is 2 or more and the first
|
| 22 |
+
# and last chars of the string are the same.
|
| 23 |
+
# Note: python does not have a ++ operator, but += works.
|
| 24 |
+
def match_ends(words):
|
| 25 |
+
count = 0
|
| 26 |
+
for word in words:
|
| 27 |
+
if len(word) >= 2 and word[0] == word[-1]:
|
| 28 |
+
count += 1
|
| 29 |
+
return count
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# B. front_x
|
| 33 |
+
# Given a list of strings, return a list with the strings
|
| 34 |
+
# in sorted order, except group all the strings that begin with 'x' first.
|
| 35 |
+
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
|
| 36 |
+
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
|
| 37 |
+
# Hint: this can be done by making 2 lists and sorting each of them
|
| 38 |
+
# before combining them.
|
| 39 |
+
def front_x(words):
|
| 40 |
+
a = []
|
| 41 |
+
x = []
|
| 42 |
+
for word in words:
|
| 43 |
+
if word[0] == "x":
|
| 44 |
+
x.append(word)
|
| 45 |
+
else:
|
| 46 |
+
a.append(word)
|
| 47 |
+
a.sort()
|
| 48 |
+
x.sort()
|
| 49 |
+
return x + a
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# C. sort_last
|
| 53 |
+
# Given a list of non-empty tuples, return a list sorted in increasing
|
| 54 |
+
# order by the last element in each tuple.
|
| 55 |
+
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
|
| 56 |
+
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
|
| 57 |
+
# Hint: use a custom key= function to extract the last element form each tuple.
|
| 58 |
+
def sort_last(tuples):
|
| 59 |
+
def ultimo(tuple):
|
| 60 |
+
return tuple[-1]
|
| 61 |
+
tuples.sort(key=ultimo)
|
| 62 |
+
return tuples
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# Simple provided test() function used in main() to print
|
| 66 |
+
# what each function returns vs. what it's supposed to return.
|
| 67 |
+
def test(got, expected):
|
| 68 |
+
if got == expected:
|
| 69 |
+
prefix = ' OK '
|
| 70 |
+
else:
|
| 71 |
+
prefix = ' X '
|
| 72 |
+
print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# Calls the above functions with interesting inputs.
|
| 76 |
+
def main():
|
| 77 |
+
print('match_ends')
|
| 78 |
+
test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
|
| 79 |
+
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
|
| 80 |
+
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
|
| 81 |
+
|
| 82 |
+
print()
|
| 83 |
+
print('front_x')
|
| 84 |
+
test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
|
| 85 |
+
['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
|
| 86 |
+
test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),
|
| 87 |
+
['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])
|
| 88 |
+
test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),
|
| 89 |
+
['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])
|
| 90 |
+
|
| 91 |
+
print()
|
| 92 |
+
print('sort_last')
|
| 93 |
+
test(sort_last([(1, 3), (3, 2), (2, 1)]),
|
| 94 |
+
[(2, 1), (3, 2), (1, 3)])
|
| 95 |
+
test(sort_last([(2, 3), (1, 2), (3, 1)]),
|
| 96 |
+
[(3, 1), (1, 2), (2, 3)])
|
| 97 |
+
test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
|
| 98 |
+
[(2, 2), (1, 3), (3, 4, 5), (1, 7)])
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == '__main__':
|
| 102 |
+
main()
|
code/train/Python/0065512_course_grade.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CourseGrade Class
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from django.conf import settings
|
| 7 |
+
from lazy import lazy
|
| 8 |
+
from logging import getLogger
|
| 9 |
+
from lms.djangoapps.course_blocks.api import get_course_blocks
|
| 10 |
+
from openedx.core.djangoapps.signals.signals import GRADES_UPDATED
|
| 11 |
+
from xmodule import block_metadata_utils
|
| 12 |
+
|
| 13 |
+
from .subsection_grade import SubsectionGradeFactory
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
log = getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class CourseGrade(object):
|
| 20 |
+
"""
|
| 21 |
+
Course Grade class
|
| 22 |
+
"""
|
| 23 |
+
def __init__(self, student, course, course_structure):
|
| 24 |
+
self.student = student
|
| 25 |
+
self.course = course
|
| 26 |
+
self.course_structure = course_structure
|
| 27 |
+
self.chapter_grades = []
|
| 28 |
+
|
| 29 |
+
@lazy
|
| 30 |
+
def subsection_grade_totals_by_format(self):
|
| 31 |
+
"""
|
| 32 |
+
Returns grades for the subsections in the course in
|
| 33 |
+
a dict keyed by subsection format types.
|
| 34 |
+
"""
|
| 35 |
+
subsections_by_format = defaultdict(list)
|
| 36 |
+
for chapter in self.chapter_grades:
|
| 37 |
+
for subsection_grade in chapter['sections']:
|
| 38 |
+
if subsection_grade.graded:
|
| 39 |
+
graded_total = subsection_grade.graded_total
|
| 40 |
+
if graded_total.possible > 0:
|
| 41 |
+
subsections_by_format[subsection_grade.format].append(graded_total)
|
| 42 |
+
return subsections_by_format
|
| 43 |
+
|
| 44 |
+
@lazy
|
| 45 |
+
def locations_to_weighted_scores(self):
|
| 46 |
+
"""
|
| 47 |
+
Returns a dict of problem scores keyed by their locations.
|
| 48 |
+
"""
|
| 49 |
+
locations_to_weighted_scores = {}
|
| 50 |
+
for chapter in self.chapter_grades:
|
| 51 |
+
for subsection_grade in chapter['sections']:
|
| 52 |
+
locations_to_weighted_scores.update(subsection_grade.locations_to_weighted_scores)
|
| 53 |
+
return locations_to_weighted_scores
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def has_access_to_course(self):
|
| 57 |
+
"""
|
| 58 |
+
Returns whether the course structure as seen by the
|
| 59 |
+
given student is non-empty.
|
| 60 |
+
"""
|
| 61 |
+
return len(self.course_structure) > 0
|
| 62 |
+
|
| 63 |
+
@lazy
|
| 64 |
+
def summary(self):
|
| 65 |
+
"""
|
| 66 |
+
Returns the grade summary as calculated by the course's grader.
|
| 67 |
+
"""
|
| 68 |
+
# Grading policy might be overriden by a CCX, need to reset it
|
| 69 |
+
self.course.set_grading_policy(self.course.grading_policy)
|
| 70 |
+
grade_summary = self.course.grader.grade(
|
| 71 |
+
self.subsection_grade_totals_by_format,
|
| 72 |
+
generate_random_scores=settings.GENERATE_PROFILE_SCORES
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# We round the grade here, to make sure that the grade is a whole percentage and
|
| 76 |
+
# doesn't get displayed differently than it gets grades
|
| 77 |
+
grade_summary['percent'] = round(grade_summary['percent'] * 100 + 0.05) / 100
|
| 78 |
+
grade_summary['grade'] = self._compute_letter_grade(grade_summary['percent'])
|
| 79 |
+
grade_summary['totaled_scores'] = self.subsection_grade_totals_by_format
|
| 80 |
+
grade_summary['raw_scores'] = list(self.locations_to_weighted_scores.itervalues())
|
| 81 |
+
|
| 82 |
+
return grade_summary
|
| 83 |
+
|
| 84 |
+
def compute(self):
|
| 85 |
+
"""
|
| 86 |
+
Computes the grade for the given student and course.
|
| 87 |
+
"""
|
| 88 |
+
subsection_grade_factory = SubsectionGradeFactory(self.student)
|
| 89 |
+
for chapter_key in self.course_structure.get_children(self.course.location):
|
| 90 |
+
chapter = self.course_structure[chapter_key]
|
| 91 |
+
subsection_grades = []
|
| 92 |
+
for subsection_key in self.course_structure.get_children(chapter_key):
|
| 93 |
+
subsection_grades.append(
|
| 94 |
+
subsection_grade_factory.create(
|
| 95 |
+
self.course_structure[subsection_key],
|
| 96 |
+
self.course_structure, self.course
|
| 97 |
+
)
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
self.chapter_grades.append({
|
| 101 |
+
'display_name': block_metadata_utils.display_name_with_default_escaped(chapter),
|
| 102 |
+
'url_name': block_metadata_utils.url_name_for_block(chapter),
|
| 103 |
+
'sections': subsection_grades
|
| 104 |
+
})
|
| 105 |
+
|
| 106 |
+
self._signal_listeners_when_grade_computed()
|
| 107 |
+
|
| 108 |
+
def score_for_module(self, location):
|
| 109 |
+
"""
|
| 110 |
+
Calculate the aggregate weighted score for any location in the course.
|
| 111 |
+
This method returns a tuple containing (earned_score, possible_score).
|
| 112 |
+
|
| 113 |
+
If the location is of 'problem' type, this method will return the
|
| 114 |
+
possible and earned scores for that problem. If the location refers to a
|
| 115 |
+
composite module (a vertical or section ) the scores will be the sums of
|
| 116 |
+
all scored problems that are children of the chosen location.
|
| 117 |
+
"""
|
| 118 |
+
if location in self.locations_to_weighted_scores:
|
| 119 |
+
score = self.locations_to_weighted_scores[location]
|
| 120 |
+
return score.earned, score.possible
|
| 121 |
+
children = self.course_structure.get_children(location)
|
| 122 |
+
earned = 0.0
|
| 123 |
+
possible = 0.0
|
| 124 |
+
for child in children:
|
| 125 |
+
child_earned, child_possible = self.score_for_module(child)
|
| 126 |
+
earned += child_earned
|
| 127 |
+
possible += child_possible
|
| 128 |
+
return earned, possible
|
| 129 |
+
|
| 130 |
+
def _compute_letter_grade(self, percentage):
|
| 131 |
+
"""
|
| 132 |
+
Returns a letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None.
|
| 133 |
+
|
| 134 |
+
Arguments
|
| 135 |
+
- grade_cutoffs is a dictionary mapping a grade to the lowest
|
| 136 |
+
possible percentage to earn that grade.
|
| 137 |
+
- percentage is the final percent across all problems in a course
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
letter_grade = None
|
| 141 |
+
grade_cutoffs = self.course.grade_cutoffs
|
| 142 |
+
|
| 143 |
+
# Possible grades, sorted in descending order of score
|
| 144 |
+
descending_grades = sorted(grade_cutoffs, key=lambda x: grade_cutoffs[x], reverse=True)
|
| 145 |
+
for possible_grade in descending_grades:
|
| 146 |
+
if percentage >= grade_cutoffs[possible_grade]:
|
| 147 |
+
letter_grade = possible_grade
|
| 148 |
+
break
|
| 149 |
+
|
| 150 |
+
return letter_grade
|
| 151 |
+
|
| 152 |
+
def _signal_listeners_when_grade_computed(self):
|
| 153 |
+
"""
|
| 154 |
+
Signal all listeners when grades are computed.
|
| 155 |
+
"""
|
| 156 |
+
responses = GRADES_UPDATED.send_robust(
|
| 157 |
+
sender=None,
|
| 158 |
+
user=self.student,
|
| 159 |
+
grade_summary=self.summary,
|
| 160 |
+
course_key=self.course.id,
|
| 161 |
+
deadline=self.course.end
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
for receiver, response in responses:
|
| 165 |
+
log.info(
|
| 166 |
+
'Signal fired when student grade is calculated. Receiver: %s. Response: %s',
|
| 167 |
+
receiver, response
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class CourseGradeFactory(object):
|
| 172 |
+
"""
|
| 173 |
+
Factory class to create Course Grade objects
|
| 174 |
+
"""
|
| 175 |
+
def __init__(self, student):
|
| 176 |
+
self.student = student
|
| 177 |
+
|
| 178 |
+
def create(self, course):
|
| 179 |
+
"""
|
| 180 |
+
Returns the CourseGrade object for the given student and course.
|
| 181 |
+
"""
|
| 182 |
+
course_structure = get_course_blocks(self.student, course.location)
|
| 183 |
+
return (
|
| 184 |
+
self._get_saved_grade(course, course_structure) or
|
| 185 |
+
self._compute_and_update_grade(course, course_structure)
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def _compute_and_update_grade(self, course, course_structure):
|
| 189 |
+
"""
|
| 190 |
+
Freshly computes and updates the grade for the student and course.
|
| 191 |
+
"""
|
| 192 |
+
course_grade = CourseGrade(self.student, course, course_structure)
|
| 193 |
+
course_grade.compute()
|
| 194 |
+
return course_grade
|
| 195 |
+
|
| 196 |
+
def _get_saved_grade(self, course, course_structure): # pylint: disable=unused-argument
|
| 197 |
+
"""
|
| 198 |
+
Returns the saved grade for the given course and student.
|
| 199 |
+
"""
|
| 200 |
+
if settings.FEATURES.get('ENABLE_SUBSECTION_GRADES_SAVED') and course.enable_subsection_grades_saved:
|
| 201 |
+
# TODO LATER Retrieve the saved grade for the course, if it exists.
|
| 202 |
+
_pretend_to_save_course_grades()
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _pretend_to_save_course_grades():
|
| 206 |
+
"""
|
| 207 |
+
Stub to facilitate testing feature flag until robust grade work lands.
|
| 208 |
+
"""
|
| 209 |
+
pass
|
code/train/Python/0065884_E4.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__author__ = 'shawnmehan'
|
| 2 |
+
|
| 3 |
+
""" two digit products 91*99 = 9009, largest palindrome of such multiples.
|
| 4 |
+
What is largest 3-digits palindrome
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import itertools
|
| 8 |
+
|
| 9 |
+
def get_list(n):
|
| 10 |
+
l = [] # set up output list
|
| 11 |
+
n_string = str(n) # convert number to string
|
| 12 |
+
for c in n_string:
|
| 13 |
+
l.append(c)
|
| 14 |
+
return l
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_reverse_list(l):
|
| 18 |
+
r = [] # set up output list
|
| 19 |
+
for c in range(0,len(l)): # flip the list
|
| 20 |
+
r.append(l[-(c+1)])
|
| 21 |
+
return r
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def is_palindrome(l1, l2):
|
| 25 |
+
if l1 == l2:
|
| 26 |
+
return True
|
| 27 |
+
else:
|
| 28 |
+
return False
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def largest_product():
|
| 32 |
+
max_product = 0
|
| 33 |
+
for i, j in itertools.product(range(1, 100000), range(1, 100000)):
|
| 34 |
+
product = i * j
|
| 35 |
+
if max_product > product: # smaller than what we already found so skip
|
| 36 |
+
continue
|
| 37 |
+
front = get_list(product)
|
| 38 |
+
back = get_reverse_list(front)
|
| 39 |
+
if (is_palindrome(front, back)):
|
| 40 |
+
max_product = product
|
| 41 |
+
return max_product
|
| 42 |
+
|
| 43 |
+
print largest_product()
|
code/train/Python/0066105_pascal_voc.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import division
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from math import ceil, floor
|
| 5 |
+
from xml.dom.minidom import parse
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from skimage.io import imread
|
| 9 |
+
from skimage.transform import rescale
|
| 10 |
+
|
| 11 |
+
from .dataset import Datasets
|
| 12 |
+
from .download import maybe_download_and_extract
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
URL = 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/'\
|
| 16 |
+
'VOCtrainval_11-May-2012.tar'
|
| 17 |
+
CLASSES = [
|
| 18 |
+
'person', 'bird', 'cat', 'cow', 'dog', 'horse', 'sheep', 'aeroplane',
|
| 19 |
+
'bicycle', 'boat', 'bus', 'car', 'motorbike', 'train', 'bottle', 'chair',
|
| 20 |
+
'diningtable', 'pottedplant', 'sofa', 'tvmonitor'
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class PascalVOC(Datasets):
|
| 25 |
+
def __init__(self, data_dir, val_size=1500, fixed_size=None):
|
| 26 |
+
self._fixed_size = fixed_size
|
| 27 |
+
|
| 28 |
+
maybe_download_and_extract(URL, data_dir)
|
| 29 |
+
|
| 30 |
+
data_dir = os.path.join(data_dir, 'VOCdevkit', 'VOC2012')
|
| 31 |
+
names = os.listdir(os.path.join(data_dir, 'Annotations'))
|
| 32 |
+
names = [name.split('.')[0] for name in names]
|
| 33 |
+
names = sorted(names)
|
| 34 |
+
|
| 35 |
+
# PascalVOC didn't release the full test annotations yet, use the
|
| 36 |
+
# validation set instead :(
|
| 37 |
+
train = Dataset(names[val_size:], data_dir, fixed_size)
|
| 38 |
+
val = Dataset(names[:val_size], data_dir, fixed_size)
|
| 39 |
+
test = Dataset(names[:val_size], data_dir, fixed_size)
|
| 40 |
+
|
| 41 |
+
super(PascalVOC, self).__init__(train, val, test)
|
| 42 |
+
|
| 43 |
+
@property
|
| 44 |
+
def classes(self):
|
| 45 |
+
return CLASSES
|
| 46 |
+
|
| 47 |
+
@property
|
| 48 |
+
def width(self):
|
| 49 |
+
return self._fixed_size
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def height(self):
|
| 53 |
+
return self._fixed_size
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def num_channels(self):
|
| 57 |
+
return 3
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Dataset(object):
|
| 61 |
+
def __init__(self, names, data_dir, fixed_size=None):
|
| 62 |
+
self.epochs_completed = 0
|
| 63 |
+
|
| 64 |
+
self._data_dir = data_dir
|
| 65 |
+
self._fixed_size = fixed_size
|
| 66 |
+
self._names = names
|
| 67 |
+
self._index_in_epoch = 0
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def num_examples(self):
|
| 71 |
+
return len(self._names)
|
| 72 |
+
|
| 73 |
+
def _random_shuffle_examples(self):
|
| 74 |
+
perm = np.arange(self.num_examples)
|
| 75 |
+
np.random.shuffle(perm)
|
| 76 |
+
self._names = [self._names[i] for i in perm]
|
| 77 |
+
|
| 78 |
+
def next_batch(self, batch_size, shuffle=True):
|
| 79 |
+
# This code is nearly complete identical to the default next_batch
|
| 80 |
+
# method of the default dataset class, but instead of shuffling the
|
| 81 |
+
# examples in memory, we shuffle just the filenames.
|
| 82 |
+
#
|
| 83 |
+
# Therefore the duplication check of this file is diabled in
|
| 84 |
+
# .codeclimate.yml.
|
| 85 |
+
|
| 86 |
+
start = self._index_in_epoch
|
| 87 |
+
|
| 88 |
+
# Shuffle for the first epoch.
|
| 89 |
+
if self.epochs_completed == 0 and start == 0 and shuffle:
|
| 90 |
+
self._random_shuffle_examples()
|
| 91 |
+
|
| 92 |
+
if start + batch_size > self.num_examples:
|
| 93 |
+
# Finished epoch.
|
| 94 |
+
self.epochs_completed += 1
|
| 95 |
+
|
| 96 |
+
# Get the rest examples in this epoch.
|
| 97 |
+
rest_num_examples = self.num_examples - start
|
| 98 |
+
names_rest = self._names[start:self.num_examples]
|
| 99 |
+
|
| 100 |
+
# Shuffle the examples.
|
| 101 |
+
if shuffle:
|
| 102 |
+
self._random_shuffle_examples()
|
| 103 |
+
|
| 104 |
+
# Start next epoch.
|
| 105 |
+
start = 0
|
| 106 |
+
self._index_in_epoch = batch_size - rest_num_examples
|
| 107 |
+
end = self._index_in_epoch
|
| 108 |
+
names = names_rest + self._names[start:end]
|
| 109 |
+
else:
|
| 110 |
+
# Just slice the examples.
|
| 111 |
+
self._index_in_epoch += batch_size
|
| 112 |
+
end = self._index_in_epoch
|
| 113 |
+
names = self._names[start:end]
|
| 114 |
+
|
| 115 |
+
if self._fixed_size is None:
|
| 116 |
+
images = [self._read_image(name) for name in names]
|
| 117 |
+
else:
|
| 118 |
+
images = np.stack([self._read_image(name) for name in names])
|
| 119 |
+
labels = np.stack([self._read_label(name) for name in names])
|
| 120 |
+
|
| 121 |
+
return images, labels
|
| 122 |
+
|
| 123 |
+
def _read_image(self, name):
|
| 124 |
+
path = os.path.join(self._data_dir, 'JPEGImages',
|
| 125 |
+
'{}.jpg'.format(name))
|
| 126 |
+
image = imread(path)
|
| 127 |
+
|
| 128 |
+
if self._fixed_size is None:
|
| 129 |
+
image = (1 / 255) * image.astype(np.float32)
|
| 130 |
+
return image.astype(np.float32)
|
| 131 |
+
else:
|
| 132 |
+
height, width, _ = image.shape
|
| 133 |
+
|
| 134 |
+
scale_y = self._fixed_size / height
|
| 135 |
+
scale_x = self._fixed_size / width
|
| 136 |
+
scale = min(scale_y, scale_x)
|
| 137 |
+
|
| 138 |
+
image = rescale(image, (scale, scale), mode='constant')
|
| 139 |
+
|
| 140 |
+
pad_y = self._fixed_size - image.shape[0]
|
| 141 |
+
pad_x = self._fixed_size - image.shape[1]
|
| 142 |
+
|
| 143 |
+
image = np.pad(image,
|
| 144 |
+
((int(ceil(pad_y / 2)), int(floor(pad_y / 2))),
|
| 145 |
+
(int(ceil(pad_x / 2)),
|
| 146 |
+
int(floor(pad_x / 2))), (0, 0)), 'constant')
|
| 147 |
+
return image
|
| 148 |
+
|
| 149 |
+
def _read_label(self, name):
|
| 150 |
+
path = os.path.join(self._data_dir, 'Annotations',
|
| 151 |
+
'{}.xml'.format(name))
|
| 152 |
+
annotation = parse(path)
|
| 153 |
+
|
| 154 |
+
label = np.zeros((len(CLASSES)), np.uint8)
|
| 155 |
+
|
| 156 |
+
# Get the label to the greatest bounding box.
|
| 157 |
+
max_area = 0
|
| 158 |
+
max_name = ''
|
| 159 |
+
for obj in annotation.getElementsByTagName('object'):
|
| 160 |
+
name = obj.getElementsByTagName('name')[0].firstChild.nodeValue
|
| 161 |
+
bbox = obj.getElementsByTagName('bndbox')[0]
|
| 162 |
+
xmin = bbox.getElementsByTagName('xmin')[0].firstChild.nodeValue
|
| 163 |
+
xmax = bbox.getElementsByTagName('xmax')[0].firstChild.nodeValue
|
| 164 |
+
ymin = bbox.getElementsByTagName('ymin')[0].firstChild.nodeValue
|
| 165 |
+
ymax = bbox.getElementsByTagName('ymax')[0].firstChild.nodeValue
|
| 166 |
+
area = (float(xmax) - float(xmin)) * (float(ymax) - float(ymin))
|
| 167 |
+
if area > max_area:
|
| 168 |
+
max_area = area
|
| 169 |
+
max_name = name
|
| 170 |
+
|
| 171 |
+
label[CLASSES.index(max_name)] = 1
|
| 172 |
+
|
| 173 |
+
return label
|
code/train/Python/0066263_test_extensions.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# vim: tabstop=4 shiftwidth=4 softtabstop=4
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
|
| 4 |
+
# Copyright 2011 OpenStack LLC.
|
| 5 |
+
# All Rights Reserved.
|
| 6 |
+
#
|
| 7 |
+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
| 8 |
+
# not use this file except in compliance with the License. You may obtain
|
| 9 |
+
# a copy of the License at
|
| 10 |
+
#
|
| 11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 12 |
+
#
|
| 13 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 14 |
+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
| 15 |
+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
| 16 |
+
# License for the specific language governing permissions and limitations
|
| 17 |
+
# under the License.
|
| 18 |
+
|
| 19 |
+
import iso8601
|
| 20 |
+
from lxml import etree
|
| 21 |
+
import webob
|
| 22 |
+
|
| 23 |
+
from manila.api.v1 import router
|
| 24 |
+
from manila.api import xmlutil
|
| 25 |
+
|
| 26 |
+
from manila.openstack.common import jsonutils
|
| 27 |
+
from manila import test
|
| 28 |
+
from oslo.config import cfg
|
| 29 |
+
|
| 30 |
+
CONF = cfg.CONF
|
| 31 |
+
NS = "{http://docs.openstack.org/common/api/v1.0}"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ExtensionTestCase(test.TestCase):
|
| 35 |
+
def setUp(self):
|
| 36 |
+
super(ExtensionTestCase, self).setUp()
|
| 37 |
+
ext_list = CONF.osapi_share_extension[:]
|
| 38 |
+
fox = ('manila.tests.api.extensions.foxinsocks.Foxinsocks')
|
| 39 |
+
if fox not in ext_list:
|
| 40 |
+
ext_list.append(fox)
|
| 41 |
+
self.flags(osapi_share_extension=ext_list)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ExtensionControllerTest(ExtensionTestCase):
|
| 45 |
+
|
| 46 |
+
def setUp(self):
|
| 47 |
+
super(ExtensionControllerTest, self).setUp()
|
| 48 |
+
self.ext_list = []
|
| 49 |
+
self.ext_list.sort()
|
| 50 |
+
|
| 51 |
+
def test_list_extensions_json(self):
|
| 52 |
+
app = router.APIRouter()
|
| 53 |
+
request = webob.Request.blank("/fake/extensions")
|
| 54 |
+
response = request.get_response(app)
|
| 55 |
+
self.assertEqual(200, response.status_int)
|
| 56 |
+
|
| 57 |
+
# Make sure we have all the extensions, extra extensions being OK.
|
| 58 |
+
data = jsonutils.loads(response.body)
|
| 59 |
+
names = [str(x['name']) for x in data['extensions']
|
| 60 |
+
if str(x['name']) in self.ext_list]
|
| 61 |
+
names.sort()
|
| 62 |
+
self.assertEqual(names, self.ext_list)
|
| 63 |
+
|
| 64 |
+
# Ensure all the timestamps are valid according to iso8601
|
| 65 |
+
for ext in data['extensions']:
|
| 66 |
+
iso8601.parse_date(ext['updated'])
|
| 67 |
+
|
| 68 |
+
# Make sure that at least Fox in Sox is correct.
|
| 69 |
+
(fox_ext, ) = [
|
| 70 |
+
x for x in data['extensions'] if x['alias'] == 'FOXNSOX']
|
| 71 |
+
self.assertEqual(
|
| 72 |
+
fox_ext, {'namespace': 'http://www.fox.in.socks/api/ext/pie/v1.0',
|
| 73 |
+
'name': 'Fox In Socks',
|
| 74 |
+
'updated': '2011-01-22T13:25:27-06:00',
|
| 75 |
+
'description': 'The Fox In Socks Extension',
|
| 76 |
+
'alias': 'FOXNSOX',
|
| 77 |
+
'links': []}, )
|
| 78 |
+
|
| 79 |
+
for ext in data['extensions']:
|
| 80 |
+
url = '/fake/extensions/%s' % ext['alias']
|
| 81 |
+
request = webob.Request.blank(url)
|
| 82 |
+
response = request.get_response(app)
|
| 83 |
+
output = jsonutils.loads(response.body)
|
| 84 |
+
self.assertEqual(output['extension']['alias'], ext['alias'])
|
| 85 |
+
|
| 86 |
+
def test_get_extension_json(self):
|
| 87 |
+
app = router.APIRouter()
|
| 88 |
+
request = webob.Request.blank("/fake/extensions/FOXNSOX")
|
| 89 |
+
response = request.get_response(app)
|
| 90 |
+
self.assertEqual(200, response.status_int)
|
| 91 |
+
|
| 92 |
+
data = jsonutils.loads(response.body)
|
| 93 |
+
self.assertEqual(
|
| 94 |
+
data['extension'],
|
| 95 |
+
{"namespace": "http://www.fox.in.socks/api/ext/pie/v1.0",
|
| 96 |
+
"name": "Fox In Socks",
|
| 97 |
+
"updated": "2011-01-22T13:25:27-06:00",
|
| 98 |
+
"description": "The Fox In Socks Extension",
|
| 99 |
+
"alias": "FOXNSOX",
|
| 100 |
+
"links": []})
|
| 101 |
+
|
| 102 |
+
def test_get_non_existing_extension_json(self):
|
| 103 |
+
app = router.APIRouter()
|
| 104 |
+
request = webob.Request.blank("/fake/extensions/4")
|
| 105 |
+
response = request.get_response(app)
|
| 106 |
+
self.assertEqual(404, response.status_int)
|
| 107 |
+
|
| 108 |
+
def test_list_extensions_xml(self):
|
| 109 |
+
app = router.APIRouter()
|
| 110 |
+
request = webob.Request.blank("/fake/extensions")
|
| 111 |
+
request.accept = "application/xml"
|
| 112 |
+
response = request.get_response(app)
|
| 113 |
+
self.assertEqual(200, response.status_int)
|
| 114 |
+
|
| 115 |
+
root = etree.XML(response.body)
|
| 116 |
+
self.assertEqual(root.tag.split('extensions')[0], NS)
|
| 117 |
+
|
| 118 |
+
# Make sure we have all the extensions, extras extensions being OK.
|
| 119 |
+
exts = root.findall('{0}extension'.format(NS))
|
| 120 |
+
self.assert_(len(exts) >= len(self.ext_list))
|
| 121 |
+
|
| 122 |
+
# Make sure that at least Fox in Sox is correct.
|
| 123 |
+
(fox_ext, ) = [x for x in exts if x.get('alias') == 'FOXNSOX']
|
| 124 |
+
self.assertEqual(fox_ext.get('name'), 'Fox In Socks')
|
| 125 |
+
self.assertEqual(
|
| 126 |
+
fox_ext.get('namespace'),
|
| 127 |
+
'http://www.fox.in.socks/api/ext/pie/v1.0')
|
| 128 |
+
self.assertEqual(fox_ext.get('updated'), '2011-01-22T13:25:27-06:00')
|
| 129 |
+
self.assertEqual(
|
| 130 |
+
fox_ext.findtext('{0}description'.format(NS)),
|
| 131 |
+
'The Fox In Socks Extension')
|
| 132 |
+
|
| 133 |
+
xmlutil.validate_schema(root, 'extensions')
|
| 134 |
+
|
| 135 |
+
def test_get_extension_xml(self):
|
| 136 |
+
app = router.APIRouter()
|
| 137 |
+
request = webob.Request.blank("/fake/extensions/FOXNSOX")
|
| 138 |
+
request.accept = "application/xml"
|
| 139 |
+
response = request.get_response(app)
|
| 140 |
+
self.assertEqual(200, response.status_int)
|
| 141 |
+
xml = response.body
|
| 142 |
+
|
| 143 |
+
root = etree.XML(xml)
|
| 144 |
+
self.assertEqual(root.tag.split('extension')[0], NS)
|
| 145 |
+
self.assertEqual(root.get('alias'), 'FOXNSOX')
|
| 146 |
+
self.assertEqual(root.get('name'), 'Fox In Socks')
|
| 147 |
+
self.assertEqual(
|
| 148 |
+
root.get('namespace'),
|
| 149 |
+
'http://www.fox.in.socks/api/ext/pie/v1.0')
|
| 150 |
+
self.assertEqual(root.get('updated'), '2011-01-22T13:25:27-06:00')
|
| 151 |
+
self.assertEqual(
|
| 152 |
+
root.findtext('{0}description'.format(NS)),
|
| 153 |
+
'The Fox In Socks Extension')
|
| 154 |
+
|
| 155 |
+
xmlutil.validate_schema(root, 'extension')
|
code/train/Python/0068007_utils.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import sqrt
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def eigh(a, tol=1.0e-9):
|
| 5 |
+
"""
|
| 6 |
+
Calculates the eigenValues and vectors using jacobi method.
|
| 7 |
+
Code configured without numpy from http://goo.gl/U3m7nX
|
| 8 |
+
|
| 9 |
+
Returns:
|
| 10 |
+
(list of 3 floats) EigenValues
|
| 11 |
+
(3x3 list of floats) EigenVectors
|
| 12 |
+
|
| 13 |
+
Raises:
|
| 14 |
+
None
|
| 15 |
+
"""
|
| 16 |
+
# Find largest off-diag. element a[k][l]
|
| 17 |
+
def maxElem(a):
|
| 18 |
+
n = len(a)
|
| 19 |
+
aMax = 0.0
|
| 20 |
+
for i in range(n - 1):
|
| 21 |
+
for j in range(i + 1, n):
|
| 22 |
+
if abs(a[i][j]) >= aMax:
|
| 23 |
+
aMax = abs(a[i][j])
|
| 24 |
+
k = i
|
| 25 |
+
l = j
|
| 26 |
+
return aMax, k, l
|
| 27 |
+
|
| 28 |
+
# Rotate to make a[k][l] = 0
|
| 29 |
+
def rotate(a, p, k, l):
|
| 30 |
+
n = len(a)
|
| 31 |
+
aDiff = a[l][l] - a[k][k]
|
| 32 |
+
if abs(a[k][l]) < abs(aDiff) * 1.0e-36:
|
| 33 |
+
t = a[k][l] / aDiff
|
| 34 |
+
else:
|
| 35 |
+
phi = aDiff / (2.0 * a[k][l])
|
| 36 |
+
t = 1.0 / (abs(phi) + sqrt(phi ** 2 + 1.0))
|
| 37 |
+
if phi < 0.0:
|
| 38 |
+
t = -t
|
| 39 |
+
c = 1.0 / sqrt(t ** 2 + 1.0)
|
| 40 |
+
s = t * c
|
| 41 |
+
tau = s / (1.0 + c)
|
| 42 |
+
temp = a[k][l]
|
| 43 |
+
a[k][l] = 0.0
|
| 44 |
+
a[k][k] = a[k][k] - t * temp
|
| 45 |
+
a[l][l] = a[l][l] + t * temp
|
| 46 |
+
for i in range(k): # Case of i < k
|
| 47 |
+
temp = a[i][k]
|
| 48 |
+
a[i][k] = temp - s * (a[i][l] + tau * temp)
|
| 49 |
+
a[i][l] = a[i][l] + s * (temp - tau * a[i][l])
|
| 50 |
+
for i in range(k + 1, l): # Case of k < i < l
|
| 51 |
+
temp = a[k][i]
|
| 52 |
+
a[k][i] = temp - s * (a[i][l] + tau * a[k][i])
|
| 53 |
+
a[i][l] = a[i][l] + s * (temp - tau * a[i][l])
|
| 54 |
+
for i in range(l + 1, n): # Case of i > l
|
| 55 |
+
temp = a[k][i]
|
| 56 |
+
a[k][i] = temp - s * (a[l][i] + tau * temp)
|
| 57 |
+
a[l][i] = a[l][i] + s * (temp - tau * a[l][i])
|
| 58 |
+
for i in range(n): # Update transformation matrix
|
| 59 |
+
temp = p[i][k]
|
| 60 |
+
p[i][k] = temp - s * (p[i][l] + tau * p[i][k])
|
| 61 |
+
p[i][l] = p[i][l] + s * (temp - tau * p[i][l])
|
| 62 |
+
|
| 63 |
+
# Set limit on number of rotations
|
| 64 |
+
n = len(a)
|
| 65 |
+
maxRot = 5 * (n ** 2)
|
| 66 |
+
|
| 67 |
+
p = [[1.0, 0.0, 0.0],
|
| 68 |
+
[0.0, 1.0, 0.0],
|
| 69 |
+
[0.0, 0.0, 1.0]]
|
| 70 |
+
|
| 71 |
+
# Jacobi rotation loop
|
| 72 |
+
for i in range(maxRot):
|
| 73 |
+
|
| 74 |
+
aMax, k, l = maxElem(a)
|
| 75 |
+
|
| 76 |
+
if aMax < tol:
|
| 77 |
+
return [a[i][i] for i in range(len(a))], p
|
| 78 |
+
|
| 79 |
+
rotate(a, p, k, l)
|
code/train/Python/0068360_462._Minimum_Moves_to_Equal_Array_Elements_II.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class Solution(object):
|
| 2 |
+
def step(self, pre_sums, nums, x):
|
| 3 |
+
from bisect import bisect_left, bisect_right
|
| 4 |
+
ret = 0
|
| 5 |
+
left_pos = bisect_left(nums, x)
|
| 6 |
+
if left_pos > 0:
|
| 7 |
+
ret += x * (left_pos) - pre_sums[left_pos-1]
|
| 8 |
+
right_pos = bisect_right(nums, x)
|
| 9 |
+
if right_pos > 0 and right_pos < len(nums):
|
| 10 |
+
ret += pre_sums[-1] - pre_sums[right_pos-1] - x * (len(nums)-right_pos)
|
| 11 |
+
# print pre_sums, nums, x, ret
|
| 12 |
+
return ret
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def minMoves2(self, nums):
|
| 16 |
+
"""
|
| 17 |
+
:type nums: List[int]
|
| 18 |
+
:rtype: int
|
| 19 |
+
"""
|
| 20 |
+
nums = sorted(nums)
|
| 21 |
+
pre_sums = [nums[0]]
|
| 22 |
+
for i in nums[1:]:
|
| 23 |
+
pre_sums.append(pre_sums[-1]+i)
|
| 24 |
+
l, r = nums[0], nums[-1]+1
|
| 25 |
+
ret = 1e9
|
| 26 |
+
while l < r:
|
| 27 |
+
mid = (l+r) / 2
|
| 28 |
+
mid_val = self.step(pre_sums, nums, mid)
|
| 29 |
+
ret = min(ret, mid_val)
|
| 30 |
+
right_val = self.step(pre_sums, nums, mid+1)
|
| 31 |
+
if mid_val == right_val:
|
| 32 |
+
return mid_val
|
| 33 |
+
elif mid_val < right_val:
|
| 34 |
+
r = mid
|
| 35 |
+
else:
|
| 36 |
+
l = mid+1
|
| 37 |
+
return ret
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
print Solution().minMoves2([1,1,1,2,2,3])
|
code/train/Python/0069275_flotilla.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
==============
|
| 3 |
+
FlotillaClient
|
| 4 |
+
==============
|
| 5 |
+
|
| 6 |
+
This is the core Python code for connecting to, processing input from, and
|
| 7 |
+
sending messages to the Flotilla itself.
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
from serial import SerialException
|
| 13 |
+
|
| 14 |
+
from twisted.internet import defer
|
| 15 |
+
from twisted.internet.serialport import SerialPort
|
| 16 |
+
from twisted.protocols.basic import LineReceiver
|
| 17 |
+
|
| 18 |
+
from .hardware import Colour
|
| 19 |
+
from .hardware import Dial
|
| 20 |
+
from .hardware import Joystick
|
| 21 |
+
from .hardware import Light
|
| 22 |
+
from .hardware import Matrix
|
| 23 |
+
from .hardware import Motion
|
| 24 |
+
from .hardware import Motor
|
| 25 |
+
from .hardware import Number
|
| 26 |
+
from .hardware import Rainbow
|
| 27 |
+
from .hardware import Slider
|
| 28 |
+
from .hardware import Touch
|
| 29 |
+
from .hardware import Weather
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class FlotillaClient(LineReceiver):
|
| 33 |
+
|
| 34 |
+
MODULES = {'matrix': Matrix,
|
| 35 |
+
'number': Number,
|
| 36 |
+
'rainbow': Rainbow,
|
| 37 |
+
'motor': Motor,
|
| 38 |
+
'touch': Touch,
|
| 39 |
+
'dial': Dial,
|
| 40 |
+
'slider': Slider,
|
| 41 |
+
'joystick': Joystick,
|
| 42 |
+
'motion': Motion,
|
| 43 |
+
'light': Light,
|
| 44 |
+
'colour': Colour,
|
| 45 |
+
'weather': Weather,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
def _resetModules(self):
|
| 49 |
+
self.modules = { x: None for x in range(1, 9) }
|
| 50 |
+
|
| 51 |
+
def run(self, project, reactor):
|
| 52 |
+
self.project = project
|
| 53 |
+
self.reactor = reactor
|
| 54 |
+
self._ready = False
|
| 55 |
+
self._connected = False
|
| 56 |
+
flotilla_port = self.project._flotilla_port
|
| 57 |
+
baudrate = self.project._baudrate
|
| 58 |
+
try:
|
| 59 |
+
SerialPort(self, flotilla_port, reactor, baudrate)
|
| 60 |
+
except SerialException as e:
|
| 61 |
+
if not hasattr(self, '_count'):
|
| 62 |
+
self._count = 0
|
| 63 |
+
print("Trying to connect to Flotilla. This may take up to 30 seconds")
|
| 64 |
+
self._count += 1
|
| 65 |
+
if self._count <= 30:
|
| 66 |
+
if self._count % 5 == 0:
|
| 67 |
+
print("Trying... {} seconds".format(self._count))
|
| 68 |
+
def runner(arg):
|
| 69 |
+
self.run(project, reactor)
|
| 70 |
+
d = defer.Deferred()
|
| 71 |
+
d.addCallback(runner)
|
| 72 |
+
reactor.callLater(1, d.callback, None)
|
| 73 |
+
return defer.waitForDeferred(d)
|
| 74 |
+
else:
|
| 75 |
+
# It took more than 30 seconds (I've never seen this)
|
| 76 |
+
raise e
|
| 77 |
+
|
| 78 |
+
def connectionLost(self, reason):
|
| 79 |
+
self._resetModules()
|
| 80 |
+
print('Flotilla is disconnected.')
|
| 81 |
+
|
| 82 |
+
@defer.deferredGenerator
|
| 83 |
+
def connectionMade(self):
|
| 84 |
+
self._resetModules()
|
| 85 |
+
self._lines = []
|
| 86 |
+
print('Flotilla is connected.')
|
| 87 |
+
self.flotillaCommand(b'v')
|
| 88 |
+
def check(arg):
|
| 89 |
+
self.flotillaCommand(b'v')
|
| 90 |
+
while not self._ready:
|
| 91 |
+
d = defer.Deferred()
|
| 92 |
+
d.addCallback(check)
|
| 93 |
+
self.reactor.callLater(1, d.callback, None)
|
| 94 |
+
wfd = defer.waitForDeferred(d)
|
| 95 |
+
yield wfd
|
| 96 |
+
|
| 97 |
+
def flotillaCommand(self, cmd):
|
| 98 |
+
self.delimiter = b'\r'
|
| 99 |
+
self.sendLine(cmd)
|
| 100 |
+
self.delimiter = b'\r\n'
|
| 101 |
+
|
| 102 |
+
def handle_hash(self, line):
|
| 103 |
+
|
| 104 |
+
self.project.log("INFO", line)
|
| 105 |
+
|
| 106 |
+
if self._ready:
|
| 107 |
+
# We are all good. No action required.
|
| 108 |
+
return
|
| 109 |
+
|
| 110 |
+
if line.startswith(b'# Flotilla'):
|
| 111 |
+
# Occasional case where the first line gets missed off the first
|
| 112 |
+
# time, so reset.
|
| 113 |
+
self._lines = []
|
| 114 |
+
|
| 115 |
+
self._lines.append(line)
|
| 116 |
+
|
| 117 |
+
if len(self._lines) == 5 and not self._connected:
|
| 118 |
+
# We have issued our first b'v'
|
| 119 |
+
ready = [False, False, False, False, False,]
|
| 120 |
+
starts = [b'# Flotilla', b'# Version', b'# Serial', b'# User', b'# Dock',]
|
| 121 |
+
for i in range(5):
|
| 122 |
+
ready[i] = self._lines[i].startswith(starts[i])
|
| 123 |
+
if all(ready):
|
| 124 |
+
self._connected = True
|
| 125 |
+
self._lines = []
|
| 126 |
+
self.flotillaCommand(b'd')
|
| 127 |
+
|
| 128 |
+
if len(self._lines) == 11 and not self._ready:
|
| 129 |
+
# We're connected, and have issued a b'd'
|
| 130 |
+
ready = [False,] * 11
|
| 131 |
+
starts = [b'# SRAM', b'# Loop', b'# Channels', b'# - 0', b'# - 1',
|
| 132 |
+
b'# - 2', b'# - 3', b'# - 4', b'# - 5', b'# - 6', b'# - 7',]
|
| 133 |
+
for i in range(11):
|
| 134 |
+
ready[i] = self._lines[i].startswith(starts[i])
|
| 135 |
+
if all(ready):
|
| 136 |
+
self._ready = True
|
| 137 |
+
self._lines = []
|
| 138 |
+
self.project.connectModules()
|
| 139 |
+
self.flotillaCommand(b'e')
|
| 140 |
+
|
| 141 |
+
def handle_C(self, channel, module):
|
| 142 |
+
print("Found a {} on channel {}".format(module, channel))
|
| 143 |
+
new_module = self.MODULES[module](self, channel)
|
| 144 |
+
self.modules[channel] = new_module
|
| 145 |
+
self.project.connect()
|
| 146 |
+
|
| 147 |
+
def handle_D(self, channel, module):
|
| 148 |
+
self.modules[channel] = None
|
| 149 |
+
# TODO we should send a message to the project that a new module
|
| 150 |
+
# has been deleted
|
| 151 |
+
|
| 152 |
+
def handle_U(self, channel, module, data):
|
| 153 |
+
if self.modules[channel] is None:
|
| 154 |
+
# It's possible to get input from a hardware module before
|
| 155 |
+
# everything is connected up. Ignore it until we're ready
|
| 156 |
+
# Rather than using ``self._ready`` we check for ``None`` to avoid
|
| 157 |
+
# any unhandled exceptions.
|
| 158 |
+
return
|
| 159 |
+
j = self.modules[channel].change(data)
|
| 160 |
+
|
| 161 |
+
def message(self, data):
|
| 162 |
+
self.project.message(data)
|
| 163 |
+
|
| 164 |
+
def connectedModules(self, type_=None):
|
| 165 |
+
if type_ is None:
|
| 166 |
+
return self.modules.values()
|
| 167 |
+
return [ m for m in self.modules.values() if m is not None and m.module == type_ ]
|
| 168 |
+
|
| 169 |
+
def firstOf(self, type_):
|
| 170 |
+
modules = self.connectedModules(type_)
|
| 171 |
+
if len(modules) == 0:
|
| 172 |
+
return None
|
| 173 |
+
l = [ (m.channel, m) for m in modules ]
|
| 174 |
+
l.sort()
|
| 175 |
+
return l[0][1]
|
| 176 |
+
|
| 177 |
+
def lineReceived(self, line):
|
| 178 |
+
parts = line.split(b" ")
|
| 179 |
+
cmd = parts[0]
|
| 180 |
+
if cmd == b'#':
|
| 181 |
+
self.handle_hash(line)
|
| 182 |
+
return
|
| 183 |
+
try:
|
| 184 |
+
channel, module = parts[1].decode('ascii').split('/')
|
| 185 |
+
except IndexError as e:
|
| 186 |
+
# Sometimes, if the Flotilla is particularly overloaded, we get
|
| 187 |
+
# malformed lines. Ignore them.
|
| 188 |
+
print(line)
|
| 189 |
+
return
|
| 190 |
+
channel = int(channel)
|
| 191 |
+
if cmd == b'c':
|
| 192 |
+
self.handle_C(channel, module)
|
| 193 |
+
return
|
| 194 |
+
if cmd == b'd':
|
| 195 |
+
self.handle_D(channel, module)
|
| 196 |
+
return
|
| 197 |
+
if cmd == b'u':
|
| 198 |
+
data = parts[2]
|
| 199 |
+
self.handle_U(channel, module, data)
|
| 200 |
+
return
|
| 201 |
+
|
code/train/Python/0069309_dsatur.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
@author: Dallas Fraser
|
| 3 |
+
@id: 20652186
|
| 4 |
+
@class: CS686
|
| 5 |
+
@date: 2016-04-05
|
| 6 |
+
@note: coloring_aux with a greedy algorithm
|
| 7 |
+
'''
|
| 8 |
+
import logging
|
| 9 |
+
from inducer.graph import available_color,\
|
| 10 |
+
color_vertex,\
|
| 11 |
+
copy_graph,\
|
| 12 |
+
chromatic_number,\
|
| 13 |
+
is_colored, get_color
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def inducer_coloring(G):
|
| 17 |
+
(H, chromatic) = coloring(G)
|
| 18 |
+
colors = [[] for __ in range(0, chromatic)]
|
| 19 |
+
for node in H.nodes():
|
| 20 |
+
colors[get_color(H, node)].append(node)
|
| 21 |
+
return colors
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def coloring(G, logger=None):
|
| 25 |
+
"""Returns a coloring and chromatic number"""
|
| 26 |
+
if logger is None:
|
| 27 |
+
logging.basicConfig(level=logging.DEBUG,
|
| 28 |
+
format='%(asctime)s %(message)s')
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
H = dsatur(G, logger)
|
| 31 |
+
return (H, chromatic_number(H))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def dsatur(G, logger):
|
| 35 |
+
"""Returns a coloring using dsatur
|
| 36 |
+
|
| 37 |
+
Parameters:
|
| 38 |
+
G: the graph to color (networkx)
|
| 39 |
+
logger: the logger to use
|
| 40 |
+
Returns:
|
| 41 |
+
H: a colored copy of the G (networkx)
|
| 42 |
+
Note:
|
| 43 |
+
used the networkx implementaiton as a starting base but made changes
|
| 44 |
+
"""
|
| 45 |
+
H = copy_graph(G)
|
| 46 |
+
len_g = len(H)
|
| 47 |
+
no_colored = 0
|
| 48 |
+
distinct_colors = {}
|
| 49 |
+
for node in H.nodes():
|
| 50 |
+
distinct_colors[node] = set()
|
| 51 |
+
while no_colored != len_g:
|
| 52 |
+
if no_colored == 0:
|
| 53 |
+
# When sat. for all nodes is 0, yield the node with highest degree
|
| 54 |
+
node = max([x for x in H.nodes()],
|
| 55 |
+
key=lambda x: len(list(H.neighbors(x))))
|
| 56 |
+
else:
|
| 57 |
+
# want the vertex with the highest saturation
|
| 58 |
+
highest_saturation = -1
|
| 59 |
+
highest_saturation_nodes = []
|
| 60 |
+
for node, distinct in distinct_colors.items():
|
| 61 |
+
# If the node is not already colored
|
| 62 |
+
if not is_colored(H, node):
|
| 63 |
+
saturation = len(distinct)
|
| 64 |
+
if saturation > highest_saturation:
|
| 65 |
+
highest_saturation = saturation
|
| 66 |
+
highest_saturation_nodes = [node]
|
| 67 |
+
elif saturation == highest_saturation:
|
| 68 |
+
highest_saturation_nodes.append(node)
|
| 69 |
+
if len(highest_saturation_nodes) == 1:
|
| 70 |
+
node = highest_saturation_nodes[0]
|
| 71 |
+
else:
|
| 72 |
+
# Return the node with highest degree
|
| 73 |
+
max_node = max([x for x in highest_saturation_nodes],
|
| 74 |
+
key=lambda x: len(list(H.neighbors(x))))
|
| 75 |
+
node = max_node
|
| 76 |
+
color = 0
|
| 77 |
+
# find some color can use for it
|
| 78 |
+
while not available_color(H, node, color):
|
| 79 |
+
color += 1
|
| 80 |
+
# color the vertex
|
| 81 |
+
color_vertex(H, node, color)
|
| 82 |
+
logger.debug("Colored {} to {}".format(node, color))
|
| 83 |
+
no_colored += 1
|
| 84 |
+
# tells it neighbors what is up
|
| 85 |
+
for neighbour in H.neighbors(node):
|
| 86 |
+
distinct_colors[neighbour].add(color)
|
| 87 |
+
return H
|
code/train/Python/0070347_config.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: UTF-8 -*-
|
| 2 |
+
# Copyright 2009-2017 Luc Saffre
|
| 3 |
+
# License: BSD (see file COPYING for details)
|
| 4 |
+
|
| 5 |
+
"""This defines the :class:`ConfigDirCache` which Lino instantiates
|
| 6 |
+
and installs as :attr:`SITE.confdirs
|
| 7 |
+
<lino.core.site.Site.confdirs>`.
|
| 8 |
+
|
| 9 |
+
It creates a list `config_dirs` of all configuration directories by
|
| 10 |
+
looping through :attr:`lino.core.site.Site.installed_plugins` and taking those
|
| 11 |
+
whose source directory has a :xfile:`config` subdir.
|
| 12 |
+
|
| 13 |
+
The mechanism in this module emulates the behaviour of Django's and
|
| 14 |
+
Jinja's template loaders.
|
| 15 |
+
|
| 16 |
+
We cannot use the Jinja loader because Jinja's `get_template` method
|
| 17 |
+
returns a `Template`, and Jinja templates don't know their filename.
|
| 18 |
+
One possibility might be to write a special Jinja Template class...
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import unicode_literals
|
| 23 |
+
from builtins import object
|
| 24 |
+
|
| 25 |
+
import logging
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
import os
|
| 29 |
+
from os.path import join, abspath, dirname, isdir
|
| 30 |
+
import sys
|
| 31 |
+
import codecs
|
| 32 |
+
from fnmatch import fnmatch
|
| 33 |
+
import six
|
| 34 |
+
|
| 35 |
+
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
|
| 36 |
+
|
| 37 |
+
from lino.utils import iif
|
| 38 |
+
|
| 39 |
+
SUBDIR_NAME = 'config' # we might change this to "templates"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class ConfigDir(object):
|
| 43 |
+
|
| 44 |
+
"""A directory that may contain configuration files.
|
| 45 |
+
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(self, name, writeable):
|
| 49 |
+
self.name = abspath(name)
|
| 50 |
+
self.writeable = writeable
|
| 51 |
+
|
| 52 |
+
def __repr__(self):
|
| 53 |
+
return "ConfigDir %s" % self.name + iif(
|
| 54 |
+
self.writeable, " (writeable)", "")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class ConfigDirCache(object):
|
| 58 |
+
_init = False
|
| 59 |
+
|
| 60 |
+
def __init__(self, site):
|
| 61 |
+
if self._init:
|
| 62 |
+
raise Exception("Oops, ConfigDirCache was already instantiated!")
|
| 63 |
+
self._init = True
|
| 64 |
+
self.site = site
|
| 65 |
+
self.scan_config_dirs()
|
| 66 |
+
|
| 67 |
+
def scan_config_dirs(self):
|
| 68 |
+
"""Scan the file system and populate :attr:`config_dirs`."""
|
| 69 |
+
config_dirs = []
|
| 70 |
+
|
| 71 |
+
for pth in self.site.get_settings_subdirs(SUBDIR_NAME):
|
| 72 |
+
if six.PY2:
|
| 73 |
+
pth = pth.decode(fs_encoding)
|
| 74 |
+
config_dirs.append(ConfigDir(pth, False))
|
| 75 |
+
|
| 76 |
+
def add_config_dir(name, mod):
|
| 77 |
+
pth = join(dirname(mod.__file__), SUBDIR_NAME)
|
| 78 |
+
if isdir(pth):
|
| 79 |
+
# logger.info("add_config_dir %s %s", name, pth)
|
| 80 |
+
# config_dirs.append(ConfigDir(pth.decode(fs_encoding), False))
|
| 81 |
+
config_dirs.append(ConfigDir(pth, False))
|
| 82 |
+
|
| 83 |
+
self.site.for_each_app(add_config_dir)
|
| 84 |
+
|
| 85 |
+
self.LOCAL_CONFIG_DIR = None
|
| 86 |
+
|
| 87 |
+
p = self.site.cache_dir.child(SUBDIR_NAME)
|
| 88 |
+
if isdir(p):
|
| 89 |
+
self.LOCAL_CONFIG_DIR = ConfigDir(p, True)
|
| 90 |
+
config_dirs.append(self.LOCAL_CONFIG_DIR)
|
| 91 |
+
|
| 92 |
+
config_dirs.reverse()
|
| 93 |
+
self.config_dirs = tuple(config_dirs)
|
| 94 |
+
|
| 95 |
+
# logger.info('config_dirs:\n%s', '\n'.join([
|
| 96 |
+
# repr(cd) for cd in config_dirs]))
|
| 97 |
+
|
| 98 |
+
def find_config_file(self, fn, *groups):
|
| 99 |
+
"""
|
| 100 |
+
Return the full path of the first occurence within the
|
| 101 |
+
:class:`lino.utils.config.ConfigDirCache` of a file named
|
| 102 |
+
`filename`
|
| 103 |
+
|
| 104 |
+
"""
|
| 105 |
+
if os.path.isabs(fn):
|
| 106 |
+
return fn
|
| 107 |
+
if len(groups) == 0:
|
| 108 |
+
groups = ['']
|
| 109 |
+
for group in groups:
|
| 110 |
+
if group:
|
| 111 |
+
prefix = join(*(group.split('/')))
|
| 112 |
+
else:
|
| 113 |
+
prefix = ''
|
| 114 |
+
for cd in self.config_dirs:
|
| 115 |
+
ffn = join(cd.name, prefix, fn)
|
| 116 |
+
if os.path.exists(ffn):
|
| 117 |
+
return ffn
|
| 118 |
+
|
| 119 |
+
def find_config_files(self, pattern, *groups):
|
| 120 |
+
"""
|
| 121 |
+
Returns a dict of `filename` -> `config_dir` entries for each config
|
| 122 |
+
file on this site that matches the pattern. Loops through
|
| 123 |
+
`config_dirs` and collects matching files. When a filename is
|
| 124 |
+
provided by more than one app, then the latest app gets it.
|
| 125 |
+
|
| 126 |
+
`groups` is a tuple of strings, e.g. '', 'foo', 'foo/bar', ...
|
| 127 |
+
|
| 128 |
+
"""
|
| 129 |
+
files = {}
|
| 130 |
+
for group in groups:
|
| 131 |
+
if group:
|
| 132 |
+
prefix = os.path.sep + join(*(group.split('/')))
|
| 133 |
+
else:
|
| 134 |
+
prefix = ''
|
| 135 |
+
for cd in self.config_dirs:
|
| 136 |
+
pth = cd.name + prefix
|
| 137 |
+
if isdir(pth):
|
| 138 |
+
for fn in os.listdir(pth):
|
| 139 |
+
if fnmatch(fn, pattern):
|
| 140 |
+
files.setdefault(fn, cd)
|
| 141 |
+
return files
|
| 142 |
+
|
| 143 |
+
def find_template_config_files(self, template_ext, *groups):
|
| 144 |
+
"""
|
| 145 |
+
Like :func:`find_config_files`, but ignore babel variants:
|
| 146 |
+
e.g. ignore "foo_fr.html" if "foo.html" exists.
|
| 147 |
+
Note: but don't ignore "my_template.html"
|
| 148 |
+
"""
|
| 149 |
+
files = self.find_config_files('*' + template_ext, *groups)
|
| 150 |
+
l = []
|
| 151 |
+
template_ext
|
| 152 |
+
for name in list(files.keys()):
|
| 153 |
+
basename = name[:-len(template_ext)]
|
| 154 |
+
chunks = basename.split('_')
|
| 155 |
+
if len(chunks) > 1:
|
| 156 |
+
basename = '_'.join(chunks[:-1])
|
| 157 |
+
if basename + template_ext in files:
|
| 158 |
+
continue
|
| 159 |
+
l.append(name)
|
| 160 |
+
l.sort()
|
| 161 |
+
if not l:
|
| 162 |
+
logger.warning(
|
| 163 |
+
"find_template_config_files() : no matches for (%r, %r)",
|
| 164 |
+
'*' + template_ext, groups)
|
| 165 |
+
return l
|
| 166 |
+
|
| 167 |
+
def load_config_files(self, loader, pattern, *groups):
|
| 168 |
+
"""
|
| 169 |
+
Currently not used.
|
| 170 |
+
Naming conventions for :xfile:`*.dtl` files are:
|
| 171 |
+
|
| 172 |
+
- the first detail is called appname.Model.dtl
|
| 173 |
+
- If there are more Details, then they are called
|
| 174 |
+
appname.Model.2.dtl, appname.Model.3.dtl etc.
|
| 175 |
+
|
| 176 |
+
The `sort()` below must remove the filename extension (".dtl")
|
| 177 |
+
because otherwise the frist Detail would come last.
|
| 178 |
+
"""
|
| 179 |
+
files = list(self.find_config_files(pattern, *groups).items())
|
| 180 |
+
|
| 181 |
+
def fcmp(a):
|
| 182 |
+
return a[0][:-4]
|
| 183 |
+
files.sort(key=fcmp)
|
| 184 |
+
for group in groups:
|
| 185 |
+
prefix = group.replace("/", os.sep)
|
| 186 |
+
for filename, cd in files:
|
| 187 |
+
filename = join(prefix, filename)
|
| 188 |
+
ffn = join(cd.name, filename)
|
| 189 |
+
logger.debug("Loading %s...", ffn)
|
| 190 |
+
s = codecs.open(ffn, encoding='utf-8').read()
|
| 191 |
+
loader(s, cd, filename)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
IGNORE_TIMES = False
|
| 195 |
+
MODIFY_WINDOW = 2
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def must_make(src, target):
|
| 199 |
+
"returns True if src is newer than target"
|
| 200 |
+
try:
|
| 201 |
+
src_st = os.stat(src)
|
| 202 |
+
src_mt = src_st.st_mtime
|
| 203 |
+
except OSError:
|
| 204 |
+
# self.error("os.stat() failed: ",e)
|
| 205 |
+
return False
|
| 206 |
+
|
| 207 |
+
try:
|
| 208 |
+
target_st = os.stat(target)
|
| 209 |
+
target_mt = target_st.st_mtime
|
| 210 |
+
except OSError:
|
| 211 |
+
# self.error("os.stat() failed: %s", e)
|
| 212 |
+
return True
|
| 213 |
+
|
| 214 |
+
if src_mt - target_mt > MODIFY_WINDOW:
|
| 215 |
+
return True
|
| 216 |
+
return False
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def make_dummy_messages_file(src_fn, messages):
|
| 220 |
+
"""
|
| 221 |
+
Write a dummy `.py` source file containing
|
| 222 |
+
translatable messages that getmessages will find.
|
| 223 |
+
"""
|
| 224 |
+
raise Exception("Never used")
|
| 225 |
+
target_fn = src_fn + '.py'
|
| 226 |
+
if not must_make(src_fn, target_fn):
|
| 227 |
+
logger.debug("%s is up-to-date.", target_fn)
|
| 228 |
+
return
|
| 229 |
+
try:
|
| 230 |
+
f = file(target_fn, 'w')
|
| 231 |
+
except IOError as e:
|
| 232 |
+
logger.warning("Could not write file %s : %s", target_fn, e)
|
| 233 |
+
return
|
| 234 |
+
f.write("# this file is generated by Lino\n")
|
| 235 |
+
f.write("from django.utils.translation import ugettext\n")
|
| 236 |
+
for m in messages:
|
| 237 |
+
f.write("ugettext(%r)\n" % m)
|
| 238 |
+
f.close()
|
| 239 |
+
logger.info("Wrote %d dummy messages to %s.", len(messages), target_fn)
|
code/train/Python/0070419_config.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
module: radmin.confg
|
| 3 |
+
Config file logic
|
| 4 |
+
|
| 5 |
+
Created by Ian Starnes 2007-11-27
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
class Config(object):
|
| 10 |
+
"""The Config class."""
|
| 11 |
+
def __init__(self, filename):
|
| 12 |
+
self.filename = filename
|
| 13 |
+
self._items = {}
|
| 14 |
+
execfile(filename, globals(), self._items)
|
| 15 |
+
|
| 16 |
+
def add(self, key, value):
|
| 17 |
+
self._items[key] = value
|
| 18 |
+
|
| 19 |
+
def has_key(self, key):
|
| 20 |
+
return self._items.has_key(key)
|
| 21 |
+
|
| 22 |
+
def get(self, field, default=None, required=False):
|
| 23 |
+
"returns the field as a string"
|
| 24 |
+
if self._items.has_key(field):
|
| 25 |
+
return self._items[field]
|
| 26 |
+
if required:
|
| 27 |
+
raise Exception("missing required field(%s)!" % field)
|
| 28 |
+
return default
|
| 29 |
+
|
| 30 |
+
class IniFile(object):
|
| 31 |
+
"""docstring for IniFile"""
|
| 32 |
+
SYNTAX_COMMENTS = ['#', ';']
|
| 33 |
+
SYNTAX_DELIMITER = '='
|
| 34 |
+
|
| 35 |
+
def __init__(self, filename):
|
| 36 |
+
self.filename = filename
|
| 37 |
+
self.sections = []
|
| 38 |
+
self._section_dict = {}
|
| 39 |
+
|
| 40 |
+
def hasSection(self, section):
|
| 41 |
+
return section in self.sections
|
| 42 |
+
|
| 43 |
+
def getSection(self, section):
|
| 44 |
+
if section not in self.sections:
|
| 45 |
+
self._section_dict[section] = {}
|
| 46 |
+
self.sections.append(section)
|
| 47 |
+
return self._section_dict[section]
|
| 48 |
+
|
| 49 |
+
def load(self):
|
| 50 |
+
f = open(self.filename, 'r')
|
| 51 |
+
section = self.getSection("")
|
| 52 |
+
quote = None
|
| 53 |
+
key = None
|
| 54 |
+
value = None
|
| 55 |
+
for line in f.readlines():
|
| 56 |
+
# if inside a quote read anything until end quote
|
| 57 |
+
if quote != None:
|
| 58 |
+
new_value = line.strip()
|
| 59 |
+
if new_value[-1] == quote:
|
| 60 |
+
value += new_value[:-1]
|
| 61 |
+
quote = None
|
| 62 |
+
section[key] = value
|
| 63 |
+
continue
|
| 64 |
+
value += new_value
|
| 65 |
+
|
| 66 |
+
# ignore comments or empty lines
|
| 67 |
+
if line[0] in IniFile.SYNTAX_COMMENTS or len(line) < 3:
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
# check for new section
|
| 71 |
+
if line[0] == '[':
|
| 72 |
+
section = self.getSection(line[1:line.find("]")])
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
# check for delimiter
|
| 76 |
+
if line.count(IniFile.SYNTAX_DELIMITER) >= 1:
|
| 77 |
+
#key, value = line.split('=')
|
| 78 |
+
pos = line.find(IniFile.SYNTAX_DELIMITER)
|
| 79 |
+
key = line[:pos].strip()
|
| 80 |
+
value = line[pos+len(IniFile.SYNTAX_DELIMITER):].strip()
|
| 81 |
+
if value[0] == '"':
|
| 82 |
+
quote = '"'
|
| 83 |
+
elif value[0] == "'":
|
| 84 |
+
quote = "'"
|
| 85 |
+
|
| 86 |
+
# parse the string
|
| 87 |
+
if quote != None:
|
| 88 |
+
if value[-1] == quote:
|
| 89 |
+
value = value[1:-1]
|
| 90 |
+
quote = None
|
| 91 |
+
else:
|
| 92 |
+
value = value[1:]
|
| 93 |
+
continue
|
| 94 |
+
else:
|
| 95 |
+
if value.count('.') == 1:
|
| 96 |
+
flt = value.split('.')
|
| 97 |
+
if flt[0].isdigit() and flt[1].isdigit():
|
| 98 |
+
value = float(value)
|
| 99 |
+
elif value.isdigit():
|
| 100 |
+
value = int(value)
|
| 101 |
+
section[key] = value
|
| 102 |
+
|
| 103 |
+
else:
|
| 104 |
+
print "no delimiter found in line: %s" % line
|
| 105 |
+
|
| 106 |
+
def _write(self, writer, comment=None):
|
| 107 |
+
f = writer
|
| 108 |
+
if comment:
|
| 109 |
+
f.write("# %s\n\n" % self.comment)
|
| 110 |
+
for name in self.sections:
|
| 111 |
+
section = self._section_dict[name]
|
| 112 |
+
if len(section) > 0:
|
| 113 |
+
f.write("[%s]\n" % name)
|
| 114 |
+
sorted_keys = section.keys()
|
| 115 |
+
sorted_keys.sort()
|
| 116 |
+
for key in sorted_keys:
|
| 117 |
+
value = section[key]
|
| 118 |
+
if type(value) is str:
|
| 119 |
+
if value.count('\n') > 0 or value.count('"') > 0:
|
| 120 |
+
f.write('%s="""%s"""\n\n' % (key, value))
|
| 121 |
+
else:
|
| 122 |
+
f.write('%s="%s"\n' % (key, value))
|
| 123 |
+
else:
|
| 124 |
+
f.write('%s=%s\n' % (key, value))
|
| 125 |
+
f.write("\n")
|
| 126 |
+
|
| 127 |
+
def save(self, comment=None):
|
| 128 |
+
f = open(self.filename, 'w')
|
| 129 |
+
self._write(f, comment)
|
| 130 |
+
f.close()
|
| 131 |
+
|
| 132 |
+
def __str__(self):
|
| 133 |
+
import StringIO
|
| 134 |
+
writer = StringIO.StringIO()
|
| 135 |
+
self._write(writer)
|
| 136 |
+
out = writer.getvalue()
|
| 137 |
+
writer.close()
|
| 138 |
+
return out
|
| 139 |
+
|
| 140 |
+
def asHTML(self):
|
| 141 |
+
"""generate html output"""
|
| 142 |
+
import StringIO, cgi
|
| 143 |
+
f = StringIO.StringIO()
|
| 144 |
+
f.write("<div class='ini'>\n")
|
| 145 |
+
for name in self.sections:
|
| 146 |
+
section = self._section_dict[name]
|
| 147 |
+
if len(section) > 0:
|
| 148 |
+
error_summary = False
|
| 149 |
+
if name.lower().count("error") > 0:
|
| 150 |
+
error_summary = True
|
| 151 |
+
f.write("<div class='ini_section'>\n")
|
| 152 |
+
|
| 153 |
+
count = 0
|
| 154 |
+
f.write("<h3>%s</h3>\n" % name)
|
| 155 |
+
if error_summary:
|
| 156 |
+
f.write("<div class='ini_errors'>\n")
|
| 157 |
+
sorted_keys = section.keys()
|
| 158 |
+
sorted_keys.sort()
|
| 159 |
+
for key in sorted_keys:
|
| 160 |
+
value = section[key]
|
| 161 |
+
if not error_summary:
|
| 162 |
+
f.write("<span class='ini_key'>%s:</span> <span class='ini_value'>%s</span>\n" %(key, value))
|
| 163 |
+
else:
|
| 164 |
+
f.write("<span class='ini_error'>%s</span>\n" % cgi.escape(value))
|
| 165 |
+
count += 1
|
| 166 |
+
if count == 3 or error_summary:
|
| 167 |
+
f.write("<br />\n")
|
| 168 |
+
count = 0
|
| 169 |
+
if error_summary:
|
| 170 |
+
f.write("</div>\n")
|
| 171 |
+
f.write("</div>\n")
|
| 172 |
+
f.write("</div>\n")
|
| 173 |
+
content = f.getvalue()
|
| 174 |
+
f.close()
|
| 175 |
+
return content
|
| 176 |
+
|
| 177 |
+
|